4 Commits

Author SHA1 Message Date
Johan LEROY
77f00268ec release: @johanleroy/git-arboretum 1.3.0
Some checks failed
CI / Build & test (Node 22) (push) Successful in 9m52s
CI / Build & test (Node 24) (push) Successful in 9m45s
Release / Publish to Gitea npm registry (push) Successful in 9m41s
CI / Pack & boot smoke (Node 22) (push) Failing after 4m59s
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 14:46:03 +02:00
Johan LEROY
fa9952bc5c feat: découverte automatique des dépôts git (scan + montrer/cacher)
Scan borné du système de fichiers (racines configurables, défaut home ; profondeur/nombre/timeout bornés ; symlinks non suivis ; exclusions node_modules/dotdirs) qui auto-enregistre les nouveaux dépôts. Insertion atomique ON CONFLICT DO NOTHING (idempotence + anti-résurrection d'un dépôt masqué + anti-course). Scan au démarrage + bouton manuel + re-scan périodique (RepoDiscoveryService, démarré dans runDaemon). Colonne repos.hidden : masquer = conservé en DB mais exclu du dashboard et jamais ré-ajouté ; supprimer = re-découvrable. UI : bouton œil par dépôt + bascule afficher-les-masqués sur le dashboard, section Découverte dans les Réglages (racines + intervalle, allow-list stricte). Robustesse : listAllWorktrees tolère l'échec git par dépôt ; flag --no-discover (escape hatch + hermétisme des acceptations).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 14:45:12 +02:00
Johan LEROY
940ccffeab chore(deps): @fastify/static ^8 → ^9
Mise à niveau majeure du plugin de service statique (déjà installée dans l'arbre de travail, build + 253 tests verts).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 14:44:52 +02:00
Johan LEROY
8cce1dc1e4 feat: onglets Réglages & Aide + icône Gitea
Réglages : préférences (langue, notifications push + test), gestion complète des tokens d'accès (liste/création/révocation, garde anti lock-out sur le dernier token), URL Gitea configurable, infos serveur en lecture seule (port/bind/origines/VAPID + flags CLI). Aide : documentation bilingue EN/FR de toutes les fonctionnalités, avec recherche. Icône Gitea (lien externe) dans la nav (sidebar + MoreSheet mobile).

Backend : routes /api/v1/auth/tokens (GET/POST/DELETE) + tokenId dans /me ; routes/settings.ts (GET/PATCH, allow-list stricte gitea_url, aucun secret exposé, URL validée http/https anti-XSS) ; AuthService.listTokens/revokeToken (transaction). Front : NavItem gère les liens externes, nav primaire/secondaire, store settings, vues SettingsView/HelpView.

236 tests verts (+15 nouveaux : auth-tokens, settings-routes).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 14:16:53 +02:00
44 changed files with 2312 additions and 206 deletions

173
package-lock.json generated
View File

@@ -720,9 +720,9 @@
}
},
"node_modules/@fastify/static": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/@fastify/static/-/static-8.3.0.tgz",
"integrity": "sha512-yKxviR5PH1OKNnisIzZKmgZSus0r2OZb8qCSbqmw34aolT4g3UlzYfeBRym+HJ1J471CR8e2ldNub4PubD1coA==",
"version": "9.1.3",
"resolved": "https://registry.npmjs.org/@fastify/static/-/static-9.1.3.tgz",
"integrity": "sha512-aXrYtsiryLhRxRNaxNqsn7FUISeb7rB9q4eHUPIot5aeQBLNahnz1m6thzm7JWC1poSGXS9XrX8DvuMivp2hkQ==",
"funding": [
{
"type": "github",
@@ -737,10 +737,10 @@
"dependencies": {
"@fastify/accept-negotiator": "^2.0.0",
"@fastify/send": "^4.0.0",
"content-disposition": "^0.5.4",
"content-disposition": "^1.0.1",
"fastify-plugin": "^5.0.0",
"fastq": "^1.17.1",
"glob": "^11.0.0"
"glob": "^13.0.0"
}
},
"node_modules/@fastify/websocket": {
@@ -839,15 +839,6 @@
"url": "https://github.com/sponsors/kazupon"
}
},
"node_modules/@isaacs/cliui": {
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-9.0.0.tgz",
"integrity": "sha512-AokJm4tuBHillT+FpMtxQ60n8ObyXBatq7jD2/JA9dxbDDokKQm8KMht5ibGzLVU9IJDIKK4TPKgMHEYMn3lMg==",
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=18"
}
},
"node_modules/@johanleroy/git-arboretum": {
"resolved": "packages/server",
"link": true
@@ -2551,15 +2542,16 @@
"peer": true
},
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
"integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
"integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",
"license": "MIT",
"dependencies": {
"safe-buffer": "5.2.1"
},
"engines": {
"node": ">= 0.6"
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/cookie": {
@@ -2590,20 +2582,6 @@
"url": "https://github.com/sponsors/mesqueeb"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
"license": "MIT",
"dependencies": {
"path-key": "^3.1.0",
"shebang-command": "^2.0.0",
"which": "^2.0.1"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
@@ -2979,22 +2957,6 @@
"node": ">=20"
}
},
"node_modules/foreground-child": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",
"integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==",
"license": "ISC",
"dependencies": {
"cross-spawn": "^7.0.6",
"signal-exit": "^4.0.1"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/fs-constants": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
@@ -3023,24 +2985,17 @@
"license": "MIT"
},
"node_modules/glob": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/glob/-/glob-11.1.0.tgz",
"integrity": "sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw==",
"deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
"version": "13.0.6",
"resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz",
"integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==",
"license": "BlueOak-1.0.0",
"dependencies": {
"foreground-child": "^3.3.1",
"jackspeak": "^4.1.1",
"minimatch": "^10.1.1",
"minipass": "^7.1.2",
"package-json-from-dist": "^1.0.0",
"path-scurry": "^2.0.0"
},
"bin": {
"glob": "dist/esm/bin.mjs"
"minimatch": "^10.2.2",
"minipass": "^7.1.3",
"path-scurry": "^2.0.2"
},
"engines": {
"node": "20 || >=22"
"node": "18 || 20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
@@ -3154,27 +3109,6 @@
"url": "https://github.com/sponsors/mesqueeb"
}
},
"node_modules/isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"license": "ISC"
},
"node_modules/jackspeak": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.2.3.tgz",
"integrity": "sha512-ykkVRwrYvFm1nb2AJfKKYPr0emF6IiXDYUaFx4Zn9ZuIH7MrzEZ3sD5RlqGXNRpHtvUHJyOnCEFxOlNDtGo7wg==",
"license": "BlueOak-1.0.0",
"dependencies": {
"@isaacs/cliui": "^9.0.0"
},
"engines": {
"node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/jiti": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
@@ -3720,12 +3654,6 @@
"wrappy": "1"
}
},
"node_modules/package-json-from-dist": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
"license": "BlueOak-1.0.0"
},
"node_modules/path-browserify": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz",
@@ -3733,15 +3661,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/path-scurry": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz",
@@ -4193,27 +4112,6 @@
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"license": "ISC"
},
"node_modules/shebang-command": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
"license": "MIT",
"dependencies": {
"shebang-regex": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/shebang-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/siginfo": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
@@ -4221,18 +4119,6 @@
"dev": true,
"license": "ISC"
},
"node_modules/signal-exit": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
"integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
"license": "ISC",
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/simple-concat": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
@@ -4908,21 +4794,6 @@
"node": ">= 16"
}
},
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
"license": "ISC",
"dependencies": {
"isexe": "^2.0.0"
},
"bin": {
"node-which": "bin/node-which"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/why-is-node-running": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
@@ -4969,7 +4840,7 @@
},
"packages/server": {
"name": "@johanleroy/git-arboretum",
"version": "1.2.0",
"version": "1.3.0",
"bundleDependencies": [
"@arboretum/shared"
],
@@ -4977,7 +4848,7 @@
"dependencies": {
"@arboretum/shared": "0.1.0",
"@fastify/cookie": "^11.0.0",
"@fastify/static": "^8.0.0",
"@fastify/static": "^9.0.0",
"@fastify/websocket": "^11.0.0",
"@homebridge/node-pty-prebuilt-multiarch": "^0.13.0",
"@xterm/headless": "^6.0.0",

View File

@@ -1,6 +1,6 @@
{
"name": "@johanleroy/git-arboretum",
"version": "1.2.0",
"version": "1.3.0",
"description": "Self-hosted web dashboard for git worktrees and the Claude Code sessions running on them",
"license": "MIT",
"type": "module",
@@ -53,7 +53,7 @@
"dependencies": {
"@arboretum/shared": "0.1.0",
"@fastify/cookie": "^11.0.0",
"@fastify/static": "^8.0.0",
"@fastify/static": "^9.0.0",
"@fastify/websocket": "^11.0.0",
"@homebridge/node-pty-prebuilt-multiarch": "^0.13.0",
"@xterm/headless": "^6.0.0",

View File

@@ -23,7 +23,7 @@ const check = (name, ok, detail = '') => {
};
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-'));
const srv = spawn('node', [join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db')], {
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'],
});

View File

@@ -62,7 +62,7 @@ writeFileSync(
const srv = spawn(
'node',
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', claudeHome],
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', claudeHome, '--no-discover'],
{ env: { ...process.env, ARBORETUM_LOG: 'warn', PATH: `${fakeBin}:${process.env.PATH}` }, stdio: ['ignore', 'pipe', 'pipe'] },
);
let srvOut = '';

View File

@@ -36,7 +36,7 @@ git('commit', '-m', 'init');
const srv = spawn(
'node',
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude')],
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
);
let srvOut = '';

View File

@@ -27,7 +27,7 @@ const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p4-'));
const srv = spawn(
'node',
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude')],
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
);
let srvOut = '';

View File

@@ -36,7 +36,7 @@ git('commit', '-m', 'init');
const srv = spawn(
'node',
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude')],
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
);
let srvOut = '';

View File

@@ -11,6 +11,7 @@ import { AuthService, LoginRateLimiter, type AuthContext } from './auth/service.
import { PtyManager } from './core/pty-manager.js';
import { DiscoveryService } from './core/discovery-service.js';
import { WorktreeManager } from './core/worktree-manager.js';
import { RepoDiscoveryService } from './core/repo-discovery.js';
import { GroupManager } from './core/group-manager.js';
import { PushService } from './core/push-service.js';
import { registerAuthRoutes } from './routes/auth.js';
@@ -19,6 +20,7 @@ import { registerRepoRoutes } from './routes/repos.js';
import { registerGroupRoutes } from './routes/groups.js';
import { registerWorktreeRoutes } from './routes/worktrees.js';
import { registerPushRoutes } from './routes/push.js';
import { registerSettingsRoutes } from './routes/settings.js';
import { registerFsRoutes } from './routes/fs.js';
import { registerWsGateway } from './ws/gateway.js';
@@ -36,6 +38,7 @@ export interface AppBundle {
auth: AuthService;
manager: PtyManager;
discovery: DiscoveryService;
repoDiscovery: RepoDiscoveryService;
worktrees: WorktreeManager;
groups: GroupManager;
push: PushService;
@@ -53,6 +56,8 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
sessionsDir: config.claudeSessionsDir,
});
const worktrees = new WorktreeManager(db, manager, discovery);
// Démarré dans runDaemon() (jamais ici) → le scan ne tourne pas pendant les tests qui appellent buildApp.
const repoDiscovery = new RepoDiscoveryService(db, worktrees);
const groups = new GroupManager(db);
void app.register(fastifyCookie);
@@ -94,10 +99,11 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
registerAuthRoutes(app, auth, limiter, serverVersion);
registerSessionRoutes(app, manager, discovery);
registerRepoRoutes(app, worktrees);
registerRepoRoutes(app, worktrees, db);
registerGroupRoutes(app, groups);
registerWorktreeRoutes(app, worktrees);
registerPushRoutes(app, push);
registerSettingsRoutes(app, db, config, serverVersion, push);
registerFsRoutes(app);
// La route websocket doit être déclarée APRÈS le chargement du plugin (contexte
// encapsulé) — sinon le handler reçoit la signature REST (request, reply).
@@ -117,5 +123,5 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
});
}
return { app, auth, manager, discovery, worktrees, groups, push };
return { app, auth, manager, discovery, repoDiscovery, worktrees, groups, push };
}

View File

@@ -35,11 +35,60 @@ export class AuthService {
}
createToken(label: string): string {
return this.createTokenRecord(label).token;
}
/** Comme createToken mais renvoie aussi l'id (pour l'API de gestion des tokens). */
createTokenRecord(label: string): { id: string; token: string } {
const id = randomUUID();
const raw = `arb_${randomBytes(24).toString('hex')}`;
this.db
.prepare('INSERT INTO auth_tokens (id, label, token_hash, created_at) VALUES (?, ?, ?, ?)')
.run(randomUUID(), label, sha256(raw), new Date().toISOString());
return raw;
.run(id, label, sha256(raw), new Date().toISOString());
return { id, token: raw };
}
/** Tokens actifs (non révoqués), du plus ancien au plus récent. Ne renvoie JAMAIS le hash. */
listTokens(): Array<{ id: string; label: string; createdAt: string; lastUsedAt: string | null }> {
return this.db
.prepare(
'SELECT id, label, created_at AS createdAt, last_used_at AS lastUsedAt FROM auth_tokens WHERE revoked_at IS NULL ORDER BY created_at',
)
.all() as Array<{ id: string; label: string; createdAt: string; lastUsedAt: string | null }>;
}
/** Nombre de tokens actifs (non révoqués). */
countActiveTokens(): number {
return (this.db.prepare('SELECT COUNT(*) AS n FROM auth_tokens WHERE revoked_at IS NULL').get() as { n: number }).n;
}
/**
* Révoque un token. Refuse de révoquer le DERNIER token actif (sinon lock-out total) → 'last'.
* 'ok' = révoqué ; 'not_found' = id inconnu ou déjà révoqué.
*/
revokeToken(id: string): 'ok' | 'last' | 'not_found' {
// Transaction : le check « dernier token » et l'UPDATE doivent être atomiques (garde
// anti lock-out robuste, même si un refactor futur introduisait de la concurrence).
this.db.exec('BEGIN IMMEDIATE');
try {
const row = this.db.prepare('SELECT id FROM auth_tokens WHERE id = ? AND revoked_at IS NULL').get(id) as
| { id: string }
| undefined;
let result: 'ok' | 'last' | 'not_found';
if (!row) {
result = 'not_found';
} else if (this.countActiveTokens() <= 1) {
result = 'last';
} else {
this.db.prepare('UPDATE auth_tokens SET revoked_at = ? WHERE id = ?').run(new Date().toISOString(), id);
result = 'ok';
}
this.db.exec('COMMIT');
return result;
} catch (err) {
this.db.exec('ROLLBACK');
throw err;
}
}
verifyRawToken(raw: string): AuthContext | null {

View File

@@ -17,6 +17,8 @@ export interface Config {
claudeSessionsDir: string;
/** sujet VAPID des notifications Web Push (mailto: ou URL). */
vapidContact: string;
/** découverte auto des repos au démarrage + périodique (désactivable via --no-discover). */
autoDiscover: boolean;
}
export function loadConfig(argv = process.argv.slice(2)): Config {
@@ -33,6 +35,8 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
'claude-home': { type: 'string' },
// sujet VAPID des notifications push (contact requis par la spec Web Push).
'vapid-contact': { type: 'string' },
// désactive la découverte auto des repos (boot + périodique) — utilisé par les tests d'acceptation.
'no-discover': { type: 'boolean', default: false },
},
strict: true,
});
@@ -60,5 +64,6 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
claudeProjectsDir: join(claudeHome, 'projects'),
claudeSessionsDir: join(claudeHome, 'sessions'),
vapidContact: values['vapid-contact'] ?? 'mailto:arboretum@localhost',
autoDiscover: !(values['no-discover'] ?? false),
};
}

View File

@@ -0,0 +1,42 @@
// Planificateur de la découverte auto des repos : scan au démarrage + re-scan périodique.
// Calqué sur DiscoveryService (sessions) — start()/stop() avec timer .unref(). Démarré depuis
// runDaemon() UNIQUEMENT (jamais buildApp), ce qui isole naturellement les tests vitest du scan.
// Lui-même sans état : il lit les racines/l'intervalle dans `settings` et délègue à WorktreeManager.
import type { Db } from '../db/index.js';
import type { WorktreeManager } from './worktree-manager.js';
import { readScanIntervalMin, readScanRoots } from './scan-settings.js';
export class RepoDiscoveryService {
private timer: NodeJS.Timeout | null = null;
constructor(
private readonly db: Db,
private readonly worktrees: WorktreeManager,
) {}
start(): void {
if (this.timer) return;
void this.refresh(); // scan initial asynchrone : ne bloque pas le boot
const intervalMin = readScanIntervalMin(this.db);
if (intervalMin > 0) {
this.timer = setInterval(() => void this.refresh(), intervalMin * 60_000);
this.timer.unref(); // ne maintient pas le process en vie
}
}
stop(): void {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
/** Relit les racines (changement effectif sans redémarrage) et lance un scan. Ne lève jamais. */
private async refresh(): Promise<void> {
try {
await this.worktrees.discoverRepos({ roots: readScanRoots(this.db) });
} catch {
/* scan tolérant : une erreur ne doit pas tuer le timer */
}
}
}

View File

@@ -0,0 +1,92 @@
// Découverte auto des dépôts git : marche bornée du système de fichiers à la recherche de `.git`.
// Fonction PURE et tolérante (ne lève jamais) — testable isolément comme parseWorktreePorcelain.
// N'appelle JAMAIS git (détection par présence de `.git`) : la validation réelle (isRepo) et la
// résolution de default_branch se font paresseusement à l'enregistrement, pas par dépôt scanné.
import { readdir } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
export interface ScanLimits {
/** profondeur maximale de descente sous chaque racine (la racine = 0). */
maxDepth: number;
/** nombre maximal de repos retournés (garde-fou anti-explosion d'un FS pathologique). */
maxRepos: number;
/** noms de dossiers à ne jamais ouvrir (en plus des dotdirs, toujours exclus). */
excludeDirs?: Set<string>;
}
/** Dossiers jamais explorés : grosses arborescences sans repos racine, ou bruit de build. */
export const DEFAULT_EXCLUDE_DIRS = new Set<string>([
'node_modules',
'vendor',
'target',
'dist',
'build',
'.cache',
'venv',
'.venv',
'__pycache__',
]);
interface Frame {
dir: string;
depth: number;
}
/**
* Parcours itératif (pile explicite, jamais de récursion non bornée) des `roots`.
* Règles :
* - un dossier contenant `.git` (fichier OU dossier → couvre les worktrees liés) est un repo :
* on l'enregistre et on NE descend PAS dedans (sous-modules/worktrees imbriqués ignorés) ;
* - on n'empile que les vrais sous-dossiers (`d.isDirectory()`), donc les symlinks ne sont PAS
* suivis (anti-cycle + anti-sortie de racine), et on saute dotdirs + excludeDirs ;
* - bornes : `maxDepth`, `maxRepos`, et un éventuel `signal` (timeout global) ;
* - tolérance : un `readdir` qui échoue (EACCES/ENOENT) est ignoré, le scan continue ;
* - racine inexistante/illisible : ignorée silencieusement.
* Retourne les chemins absolus dédupliqués des racines de repos, et `truncated` si une borne a coupé.
*/
export async function scanForRepos(
roots: string[],
limits: ScanLimits,
signal?: AbortSignal,
): Promise<{ paths: string[]; truncated: boolean }> {
const excludes = limits.excludeDirs ?? DEFAULT_EXCLUDE_DIRS;
const found = new Set<string>();
const seen = new Set<string>(); // ceinture-bretelles anti-cycle (chemins déjà visités)
let truncated = false;
// pile partagée entre toutes les racines : un seul plafond global maxRepos.
const stack: Frame[] = [];
for (const root of roots) stack.push({ dir: root, depth: 0 });
while (stack.length > 0) {
if (signal?.aborted || found.size >= limits.maxRepos) {
truncated = true;
break;
}
const { dir, depth } = stack.pop() as Frame;
if (seen.has(dir)) continue;
seen.add(dir);
// un repo : on l'enregistre et on ne descend pas.
if (existsSync(join(dir, '.git'))) {
found.add(dir);
continue;
}
if (depth >= limits.maxDepth) continue;
let entries;
try {
entries = await readdir(dir, { withFileTypes: true });
} catch {
continue; // EACCES/ENOENT/… : dossier ignoré, on poursuit
}
for (const e of entries) {
if (!e.isDirectory()) continue; // symlinks non suivis (isDirectory() est false pour un lien)
if (e.name.startsWith('.') || excludes.has(e.name)) continue;
stack.push({ dir: join(dir, e.name), depth: depth + 1 });
}
}
return { paths: [...found], truncated };
}

View File

@@ -0,0 +1,65 @@
// Réglages de la découverte auto des repos, persistés dans la table `settings` (clé/valeur).
// Frontière de sécurité : ces clés sont NON sensibles et n'entrent dans l'allow-list du PATCH
// /api/v1/settings que via les validateurs ci-dessous. Aucun secret ne transite par ici.
import { homedir } from 'node:os';
import { getSetting } from '../db/index.js';
import type { Db } from '../db/index.js';
import { isSafeAbsolutePath } from './git.js';
export const SCAN_ROOTS_KEY = 'scan_roots';
export const SCAN_INTERVAL_KEY = 'scan_interval_min';
/** Intervalle par défaut du re-scan périodique (minutes). 0 = désactivé. */
export const DEFAULT_SCAN_INTERVAL_MIN = 5;
/** Borne haute de l'intervalle (24 h) et nombre maximal de racines. */
export const MAX_SCAN_INTERVAL_MIN = 1440;
export const MAX_SCAN_ROOTS = 16;
/** Racines à scanner. Défaut : le home de l'utilisateur. Lecture tolérante (JSON malformé → défaut). */
export function readScanRoots(db: Db): string[] {
const raw = getSetting(db, SCAN_ROOTS_KEY);
if (!raw) return [homedir()];
const parsed = normalizeScanRoots(safeParse(raw));
return parsed && parsed.length > 0 ? parsed : [homedir()];
}
/** Intervalle périodique en minutes (0 = désactivé). Défaut DEFAULT_SCAN_INTERVAL_MIN. */
export function readScanIntervalMin(db: Db): number {
const raw = getSetting(db, SCAN_INTERVAL_KEY);
if (raw === null) return DEFAULT_SCAN_INTERVAL_MIN;
const n = Number(raw);
return Number.isInteger(n) && n >= 0 && n <= MAX_SCAN_INTERVAL_MIN ? n : DEFAULT_SCAN_INTERVAL_MIN;
}
/**
* Valide/normalise une liste de racines : tableau de chemins absolus normalisés (isSafeAbsolutePath),
* jamais `/` (scan catastrophique), dédupliqués, ≤ MAX_SCAN_ROOTS. Retourne null si invalide (⇒ 400).
* Une liste vide est valide (revient au défaut côté lecture).
*/
export function normalizeScanRoots(raw: unknown): string[] | null {
if (!Array.isArray(raw)) return null;
if (raw.length > MAX_SCAN_ROOTS) return null;
const out: string[] = [];
for (const item of raw) {
if (typeof item !== 'string') return null;
const p = item.trim();
if (!isSafeAbsolutePath(p) || p === '/') return null;
if (!out.includes(p)) out.push(p);
}
return out;
}
/** Valide un intervalle (entier 0MAX_SCAN_INTERVAL_MIN). Retourne null si invalide. */
export function normalizeScanIntervalMin(raw: unknown): number | null {
if (typeof raw !== 'number' || !Number.isInteger(raw)) return null;
if (raw < 0 || raw > MAX_SCAN_INTERVAL_MIN) return null;
return raw;
}
function safeParse(raw: string): unknown {
try {
return JSON.parse(raw);
} catch {
return null;
}
}

View File

@@ -7,6 +7,7 @@ import { randomUUID } from 'node:crypto';
import { basename, dirname, join, resolve } from 'node:path';
import { existsSync } from 'node:fs';
import type {
DiscoverReposResponse,
HookRunResult,
PostCreateHook,
RepoSummary,
@@ -17,6 +18,7 @@ import type {
import type { Db } from '../db/index.js';
import type { PtyManager } from './pty-manager.js';
import { DiscoveryService, mergeSessions } from './discovery-service.js';
import { scanForRepos } from './repo-scanner.js';
import { preTrustProject } from './claude-trust.js';
import {
addWorktree,
@@ -35,6 +37,10 @@ import {
const FACTS_TTL_MS = 2500;
const HOOK_TIMEOUT_MS = 5 * 60_000;
const HOOK_OUTPUT_MAX = 64 * 1024;
// Bornes du scan de découverte (anti-explosion sur un home volumineux).
const SCAN_MAX_DEPTH = 6;
const SCAN_MAX_REPOS = 2000;
const SCAN_TIMEOUT_MS = 30_000;
interface RepoRow {
id: string;
@@ -44,6 +50,7 @@ interface RepoRow {
post_create_hooks: string;
pre_trust: number;
created_at: string;
hidden: number;
}
export interface WorktreeManagerEvents {
@@ -96,6 +103,8 @@ function runHook(cwd: string, hook: PostCreateHook): Promise<HookRunResult> {
export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
private readonly factsCache = new Map<string, { facts: Array<{ w: ParsedWorktree; status: WorktreeGitStatus }>; at: number }>();
private readonly locks = new Map<string, Promise<unknown>>();
/** Scan de découverte en cours : coalesce boot + bouton + périodique sur un seul scan. */
private scanInFlight: Promise<DiscoverReposResponse> | null = null;
constructor(
private readonly db: Db,
@@ -121,6 +130,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
preTrust: row.pre_trust === 1,
createdAt: row.created_at,
valid: await isRepo(row.path),
hidden: row.hidden === 1,
};
}
@@ -143,24 +153,35 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
post_create_hooks: JSON.stringify(opts.postCreateHooks ?? []),
pre_trust: opts.preTrust ? 1 : 0,
created_at: new Date().toISOString(),
hidden: 0,
};
try {
this.db
.prepare('INSERT INTO repos (id, path, label, default_branch, post_create_hooks, pre_trust, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
.run(row.id, row.path, row.label, row.default_branch, row.post_create_hooks, row.pre_trust, row.created_at);
.prepare('INSERT INTO repos (id, path, label, default_branch, post_create_hooks, pre_trust, created_at, hidden) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
.run(row.id, row.path, row.label, row.default_branch, row.post_create_hooks, row.pre_trust, row.created_at, row.hidden);
} catch (err) {
// Course possible avec un scan concurrent qui aurait inséré le même path entre le SELECT
// d'unicité et cet INSERT (contrainte UNIQUE sur path) → on rend le même 409 explicite.
if (String((err as { code?: string }).code).includes('CONSTRAINT')) {
throw httpError(409, 'ALREADY_REGISTERED', 'This repository is already registered');
}
throw err;
}
const summary = await this.rowToSummary(row);
this.emit('repo_update', summary);
return summary;
}
async updateRepo(id: string, patch: { label?: string; postCreateHooks?: PostCreateHook[]; preTrust?: boolean }): Promise<RepoSummary> {
async updateRepo(id: string, patch: { label?: string; postCreateHooks?: PostCreateHook[]; preTrust?: boolean; hidden?: boolean }): Promise<RepoSummary> {
const row = this.getRepoRow(id);
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
if (patch.label !== undefined) row.label = patch.label.trim() || row.label;
if (patch.postCreateHooks !== undefined) row.post_create_hooks = JSON.stringify(patch.postCreateHooks);
if (patch.preTrust !== undefined) row.pre_trust = patch.preTrust ? 1 : 0;
if (patch.hidden !== undefined) row.hidden = patch.hidden ? 1 : 0;
this.db
.prepare('UPDATE repos SET label = ?, post_create_hooks = ?, pre_trust = ? WHERE id = ?')
.run(row.label, row.post_create_hooks, row.pre_trust, id);
.prepare('UPDATE repos SET label = ?, post_create_hooks = ?, pre_trust = ?, hidden = ? WHERE id = ?')
.run(row.label, row.post_create_hooks, row.pre_trust, row.hidden, id);
const summary = await this.rowToSummary(row);
this.emit('repo_update', summary);
return summary;
@@ -174,6 +195,53 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
return true;
}
/**
* Découvre les repos git sous `roots` et auto-enregistre les NOUVEAUX (path absent de la DB).
* Idempotent et anti-résurrection : un path déjà présent — visible OU masqué — n'est jamais
* réécrit (INSERT ... ON CONFLICT DO NOTHING). Les scans concurrents sont coalescés. Tolérant :
* ne lève pas (le scanner avale les erreurs FS). N'appelle aucun git pendant le scan
* (default_branch=NULL, résolu paresseusement par rowToSummary à l'affichage).
*/
discoverRepos(opts: { roots: string[]; maxDepth?: number; maxRepos?: number }): Promise<DiscoverReposResponse> {
if (this.scanInFlight) return this.scanInFlight;
this.scanInFlight = this.runDiscovery(opts).finally(() => {
this.scanInFlight = null;
});
return this.scanInFlight;
}
private async runDiscovery(opts: { roots: string[]; maxDepth?: number; maxRepos?: number }): Promise<DiscoverReposResponse> {
const t0 = Date.now();
const { paths, truncated } = await scanForRepos(
opts.roots,
{ maxDepth: opts.maxDepth ?? SCAN_MAX_DEPTH, maxRepos: opts.maxRepos ?? SCAN_MAX_REPOS },
AbortSignal.timeout(SCAN_TIMEOUT_MS),
);
const insert = this.db.prepare(
`INSERT INTO repos (id, path, label, default_branch, post_create_hooks, pre_trust, created_at, hidden)
VALUES (?, ?, ?, NULL, '[]', 0, ?, 0) ON CONFLICT(path) DO NOTHING`,
);
let added = 0;
for (const path of paths) {
const row: RepoRow = {
id: randomUUID(),
path,
label: basename(path),
default_branch: null,
post_create_hooks: '[]',
pre_trust: 0,
created_at: new Date().toISOString(),
hidden: 0,
};
const res = insert.run(row.id, row.path, row.label, row.created_at);
if (res.changes === 1) {
added++;
this.emit('repo_update', await this.rowToSummary(row)); // nouveaux uniquement
}
}
return { scanned: paths.length, added, durationMs: Date.now() - t0, truncated };
}
// ---- worktrees ----
/** Sessions (managées + découvertes) dont le cwd correspond à ce chemin de worktree. */
@@ -214,8 +282,13 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
}
async listAllWorktrees(): Promise<WorktreeSummary[]> {
const rows = this.db.prepare('SELECT id FROM repos ORDER BY created_at ASC').all() as Array<{ id: string }>;
const lists = await Promise.all(rows.map((r) => this.listRepoWorktrees(r.id)));
// Les repos masqués sont exclus du dashboard : inutile de calculer leurs worktrees (sous-process
// git par repo). Le front charge paresseusement ceux d'un repo masqué via listRepoWorktrees
// quand l'utilisateur active « afficher les masqués ».
const rows = this.db.prepare('SELECT id FROM repos WHERE hidden = 0 ORDER BY created_at ASC').all() as Array<{ id: string }>;
// Tolérance par repo : avec la découverte auto, un repo douteux (git en échec, chemin disparu,
// permission) ne doit JAMAIS faire planter tout l'endpoint — il ne contribue alors aucun worktree.
const lists = await Promise.all(rows.map((r) => this.listRepoWorktrees(r.id).catch(() => [])));
return lists.flat();
}

View File

@@ -93,6 +93,12 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
CREATE INDEX idx_group_repos_repo ON group_repos(repo_id);
`,
},
{
// Découverte auto : un repo masqué reste en DB (exclu du dashboard) pour qu'un
// re-scan ne le ressuscite pas. hidden=1 = masqué.
id: 6,
sql: `ALTER TABLE repos ADD COLUMN hidden INTEGER NOT NULL DEFAULT 0;`,
},
];
export type Db = DatabaseSync;

View File

@@ -14,11 +14,12 @@ const pkg = JSON.parse(
/** Démarre le daemon : écoute HTTP, scan des sessions, drain propre au SIGTERM/SIGINT. */
export async function runDaemon(config: Config): Promise<void> {
const db = openDb(config.dbPath);
const { app, auth, manager, discovery } = buildApp(config, db, pkg.version);
const { app, auth, manager, discovery, repoDiscovery } = buildApp(config, db, pkg.version);
const bootstrapToken = auth.ensureBootstrapToken();
await app.listen({ port: config.port, host: config.bind });
discovery.start(); // scan initial + rafraîchissement périodique des sessions découvertes
if (config.autoDiscover) repoDiscovery.start(); // découverte auto des repos : scan au boot + re-scan périodique
const url = `http://${config.bind === '0.0.0.0' ? '127.0.0.1' : config.bind}:${config.port}`;
app.log.info(`Arboretum v${pkg.version}${url}`);
@@ -35,6 +36,7 @@ export async function runDaemon(config: Config): Promise<void> {
shuttingDown = true;
app.log.info(`${signal} received — draining sessions then exiting`);
discovery.stop();
repoDiscovery.stop();
manager.shutdown();
setTimeout(() => {
void app.close().then(() => process.exit(0));

View File

@@ -1,5 +1,12 @@
import type { FastifyInstance, FastifyRequest } from 'fastify';
import type { LoginRequest, LoginResponse, MeResponse } from '@arboretum/shared';
import type {
CreateTokenRequest,
CreateTokenResponse,
LoginRequest,
LoginResponse,
MeResponse,
TokensListResponse,
} from '@arboretum/shared';
import type { AuthService, LoginRateLimiter } from '../auth/service.js';
// Tailscale Serve / un reverse-proxy TLS posent x-forwarded-proto. On ne sert jamais
@@ -41,7 +48,12 @@ export function registerAuthRoutes(
});
app.get('/api/v1/auth/me', async (req, reply) => {
const res: MeResponse = { ok: true, tokenLabel: req.authContext?.label ?? 'unknown', serverVersion };
const res: MeResponse = {
ok: true,
tokenId: req.authContext?.tokenId ?? '',
tokenLabel: req.authContext?.label ?? 'unknown',
serverVersion,
};
return reply.send(res);
});
@@ -50,4 +62,35 @@ export function registerAuthRoutes(
void reply.clearCookie(auth.cookieName, { path: '/', secure: isHttpsRequest(req) });
return reply.send({ ok: true });
});
// ---- Gestion des tokens d'accès (onglet Réglages) ----
// Sous l'auth globale (preValidation). On ne renvoie jamais le hash ; la valeur en clair
// d'un nouveau token n'est exposée qu'une seule fois, à la création.
app.get('/api/v1/auth/tokens', async (req): Promise<TokensListResponse> => {
const current = req.authContext?.tokenId;
return { tokens: auth.listTokens().map((t) => ({ ...t, current: t.id === current })) };
});
app.post('/api/v1/auth/tokens', async (req, reply) => {
const body = req.body as Partial<CreateTokenRequest> | null;
const label = typeof body?.label === 'string' ? body.label.trim() : '';
if (label.length < 1 || label.length > 64) {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'label must be 164 characters' } });
}
const { id, token } = auth.createTokenRecord(label);
return reply.status(201).send({ id, label, token } satisfies CreateTokenResponse);
});
app.delete('/api/v1/auth/tokens/:id', async (req, reply) => {
const { id } = req.params as { id: string };
const result = auth.revokeToken(id);
if (result === 'not_found') {
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No active token with this id' } });
}
if (result === 'last') {
return reply.status(409).send({ error: { code: 'LAST_TOKEN', message: 'Cannot revoke the last active token' } });
}
// 200 + corps JSON (pas 204) : le mini-client REST du front parse toujours la réponse.
return reply.send({ ok: true });
});
}

View File

@@ -1,6 +1,8 @@
import type { FastifyInstance, FastifyReply } from 'fastify';
import type { CreateRepoRequest, RepoResponse, ReposListResponse, UpdateRepoRequest } from '@arboretum/shared';
import type { CreateRepoRequest, DiscoverReposResponse, RepoResponse, ReposListResponse, UpdateRepoRequest } from '@arboretum/shared';
import type { WorktreeManager } from '../core/worktree-manager.js';
import type { Db } from '../db/index.js';
import { readScanRoots } from '../core/scan-settings.js';
/** Mappe une erreur du manager (statusCode + code) vers une réponse REST normalisée. */
export function sendManagerError(reply: FastifyReply, err: unknown): FastifyReply {
@@ -8,9 +10,19 @@ export function sendManagerError(reply: FastifyReply, err: unknown): FastifyRepl
return reply.status(e.statusCode ?? 500).send({ error: { code: e.code ?? 'INTERNAL', message: e.message ?? 'Internal error' } });
}
export function registerRepoRoutes(app: FastifyInstance, wt: WorktreeManager): void {
export function registerRepoRoutes(app: FastifyInstance, wt: WorktreeManager, db: Db): void {
app.get('/api/v1/repos', async (): Promise<ReposListResponse> => ({ repos: await wt.listRepos() }));
// Scan manuel : découvre et auto-enregistre les repos sous les racines configurées (settings).
app.post('/api/v1/repos/discover', async (_req, reply) => {
try {
const res: DiscoverReposResponse = await wt.discoverRepos({ roots: readScanRoots(db) });
return reply.send(res);
} catch (err) {
return sendManagerError(reply, err);
}
});
app.post('/api/v1/repos', async (req, reply) => {
const body = req.body as Partial<CreateRepoRequest> | null;
if (!body || typeof body.path !== 'string') {
@@ -38,6 +50,7 @@ export function registerRepoRoutes(app: FastifyInstance, wt: WorktreeManager): v
...(body.label !== undefined ? { label: body.label } : {}),
...(body.postCreateHooks !== undefined ? { postCreateHooks: body.postCreateHooks } : {}),
...(body.preTrust !== undefined ? { preTrust: body.preTrust } : {}),
...(typeof body.hidden === 'boolean' ? { hidden: body.hidden } : {}),
});
const res: RepoResponse = { repo };
return reply.send(res);

View File

@@ -0,0 +1,96 @@
// Réglages exposés à l'UI (onglet Réglages). Frontière de sécurité CENTRALE : la table `settings`
// contient aussi des SECRETS (server_secret, vapid_private). Ces routes n'exposent QUE des champs
// non sensibles et n'écrivent QUE des clés explicitement allow-listées — jamais les secrets.
import type { FastifyInstance } from 'fastify';
import type { ServerInfo, SettingsResponse, UpdateSettingsRequest } from '@arboretum/shared';
import type { Config } from '../config.js';
import { type Db, getSetting, setSetting } from '../db/index.js';
import type { PushService } from '../core/push-service.js';
import {
SCAN_INTERVAL_KEY,
SCAN_ROOTS_KEY,
normalizeScanIntervalMin,
normalizeScanRoots,
readScanIntervalMin,
readScanRoots,
} from '../core/scan-settings.js';
// Clés de `settings` modifiables via l'API (allow-list stricte). Les secrets ne figurent JAMAIS ici.
const GITEA_URL_KEY = 'gitea_url';
/** Valide/normalise une URL Gitea : http(s) uniquement (anti-XSS sur le href de l'icône). */
function normalizeGiteaUrl(raw: string): string | null {
const trimmed = raw.trim();
if (trimmed === '') return null;
let url: URL;
try {
url = new URL(trimmed);
} catch {
return null;
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
return url.toString();
}
export function registerSettingsRoutes(
app: FastifyInstance,
db: Db,
config: Config,
serverVersion: string,
push: PushService,
): void {
// '' (effacé) est normalisé en null côté réponse.
const readGiteaUrl = (): string | null => getSetting(db, GITEA_URL_KEY) || null;
const serverInfo = (): ServerInfo => ({
version: serverVersion,
port: config.port,
bind: config.bind,
allowedOrigins: config.allowedOrigins,
dataDir: config.dataDir,
vapidPublicKey: push.publicKey() || null,
vapidContact: config.vapidContact,
});
const snapshot = (): SettingsResponse => ({
settings: {
giteaUrl: readGiteaUrl(),
scanRoots: readScanRoots(db),
scanIntervalMin: readScanIntervalMin(db),
},
server: serverInfo(),
});
app.get('/api/v1/settings', async (): Promise<SettingsResponse> => snapshot());
app.patch('/api/v1/settings', async (req, reply) => {
const body = (req.body as Partial<UpdateSettingsRequest> | null) ?? {};
if ('giteaUrl' in body) {
const v = body.giteaUrl;
if (v === null || v === '') {
setSetting(db, GITEA_URL_KEY, ''); // effacement
} else if (typeof v === 'string') {
const normalized = normalizeGiteaUrl(v);
if (!normalized) {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'giteaUrl must be a valid http(s) URL' } });
}
setSetting(db, GITEA_URL_KEY, normalized);
} else {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'giteaUrl must be a string or null' } });
}
}
if ('scanRoots' in body) {
const roots = normalizeScanRoots(body.scanRoots);
if (!roots) {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'scanRoots must be an array of ≤16 absolute, normalized paths (never "/")' } });
}
setSetting(db, SCAN_ROOTS_KEY, JSON.stringify(roots));
}
if ('scanIntervalMin' in body) {
const interval = normalizeScanIntervalMin(body.scanIntervalMin);
if (interval === null) {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'scanIntervalMin must be an integer between 0 and 1440' } });
}
setSetting(db, SCAN_INTERVAL_KEY, String(interval));
}
return reply.send(snapshot());
});
}

View File

@@ -7,6 +7,7 @@ import { openDb, type Db } from '../src/db/index.js';
import { munge } from '../src/core/jsonl-discovery.js';
import { readProcStart } from '../src/core/session-registry.js';
import type { Config } from '../src/config.js';
import type { DiscoverReposResponse, RepoResponse, ReposListResponse } from '@arboretum/shared';
// resolveClaudeBin() fait `which claude` : on le stub pour ne pas dépendre d'un claude réel en PATH.
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
@@ -127,7 +128,8 @@ describe('app e2e — auth, origin et sessions', () => {
cookies: { arb_session: cookieValue },
});
expect(me.statusCode).toBe(200);
expect(me.json()).toEqual({ ok: true, tokenLabel: 'initial', serverVersion: '0.0.0-test' });
expect(me.json()).toMatchObject({ ok: true, tokenLabel: 'initial', serverVersion: '0.0.0-test' });
expect(typeof (me.json() as { tokenId: string }).tokenId).toBe('string');
});
it('cookie altéré → 401', async () => {
@@ -353,3 +355,59 @@ describe('app e2e — découverte, resume & fork (P2)', () => {
expect(fork.statusCode).toBe(201);
});
});
describe('app e2e — découverte auto des repos & masquage', () => {
let t: TestApp;
let scanRoot: string;
const bearer = (): Record<string, string> => ({ authorization: `Bearer ${t.token}` });
beforeAll(() => {
t = makeApp('repos-discover');
// un « repo » côté scanner = un dossier avec .git (le scanner ne lance pas git).
scanRoot = join(dir, 'scan-root');
mkdirSync(join(scanRoot, 'alpha', '.git'), { recursive: true });
mkdirSync(join(scanRoot, 'beta', '.git'), { recursive: true });
});
it('POST /repos/discover enregistre les repos sous les racines configurées', async () => {
// configure la racine de scan via l'allow-list settings, désactive le périodique
const patch = await t.bundle.app.inject({
method: 'PATCH',
url: '/api/v1/settings',
headers: bearer(),
payload: { scanRoots: [scanRoot], scanIntervalMin: 0 },
});
expect(patch.statusCode).toBe(200);
const disc = await t.bundle.app.inject({ method: 'POST', url: '/api/v1/repos/discover', headers: bearer() });
expect(disc.statusCode).toBe(200);
const body = disc.json() as DiscoverReposResponse;
expect(body.added).toBe(2);
expect(body.scanned).toBe(2);
const list = await t.bundle.app.inject({ method: 'GET', url: '/api/v1/repos', headers: bearer() });
const repos = (list.json() as ReposListResponse).repos;
expect(repos.map((r) => r.label).sort()).toEqual(['alpha', 'beta']);
expect(repos.every((r) => r.hidden === false)).toBe(true);
// re-scan : idempotent (aucun nouveau)
const disc2 = await t.bundle.app.inject({ method: 'POST', url: '/api/v1/repos/discover', headers: bearer() });
expect((disc2.json() as DiscoverReposResponse).added).toBe(0);
});
it('PATCH /repos/:id { hidden } masque le repo', async () => {
const list = await t.bundle.app.inject({ method: 'GET', url: '/api/v1/repos', headers: bearer() });
const repo = (list.json() as ReposListResponse).repos[0];
const patch = await t.bundle.app.inject({
method: 'PATCH',
url: `/api/v1/repos/${repo.id}`,
headers: bearer(),
payload: { hidden: true },
});
expect(patch.statusCode).toBe(200);
expect((patch.json() as RepoResponse).repo.hidden).toBe(true);
// toujours listé (les masqués restent récupérables) mais avec hidden=true
const after = await t.bundle.app.inject({ method: 'GET', url: '/api/v1/repos', headers: bearer() });
expect((after.json() as ReposListResponse).repos.find((r) => r.id === repo.id)?.hidden).toBe(true);
});
});

View File

@@ -0,0 +1,143 @@
// Gestion des tokens d'accès via l'API REST (onglet Réglages) : create → list → revoke,
// flag « courant », jamais de hash exposé, garde anti lock-out sur le dernier token.
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { buildApp, type AppBundle } from '../src/app.js';
import { openDb, type Db } from '../src/db/index.js';
import type { Config } from '../src/config.js';
import type { CreateTokenResponse, MeResponse, TokensListResponse } from '@arboretum/shared';
// Mêmes stubs que les autres tests de routes : pas de vrai claude ni de vrai PTY.
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
vi.mock('@homebridge/node-pty-prebuilt-multiarch', () => {
class FakePty {
pid = 424242;
write = vi.fn();
resize = vi.fn();
pause = vi.fn();
resume = vi.fn();
kill = vi.fn();
onData(): { dispose: () => void } {
return { dispose: () => {} };
}
onExit(): { dispose: () => void } {
return { dispose: () => {} };
}
}
return { default: { spawn: (): FakePty => new FakePty() } };
});
process.env.ARBORETUM_LOG = 'silent';
let dir: string;
let bundle: AppBundle;
let db: Db;
let token: string;
const auth = (): { authorization: string } => ({ authorization: `Bearer ${token}` });
beforeAll(() => {
dir = mkdtempSync(join(tmpdir(), 'arboretum-tokens-'));
const dbPath = join(dir, 'tokens.db');
db = openDb(dbPath);
const config: Config = {
port: 7317,
bind: '127.0.0.1',
dbPath,
dataDir: dir,
allowedOrigins: [],
printToken: false,
claudeProjectsDir: join(dir, 'claude', 'projects'),
claudeSessionsDir: join(dir, 'claude', 'sessions'),
vapidContact: 'mailto:test@localhost',
};
bundle = buildApp(config, db, '0.0.0-test');
const t = bundle.auth.ensureBootstrapToken();
if (!t) throw new Error('bootstrap token attendu sur une base vierge');
token = t;
});
afterAll(async () => {
await bundle.app.close();
db.close();
rmSync(dir, { recursive: true, force: true });
});
describe('routes de gestion des tokens', () => {
it('GET /auth/me expose le tokenId courant', async () => {
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/me', headers: auth() });
expect(res.statusCode).toBe(200);
const me = res.json() as MeResponse;
expect(typeof me.tokenId).toBe('string');
expect(me.tokenId.length).toBeGreaterThan(0);
});
it('liste le token initial et le marque « courant », sans jamais exposer de hash', async () => {
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() });
expect(res.statusCode).toBe(200);
const body = res.json() as TokensListResponse;
expect(body.tokens).toHaveLength(1);
expect(body.tokens[0]?.label).toBe('initial');
expect(body.tokens[0]?.current).toBe(true);
// aucune fuite de hash / valeur en clair
expect(JSON.stringify(body)).not.toMatch(/token_hash|tokenHash/);
});
it('crée un token (valeur en clair renvoyée une fois), puis utilisable pour sauthentifier', async () => {
const res = await bundle.app.inject({
method: 'POST',
url: '/api/v1/auth/tokens',
headers: auth(),
payload: { label: 'laptop' },
});
expect(res.statusCode).toBe(201);
const created = res.json() as CreateTokenResponse;
expect(created.label).toBe('laptop');
expect(created.token).toMatch(/^arb_[0-9a-f]{48}$/);
// le nouveau token authentifie réellement
const me = await bundle.app.inject({
method: 'GET',
url: '/api/v1/auth/me',
headers: { authorization: `Bearer ${created.token}` },
});
expect((me.json() as MeResponse).tokenLabel).toBe('laptop');
});
it('rejette un label vide ou trop long (400)', async () => {
const empty = await bundle.app.inject({ method: 'POST', url: '/api/v1/auth/tokens', headers: auth(), payload: { label: ' ' } });
expect(empty.statusCode).toBe(400);
const tooLong = await bundle.app.inject({ method: 'POST', url: '/api/v1/auth/tokens', headers: auth(), payload: { label: 'x'.repeat(65) } });
expect(tooLong.statusCode).toBe(400);
});
it('révoque un token non courant (204), qui disparaît de la liste et nauthentifie plus', async () => {
const before = (await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() })).json() as TokensListResponse;
const victim = before.tokens.find((t) => !t.current);
expect(victim).toBeDefined();
const del = await bundle.app.inject({ method: 'DELETE', url: `/api/v1/auth/tokens/${victim!.id}`, headers: auth() });
expect(del.statusCode).toBe(200);
const after = (await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() })).json() as TokensListResponse;
expect(after.tokens.find((t) => t.id === victim!.id)).toBeUndefined();
});
it('404 sur un id inconnu', async () => {
const res = await bundle.app.inject({ method: 'DELETE', url: '/api/v1/auth/tokens/nope-xyz', headers: auth() });
expect(res.statusCode).toBe(404);
});
it('409 LAST_TOKEN : refuse de révoquer le dernier token actif', async () => {
const list = (await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() })).json() as TokensListResponse;
expect(list.tokens).toHaveLength(1); // seul le token courant subsiste
const res = await bundle.app.inject({ method: 'DELETE', url: `/api/v1/auth/tokens/${list.tokens[0]!.id}`, headers: auth() });
expect(res.statusCode).toBe(409);
expect(res.json()).toMatchObject({ error: { code: 'LAST_TOKEN' } });
});
it('sans authentification → 401', async () => {
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens' });
expect(res.statusCode).toBe(401);
});
});

View File

@@ -0,0 +1,94 @@
import { describe, expect, it, afterEach } from 'vitest';
import { mkdtempSync, mkdirSync, rmSync, symlinkSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { scanForRepos } from '../src/core/repo-scanner.js';
const dirs: string[] = [];
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
function tmpRoot(): string {
const d = mkdtempSync(join(tmpdir(), 'arb-scan-'));
dirs.push(d);
return d;
}
// un « repo » pour le scanner = un dossier contenant `.git` (le scanner ne lance jamais git).
function makeRepo(...segs: string[]): void {
mkdirSync(join(...segs, '.git'), { recursive: true });
}
const limits = { maxDepth: 6, maxRepos: 2000 };
describe('scanForRepos', () => {
it('trouve un repo simple', async () => {
const root = tmpRoot();
makeRepo(root, 'proj');
const { paths, truncated } = await scanForRepos([root], limits);
expect(paths).toEqual([join(root, 'proj')]);
expect(truncated).toBe(false);
});
it('ne descend pas dans un repo trouvé (sous-repo ignoré)', async () => {
const root = tmpRoot();
makeRepo(root, 'a');
makeRepo(root, 'a', 'sub'); // imbriqué : doit être ignoré
const { paths } = await scanForRepos([root], limits);
expect(paths).toEqual([join(root, 'a')]);
});
it('ignore node_modules et les dotdirs', async () => {
const root = tmpRoot();
makeRepo(root, 'node_modules', 'pkg');
makeRepo(root, '.hidden', 'x');
makeRepo(root, 'real');
const { paths } = await scanForRepos([root], limits);
expect(paths).toEqual([join(root, 'real')]);
});
it('respecte maxDepth', async () => {
const root = tmpRoot();
makeRepo(root, 'a', 'b', 'c', 'deep'); // repo à profondeur 4
const shallow = await scanForRepos([root], { maxDepth: 2, maxRepos: 2000 });
expect(shallow.paths).toEqual([]);
const deep = await scanForRepos([root], { maxDepth: 4, maxRepos: 2000 });
expect(deep.paths).toEqual([join(root, 'a', 'b', 'c', 'deep')]);
});
it('ne suit pas les symlinks (cycle terminé, pas de doublon)', async () => {
const root = tmpRoot();
makeRepo(root, 'proj');
try {
symlinkSync(root, join(root, 'loop')); // cycle vers la racine
} catch {
/* symlink non autorisé sous certains CI : le test reste valide sans le lien */
}
const { paths } = await scanForRepos([root], limits);
expect(paths).toEqual([join(root, 'proj')]);
});
it('tronque à maxRepos', async () => {
const root = tmpRoot();
makeRepo(root, 'r1');
makeRepo(root, 'r2');
makeRepo(root, 'r3');
const { paths, truncated } = await scanForRepos([root], { maxDepth: 6, maxRepos: 2 });
expect(truncated).toBe(true);
expect(paths.length).toBeLessThanOrEqual(2);
});
it('ignore une racine inexistante sans lever', async () => {
const { paths } = await scanForRepos(['/nope/does/not/exist'], limits);
expect(paths).toEqual([]);
});
it('scanne plusieurs racines', async () => {
const r1 = tmpRoot();
const r2 = tmpRoot();
makeRepo(r1, 'one');
makeRepo(r2, 'two');
const { paths } = await scanForRepos([r1, r2], limits);
expect([...paths].sort()).toEqual([join(r1, 'one'), join(r2, 'two')].sort());
});
});

View File

@@ -0,0 +1,163 @@
// Routes Réglages : GET expose la config non sensible (jamais les secrets), PATCH n'écrit que
// l'allow-list et valide l'URL Gitea (http/https only, anti-XSS).
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { buildApp, type AppBundle } from '../src/app.js';
import { getSetting, openDb, type Db } from '../src/db/index.js';
import type { Config } from '../src/config.js';
import type { SettingsResponse } from '@arboretum/shared';
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
vi.mock('@homebridge/node-pty-prebuilt-multiarch', () => {
class FakePty {
pid = 424242;
write = vi.fn();
resize = vi.fn();
pause = vi.fn();
resume = vi.fn();
kill = vi.fn();
onData(): { dispose: () => void } {
return { dispose: () => {} };
}
onExit(): { dispose: () => void } {
return { dispose: () => {} };
}
}
return { default: { spawn: (): FakePty => new FakePty() } };
});
process.env.ARBORETUM_LOG = 'silent';
let dir: string;
let bundle: AppBundle;
let db: Db;
let token: string;
const auth = (): { authorization: string } => ({ authorization: `Bearer ${token}` });
beforeAll(() => {
dir = mkdtempSync(join(tmpdir(), 'arboretum-settings-'));
const dbPath = join(dir, 'settings.db');
db = openDb(dbPath);
const config: Config = {
port: 9999,
bind: '127.0.0.1',
dbPath,
dataDir: dir,
allowedOrigins: ['https://host.tailnet.ts.net'],
printToken: false,
claudeProjectsDir: join(dir, 'claude', 'projects'),
claudeSessionsDir: join(dir, 'claude', 'sessions'),
vapidContact: 'mailto:test@localhost',
};
bundle = buildApp(config, db, '1.2.3-test');
const t = bundle.auth.ensureBootstrapToken();
if (!t) throw new Error('bootstrap token attendu');
token = t;
});
afterAll(async () => {
await bundle.app.close();
db.close();
rmSync(dir, { recursive: true, force: true });
});
describe('GET /api/v1/settings', () => {
it('renvoie la config serveur non sensible et giteaUrl null par défaut', async () => {
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/settings', headers: auth() });
expect(res.statusCode).toBe(200);
const body = res.json() as SettingsResponse;
expect(body.server.version).toBe('1.2.3-test');
expect(body.server.port).toBe(9999);
expect(body.server.bind).toBe('127.0.0.1');
expect(body.server.allowedOrigins).toEqual(['https://host.tailnet.ts.net']);
expect(body.server.vapidPublicKey).toBeTruthy(); // clé publique = sûre à exposer
expect(body.settings.giteaUrl).toBeNull();
// défauts de découverte : home (1 racine) + intervalle 5 min
expect(Array.isArray(body.settings.scanRoots)).toBe(true);
expect(body.settings.scanRoots).toHaveLength(1);
expect(body.settings.scanIntervalMin).toBe(5);
});
it('nexpose AUCUN secret (server_secret, clé privée VAPID)', async () => {
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/settings', headers: auth() });
const raw = res.body;
const secret = getSetting(db, 'server_secret');
const vapidPrivate = getSetting(db, 'vapid_private');
expect(secret).toBeTruthy();
expect(raw).not.toContain(secret as string);
expect(raw).not.toContain(vapidPrivate as string);
expect(raw).not.toMatch(/server_secret|vapid_private|privateKey/);
});
});
describe('PATCH /api/v1/settings', () => {
it('enregistre une URL Gitea valide et la renvoie', async () => {
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { giteaUrl: 'https://git.lidge.fr' } });
expect(res.statusCode).toBe(200);
expect((res.json() as SettingsResponse).settings.giteaUrl).toBe('https://git.lidge.fr/');
// persisté
const get = await bundle.app.inject({ method: 'GET', url: '/api/v1/settings', headers: auth() });
expect((get.json() as SettingsResponse).settings.giteaUrl).toBe('https://git.lidge.fr/');
});
it('efface lURL avec null ou chaîne vide', async () => {
await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { giteaUrl: 'https://git.lidge.fr' } });
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { giteaUrl: null } });
expect((res.json() as SettingsResponse).settings.giteaUrl).toBeNull();
});
it('rejette une URL non http(s) — anti-XSS (400)', async () => {
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { giteaUrl: 'javascript:alert(1)' } });
expect(res.statusCode).toBe(400);
const notUrl = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { giteaUrl: 'pas une url' } });
expect(notUrl.statusCode).toBe(400);
});
it('ignore toute clé hors allow-list (ne touche pas aux secrets)', async () => {
const before = getSetting(db, 'server_secret');
await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { server_secret: 'pwned', vapid_private: 'pwned' } });
expect(getSetting(db, 'server_secret')).toBe(before); // inchangé
expect(getSetting(db, 'vapid_private')).not.toBe('pwned');
});
it('sans authentification → 401', async () => {
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', payload: { giteaUrl: 'https://x.example' } });
expect(res.statusCode).toBe(401);
});
});
describe('PATCH /api/v1/settings — découverte des dépôts', () => {
it('enregistre des scanRoots et un intervalle valides et les renvoie', async () => {
const res = await bundle.app.inject({
method: 'PATCH',
url: '/api/v1/settings',
headers: auth(),
payload: { scanRoots: ['/home/u/work', '/srv/code'], scanIntervalMin: 10 },
});
expect(res.statusCode).toBe(200);
const body = res.json() as SettingsResponse;
expect(body.settings.scanRoots).toEqual(['/home/u/work', '/srv/code']);
expect(body.settings.scanIntervalMin).toBe(10);
// persisté
const get = await bundle.app.inject({ method: 'GET', url: '/api/v1/settings', headers: auth() });
expect((get.json() as SettingsResponse).settings.scanRoots).toEqual(['/home/u/work', '/srv/code']);
});
it('rejette des racines non absolues, "/", avec ".." ou en surnombre (400)', async () => {
const bads: unknown[] = [['relative/path'], ['/'], ['/a/../b'], Array.from({ length: 17 }, (_, i) => `/r${i}`)];
for (const scanRoots of bads) {
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { scanRoots } });
expect(res.statusCode).toBe(400);
}
});
it('rejette un intervalle hors borne (400)', async () => {
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { scanIntervalMin: 5000 } });
expect(res.statusCode).toBe(400);
const neg = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { scanIntervalMin: -1 } });
expect(neg.statusCode).toBe(400);
});
});

View File

@@ -1,9 +1,9 @@
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { execFileSync } from 'node:child_process';
import { mkdtempSync, writeFileSync, rmSync, existsSync } from 'node:fs';
import { mkdtempSync, mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, basename, dirname, resolve } from 'node:path';
import type { WorktreeSummary } from '@arboretum/shared';
import type { RepoSummary, WorktreeSummary } from '@arboretum/shared';
import { WorktreeManager } from '../src/core/worktree-manager.js';
import { PtyManager } from '../src/core/pty-manager.js';
import { DiscoveryService } from '../src/core/discovery-service.js';
@@ -34,9 +34,7 @@ afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
function makeTmpRepo(): string {
const dir = mkdtempSync(join(tmpdir(), 'arb-wtm-'));
dirs.push(dir);
function gitInit(dir: string): void {
const run = (...args: string[]): void => void execFileSync('git', args, { cwd: dir, stdio: 'pipe' });
run('init', '-b', 'main');
run('config', 'user.email', 'test@arboretum.dev');
@@ -44,9 +42,21 @@ function makeTmpRepo(): string {
writeFileSync(join(dir, 'README.md'), '# test\n');
run('add', '-A');
run('commit', '-m', 'init');
}
function makeTmpRepo(): string {
const dir = mkdtempSync(join(tmpdir(), 'arb-wtm-'));
dirs.push(dir);
gitInit(dir);
return dir;
}
/** Crée un vrai repo git à un chemin donné (sous une racine de scan contrôlée). */
function makeRepoAt(path: string): void {
mkdirSync(path, { recursive: true });
gitInit(path);
}
describe('WorktreeManager', () => {
let db: Db;
let pty: PtyManager;
@@ -144,4 +154,79 @@ describe('WorktreeManager', () => {
pty.spawn({ cwd: wtPath, command: 'bash' });
await expect(wt.deleteWorktree(r.id, wtPath, false)).rejects.toMatchObject({ statusCode: 409, code: 'SESSION_LIVE_IN_WORKTREE' });
});
it('addRepo renvoie hidden:false ; updateRepo({hidden}) bascule et émet repo_update', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
expect(r.hidden).toBe(false);
const updates: RepoSummary[] = [];
wt.on('repo_update', (s) => updates.push(s));
const u = await wt.updateRepo(r.id, { hidden: true });
expect(u.hidden).toBe(true);
expect(updates.some((s) => s.id === r.id && s.hidden)).toBe(true);
});
it('listAllWorktrees exclut les repos masqués', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
expect((await wt.listAllWorktrees()).length).toBeGreaterThan(0); // main worktree présent
await wt.updateRepo(r.id, { hidden: true });
expect(await wt.listAllWorktrees()).toHaveLength(0);
});
it('discoverRepos : auto-ajoute les nouveaux, idempotent, masqué non ressuscité, supprimé re-découvrable', async () => {
const root = mkdtempSync(join(tmpdir(), 'arb-scan-'));
dirs.push(root);
makeRepoAt(join(root, 'a'));
makeRepoAt(join(root, 'b'));
const updates: RepoSummary[] = [];
wt.on('repo_update', (s) => updates.push(s));
const res = await wt.discoverRepos({ roots: [root], maxDepth: 2 });
expect(res.added).toBe(2);
expect(res.scanned).toBe(2);
expect(await wt.listRepos()).toHaveLength(2);
expect(updates).toHaveLength(2); // un repo_update par nouveau
// re-scan : idempotent (aucun ajout, aucune émission)
updates.length = 0;
const res2 = await wt.discoverRepos({ roots: [root], maxDepth: 2 });
expect(res2.added).toBe(0);
expect(updates).toHaveLength(0);
expect(await wt.listRepos()).toHaveLength(2);
// masquer 'a' puis re-scan : reste masqué, jamais ré-ajouté (invariant central)
const repoA = (await wt.listRepos()).find((r) => resolve(r.path) === resolve(join(root, 'a')));
await wt.updateRepo(repoA!.id, { hidden: true });
updates.length = 0;
const res3 = await wt.discoverRepos({ roots: [root], maxDepth: 2 });
expect(res3.added).toBe(0);
expect((await wt.listRepos()).find((r) => r.id === repoA!.id)?.hidden).toBe(true);
// supprimer 'b' puis re-scan : re-découvert (volontaire)
const repoB = (await wt.listRepos()).find((r) => resolve(r.path) === resolve(join(root, 'b')));
wt.removeRepo(repoB!.id);
expect(await wt.listRepos()).toHaveLength(1);
const res4 = await wt.discoverRepos({ roots: [root], maxDepth: 2 });
expect(res4.added).toBe(1);
expect(await wt.listRepos()).toHaveLength(2);
});
it('discoverRepos : repo disparu du disque conservé en DB (valid=false), non re-trouvé', async () => {
const root = mkdtempSync(join(tmpdir(), 'arb-scan-'));
dirs.push(root);
makeRepoAt(join(root, 'gone'));
await wt.discoverRepos({ roots: [root], maxDepth: 2 });
expect(await wt.listRepos()).toHaveLength(1);
rmSync(join(root, 'gone'), { recursive: true, force: true }); // disparaît du disque
const res = await wt.discoverRepos({ roots: [root], maxDepth: 2 });
expect(res.added).toBe(0); // plus trouvé par le scan
const repos = await wt.listRepos();
expect(repos).toHaveLength(1); // mais la ligne est conservée (pas de suppression auto)
expect(repos[0].valid).toBe(false);
// robustesse : un repo dont le chemin a disparu ne fait pas planter /worktrees (git échoue → [])
await expect(wt.listAllWorktrees()).resolves.toEqual([]);
});
});

View File

@@ -14,10 +14,34 @@ export interface LoginResponse {
}
export interface MeResponse {
ok: true;
/** id du token de la session courante — sert à marquer « courant » dans la liste des tokens. */
tokenId: string;
tokenLabel: string;
serverVersion: string;
}
// ---- Gestion des tokens d'accès (onglet Réglages) ----
export interface TokenInfo {
id: string;
label: string;
createdAt: string;
lastUsedAt: string | null;
/** true pour le token de la session courante. */
current: boolean;
}
export interface TokensListResponse {
tokens: TokenInfo[];
}
export interface CreateTokenRequest {
label: string;
}
export interface CreateTokenResponse {
id: string;
label: string;
/** valeur en clair — affichée une seule fois, jamais re-récupérable. */
token: string;
}
export interface CreateSessionRequest {
cwd: string;
/** binaire à lancer — défaut "claude" ; "bash" sert aux tests d'acceptation sans quota */
@@ -52,6 +76,19 @@ export interface UpdateRepoRequest {
label?: string;
postCreateHooks?: PostCreateHook[];
preTrust?: boolean;
/** true = masquer le repo (exclu du dashboard, conservé en DB) ; false = ré-afficher. */
hidden?: boolean;
}
/** Résultat d'un scan de découverte (POST /api/v1/repos/discover). */
export interface DiscoverReposResponse {
/** dossiers-repos trouvés sur disque. */
scanned: number;
/** repos réellement insérés (nouveaux, non déjà enregistrés). */
added: number;
durationMs: number;
/** true si la limite (maxRepos / timeout) a été atteinte avant la fin du scan. */
truncated: boolean;
}
export interface WorktreesListResponse {
@@ -146,3 +183,35 @@ export interface PushSubscribeRequest {
export interface PushUnsubscribeRequest {
endpoint: string;
}
// ---- Réglages & info serveur (onglet Réglages) ----
/** Config runtime non sensible du daemon — lecture seule (changée via flags CLI + redémarrage). */
export interface ServerInfo {
version: string;
port: number;
bind: string;
allowedOrigins: string[];
dataDir: string;
/** clé publique VAPID (sûre à exposer) ; null si push indisponible. */
vapidPublicKey: string | null;
vapidContact: string;
}
export interface SettingsResponse {
/** réglages modifiables à chaud (allow-list serveur — jamais les secrets). */
settings: {
giteaUrl: string | null;
/** racines absolues scannées pour la découverte auto des repos (défaut : home). */
scanRoots: string[];
/** intervalle du re-scan périodique en minutes ; 0 = périodique désactivé. */
scanIntervalMin: number;
};
server: ServerInfo;
}
export interface UpdateSettingsRequest {
/** URL de l'instance Gitea (http/https) ; null ou '' pour effacer. */
giteaUrl?: string | null;
/** racines absolues à scanner (chemins normalisés, ≤ 16) ; remplace la liste. */
scanRoots?: string[];
/** intervalle du re-scan périodique en minutes (01440 ; 0 désactive). */
scanIntervalMin?: number;
}

View File

@@ -136,6 +136,8 @@ export interface RepoSummary {
createdAt: string;
/** false si le chemin n'est plus un repo git accessible. */
valid: boolean;
/** true = masqué du dashboard (conservé en DB → non ré-ajouté au re-scan). */
hidden: boolean;
}
export interface WorktreeGitStatus {

View File

@@ -7,6 +7,13 @@
<div class="ml-auto flex items-center gap-2">
<BaseButton size="sm" :icon="Plus" @click="creating = !creating">{{ t('worktrees.new') }}</BaseButton>
<BaseButton size="sm" :icon="Scissors" :loading="busy" @click="onPrune">{{ t('worktrees.prune') }}</BaseButton>
<BaseButton
size="sm"
icon-only
:icon="repo.hidden ? Eye : EyeOff"
:aria-label="repo.hidden ? t('repos.show') : t('repos.hide')"
@click="onToggleHidden"
/>
<BaseButton variant="danger" size="sm" icon-only :icon="Trash2" :aria-label="t('repos.remove')" @click="onRemove" />
</div>
</header>
@@ -41,7 +48,7 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Plus, Scissors, Trash2 } from '@lucide/vue';
import { Eye, EyeOff, Plus, Scissors, Trash2 } from '@lucide/vue';
import type { RepoSummary } from '@arboretum/shared';
import { useWorktreesStore } from '../stores/worktrees';
import { useWorktreeView } from '../composables/useWorktreeView';
@@ -101,4 +108,12 @@ async function onRemove(): Promise<void> {
toasts.error(err);
}
}
async function onToggleHidden(): Promise<void> {
try {
await store.setHidden(props.repo.id, !props.repo.hidden);
} catch (err) {
toasts.error(err);
}
}
</script>

View File

@@ -23,6 +23,7 @@ import { onMounted, onUnmounted } from 'vue';
import { useSessionsStore } from '../../stores/sessions';
import { useWorktreesStore } from '../../stores/worktrees';
import { useGroupsStore } from '../../stores/groups';
import { useSettingsStore } from '../../stores/settings';
import AppSidebar from './AppSidebar.vue';
import MobileTabBar from './MobileTabBar.vue';
@@ -31,11 +32,14 @@ defineProps<{ fullbleed?: boolean }>();
const sessions = useSessionsStore();
const worktrees = useWorktreesStore();
const groups = useGroupsStore();
const settings = useSettingsStore();
onMounted(() => {
void worktrees.fetchAll();
void sessions.fetchSessions();
void groups.fetchGroups();
void settings.fetch(); // alimente l'icône de nav Gitea et la vue Réglages
worktrees.startRealtime();
sessions.startRealtime();
groups.startRealtime();

View File

@@ -15,7 +15,7 @@
</button>
<nav class="flex flex-1 flex-col gap-1 px-2">
<NavItem
v-for="item in items"
v-for="item in primary"
:key="item.key"
:to="item.to"
:icon="item.icon"
@@ -25,6 +25,19 @@
orientation="row"
/>
</nav>
<nav class="flex flex-col gap-1 px-2 pb-1">
<NavItem
v-for="item in secondary"
:key="item.key"
:to="item.to"
:href="item.href"
:icon="item.icon"
:label="item.label"
:badge="item.badge"
:active="isActive(item.match)"
orientation="row"
/>
</nav>
<div class="border-t border-zinc-800/80 p-3">
<AppShellFooter />
</div>
@@ -40,6 +53,6 @@ import NavItem from './NavItem.vue';
import AppShellFooter from './AppShellFooter.vue';
const { t } = useI18n();
const { items, isActive } = useNav();
const { primary, secondary, isActive } = useNav();
const palette = useCommandPalette();
</script>

View File

@@ -4,7 +4,7 @@
style="padding-bottom: env(safe-area-inset-bottom)"
>
<NavItem
v-for="item in items"
v-for="item in primary"
:key="item.key"
:to="item.to"
:icon="item.icon"
@@ -17,24 +17,27 @@
<button
type="button"
class="flex flex-1 flex-col items-center gap-0.5 py-2 text-zinc-500 transition-colors hover:text-zinc-300 focus-visible:outline-none"
:class="moreActive ? 'text-emerald-400' : ''"
@click="showMore = true"
>
<Settings :size="20" :stroke-width="1.75" />
<span class="text-[10px]">{{ t('nav.settings') }}</span>
<Menu :size="20" :stroke-width="1.75" />
<span class="text-[10px]">{{ t('nav.more') }}</span>
</button>
<MoreSheet v-if="showMore" @close="showMore = false" />
</nav>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Settings } from '@lucide/vue';
import { Menu } from '@lucide/vue';
import { useNav } from '../../composables/useNav';
import NavItem from './NavItem.vue';
import MoreSheet from './MoreSheet.vue';
const { t } = useI18n();
const { items, isActive } = useNav();
const { primary, secondary, isActive } = useNav();
const showMore = ref(false);
// « More » est actif quand la route courante appartient aux items secondaires (Réglages/Aide).
const moreActive = computed(() => secondary.value.some((i) => isActive(i.match)));
</script>

View File

@@ -7,7 +7,22 @@
style="padding-bottom: calc(1rem + env(safe-area-inset-bottom))"
>
<div class="mx-auto mb-3 h-1 w-10 rounded-full bg-zinc-700" />
<nav class="mb-3 flex flex-col gap-1">
<NavItem
v-for="item in secondary"
:key="item.key"
:to="item.to"
:href="item.href"
:icon="item.icon"
:label="item.label"
:active="isActive(item.match)"
orientation="row"
@click="emit('close')"
/>
</nav>
<div class="border-t border-zinc-800/80 pt-3">
<AppShellFooter />
</div>
<BaseButton class="mt-3 w-full" @click="emit('close')">{{ t('common.close') }}</BaseButton>
</div>
</div>
@@ -16,9 +31,12 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { useNav } from '../../composables/useNav';
import NavItem from './NavItem.vue';
import AppShellFooter from './AppShellFooter.vue';
import BaseButton from '../ui/BaseButton.vue';
const { t } = useI18n();
const { secondary, isActive } = useNav();
const emit = defineEmits<{ close: [] }>();
</script>

View File

@@ -1,7 +1,12 @@
<template>
<RouterLink
:to="to"
:aria-current="active ? 'page' : undefined"
<!-- RouterLink pour une route interne ; <a target=_blank> pour un lien externe (ex. Gitea). -->
<component
:is="href ? 'a' : RouterLink"
:to="href ? undefined : to"
:href="href"
:target="href ? '_blank' : undefined"
:rel="href ? 'noopener noreferrer' : undefined"
:aria-current="!href && active ? 'page' : undefined"
:class="orientation === 'col' ? colClass : rowClass"
>
<span class="relative">
@@ -20,16 +25,19 @@
>
{{ badge }}
</span>
</RouterLink>
</component>
</template>
<script setup lang="ts">
import { computed, type Component } from 'vue';
import type { RouteLocationRaw } from 'vue-router';
import { RouterLink, type RouteLocationRaw } from 'vue-router';
const props = withDefaults(
defineProps<{
to: RouteLocationRaw;
// `| undefined` requis par exactOptionalPropertyTypes : les items de nav passent `to`/`href`
// potentiellement undefined (l'un ou l'autre selon route interne vs lien externe).
to?: RouteLocationRaw | undefined;
href?: string | undefined;
icon: Component;
label: string;
badge?: number;

View File

@@ -0,0 +1,33 @@
<template>
<!-- Ligne de config serveur en lecture seule : label + valeur (+ flag CLI) + copier. -->
<div class="flex flex-wrap items-center gap-x-3 gap-y-0.5 py-2">
<dt class="w-40 shrink-0 text-sm text-zinc-400">{{ label }}</dt>
<dd class="flex min-w-0 flex-1 items-center gap-2">
<span :class="['min-w-0 flex-1 break-all text-sm text-zinc-200', mono ? 'font-mono text-xs' : '']">{{ value }}</span>
<span v-if="flag" class="hidden shrink-0 font-mono text-[11px] text-zinc-600 sm:inline" :title="t('settings.flagHint', { flag })">{{ flag }}</span>
<BaseButton size="sm" variant="ghost" icon-only :icon="copied ? Check : Copy" :aria-label="t('settings.copy')" @click="copy" />
</dd>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Check, Copy } from '@lucide/vue';
import BaseButton from '../ui/BaseButton.vue';
const props = defineProps<{ label: string; value: string; flag?: string; mono?: boolean }>();
const { t } = useI18n();
const copied = ref(false);
// Auto-contenu : on ne confirme (✓) qu'après la résolution réelle de l'écriture presse-papiers.
async function copy(): Promise<void> {
try {
await navigator.clipboard.writeText(props.value);
copied.value = true;
setTimeout(() => (copied.value = false), 1500);
} catch {
/* presse-papiers indisponible (http non sécurisé) : silencieux */
}
}
</script>

View File

@@ -0,0 +1,31 @@
<template>
<!-- Lucide n'a pas d'icône Gitea : motif « tasse de thé fumante » (git + tea), trait cohérent
avec les icônes Lucide (currentColor, coins arrondis). stroke-width hérité via fallthrough. -->
<svg
:width="size"
:height="size"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<!-- vapeur = mini-branche git -->
<path d="M9 5.5V4" />
<path d="M13 5.5V3" />
<circle cx="9" cy="3" r="0.6" fill="currentColor" stroke="none" />
<circle cx="13" cy="2.5" r="0.6" fill="currentColor" stroke="none" />
<!-- tasse -->
<path d="M4 8h12v4a5 5 0 0 1-5 5H9a5 5 0 0 1-5-5z" />
<!-- anse -->
<path d="M16 9h1.5a2.5 2.5 0 0 1 0 5H16" />
<!-- soucoupe -->
<path d="M5 20h10" />
</svg>
</template>
<script setup lang="ts">
withDefaults(defineProps<{ size?: number }>(), { size: 18 });
</script>

View File

@@ -1,12 +1,17 @@
import { computed, type Component } from 'vue';
import { useRoute, type RouteLocationRaw } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { GitBranch, TerminalSquare, Boxes } from '@lucide/vue';
import { Boxes, GitBranch, LifeBuoy, Settings, TerminalSquare } from '@lucide/vue';
import { useSessionsStore } from '../stores/sessions';
import { useSettingsStore } from '../stores/settings';
import GiteaIcon from '../components/ui/GiteaIcon.vue';
export interface NavEntry {
key: string;
to: RouteLocationRaw;
/** route interne (exclusif avec `href`). */
to?: RouteLocationRaw;
/** lien externe ouvert dans un nouvel onglet (exclusif avec `to`). */
href?: string;
icon: Component;
label: string;
match: string[]; // noms de routes considérés actifs pour cet item
@@ -18,19 +23,33 @@ export function useNav() {
const { t } = useI18n();
const route = useRoute();
const sessions = useSessionsStore();
const settings = useSettingsStore();
// sessions vivantes bloquées sur un dialogue (le cœur de la supervision mobile).
const waitingCount = computed(
() => sessions.sessions.filter((s) => s.live && s.activity === 'waiting').length,
);
const items = computed<NavEntry[]>(() => [
// Onglets principaux : barre du bas mobile + haut de sidebar.
const primary = computed<NavEntry[]>(() => [
{ key: 'worktrees', to: { name: 'dashboard' }, icon: GitBranch, label: t('nav.worktrees'), match: ['dashboard'], badge: 0 },
{ key: 'sessions', to: { name: 'sessions' }, icon: TerminalSquare, label: t('nav.sessions'), match: ['sessions', 'session'], badge: waitingCount.value },
{ key: 'groups', to: { name: 'groups' }, icon: Boxes, label: t('nav.groups'), match: ['groups', 'group'], badge: 0 },
]);
// Onglets secondaires : réglages, aide, et lien externe Gitea (uniquement si l'URL est configurée).
const secondary = computed<NavEntry[]>(() => {
const items: NavEntry[] = [
{ key: 'settings', to: { name: 'settings' }, icon: Settings, label: t('nav.settings'), match: ['settings'], badge: 0 },
{ key: 'help', to: { name: 'help' }, icon: LifeBuoy, label: t('nav.help'), match: ['help'], badge: 0 },
];
if (settings.giteaUrl) {
items.push({ key: 'gitea', href: settings.giteaUrl, icon: GiteaIcon, label: t('nav.gitea'), match: [], badge: 0 });
}
return items;
});
const isActive = (match: string[]): boolean => match.includes(String(route.name));
return { items, isActive, waitingCount };
return { primary, secondary, isActive, waitingCount };
}

View File

@@ -122,8 +122,13 @@ export default {
remove: 'Remove',
pathLabel: 'Repository path',
pathPlaceholder: '/absolute/path/to/repo',
empty: 'No repository registered yet — add one above.',
empty: 'No repository registered yet — add one above, or scan for repos.',
invalid: 'unavailable',
scan: 'Scan',
scanResult: 'No new repository found | 1 new repository added | {n} new repositories added',
hide: 'Hide',
show: 'Show',
showHidden: 'Show hidden ({n})',
},
worktrees: {
new: 'New worktree',
@@ -174,6 +179,9 @@ export default {
sessions: 'Sessions',
groups: 'Groups',
settings: 'Settings',
help: 'Help',
more: 'More',
gitea: 'Open Gitea',
waiting: 'waiting',
},
controls: {
@@ -292,4 +300,73 @@ export default {
count: 'no session waiting | 1 session waiting | {n} sessions waiting',
empty: 'Nothing waiting',
},
settings: {
title: 'Settings',
// Préférences
preferences: 'Preferences',
preferencesHint: 'These apply to this browser only.',
language: 'Language',
notifications: 'Notifications',
notificationsEnabled: 'Enabled — you will be notified when a session needs input.',
notificationsDisabled: 'Disabled.',
enableNotifications: 'Enable notifications',
disableNotifications: 'Disable notifications',
testNotification: 'Send a test',
testSent: 'Test notification sent',
pushUnsupported: 'Push needs HTTPS (e.g. Tailscale Serve); on iOS, install the app to your home screen first.',
// Accès & sécurité
security: 'Access & security',
securityHint: 'Tokens grant full access to this server. Create one per device and revoke any you no longer use.',
tokens: 'Access tokens',
newTokenLabel: 'Label',
newTokenPlaceholder: 'e.g. phone, laptop',
createToken: 'Create token',
tokenCreated: 'Token created',
copyTokenHint: 'Copy this token now — for security it will never be shown again.',
copy: 'Copy',
copied: 'Copied',
current: 'current',
created: 'Created {date}',
lastUsed: 'last used {date}',
neverUsed: 'never used',
revoke: 'Revoke',
confirmRevoke: 'Confirm revoke',
tokenRevoked: 'Token revoked',
lastTokenError: 'You cannot revoke the last active token — create another one first.',
// Intégrations
integrations: 'Integrations',
gitea: 'Gitea',
giteaUrlLabel: 'Gitea instance URL',
giteaUrlPlaceholder: 'https://git.example.com',
giteaUrlHint: 'Adds a shortcut icon to the navigation. Leave empty to hide it.',
save: 'Save',
saved: 'Saved',
// Découverte des dépôts
discovery: 'Repository discovery',
discoveryHint: 'Arboretum scans these folders for git repositories and registers them automatically. Hidden repos are kept and never re-added.',
scanRoots: 'Scan folders',
scanRootsEmpty: 'No folder configured — your home directory is used by default.',
addRoot: 'Add folder',
removeRoot: 'Remove',
scanInterval: 'Re-scan interval (minutes)',
scanIntervalHint: '0 disables periodic scanning. Changes apply on the next daemon restart.',
// Serveur (lecture seule)
server: 'Server',
serverHint: 'Set at startup via CLI flags — changing them requires restarting the daemon.',
version: 'Version',
port: 'Port',
bind: 'Bind address',
allowedOrigins: 'Allowed origins',
dataDir: 'Data directory',
vapidPublicKey: 'VAPID public key',
vapidContact: 'VAPID contact',
none: 'none',
flagHint: 'CLI flag: {flag}',
},
help: {
title: 'Help',
intro: 'Everything Arboretum can do, and how to use it.',
searchPlaceholder: 'Search help…',
noMatch: 'No matching topic',
},
};

View File

@@ -124,8 +124,13 @@ const fr: typeof en = {
remove: 'Retirer',
pathLabel: 'Chemin du dépôt',
pathPlaceholder: '/chemin/absolu/du/repo',
empty: 'Aucun dépôt enregistré — ajoutez-en un ci-dessus.',
empty: 'Aucun dépôt enregistré — ajoutez-en un ci-dessus, ou lancez un scan.',
invalid: 'indisponible',
scan: 'Scanner',
scanResult: 'Aucun nouveau dépôt trouvé | 1 nouveau dépôt ajouté | {n} nouveaux dépôts ajoutés',
hide: 'Masquer',
show: 'Afficher',
showHidden: 'Afficher les masqués ({n})',
},
worktrees: {
new: 'Nouveau worktree',
@@ -177,6 +182,9 @@ const fr: typeof en = {
sessions: 'Sessions',
groups: 'Groupes',
settings: 'Réglages',
help: 'Aide',
more: 'Plus',
gitea: 'Ouvrir Gitea',
waiting: 'en attente',
},
controls: {
@@ -295,6 +303,75 @@ const fr: typeof en = {
count: 'aucune session en attente | 1 session en attente | {n} sessions en attente',
empty: 'Rien à traiter',
},
settings: {
title: 'Réglages',
// Préférences
preferences: 'Préférences',
preferencesHint: 'Ces réglages ne sappliquent quà ce navigateur.',
language: 'Langue',
notifications: 'Notifications',
notificationsEnabled: 'Activées — vous serez notifié lorsquune session attend une réponse.',
notificationsDisabled: 'Désactivées.',
enableNotifications: 'Activer les notifications',
disableNotifications: 'Désactiver les notifications',
testNotification: 'Envoyer un test',
testSent: 'Notification de test envoyée',
pushUnsupported: 'Le push exige HTTPS (ex. Tailscale Serve) ; sur iOS, installez dabord lapp sur lécran daccueil.',
// Accès & sécurité
security: 'Accès & sécurité',
securityHint: 'Les jetons donnent un accès complet à ce serveur. Créez-en un par appareil et révoquez ceux que vous nutilisez plus.',
tokens: 'Jetons daccès',
newTokenLabel: 'Libellé',
newTokenPlaceholder: 'ex. téléphone, portable',
createToken: 'Créer un jeton',
tokenCreated: 'Jeton créé',
copyTokenHint: 'Copiez ce jeton maintenant — par sécurité il ne sera plus jamais affiché.',
copy: 'Copier',
copied: 'Copié',
current: 'courant',
created: 'Créé le {date}',
lastUsed: 'utilisé le {date}',
neverUsed: 'jamais utilisé',
revoke: 'Révoquer',
confirmRevoke: 'Confirmer la révocation',
tokenRevoked: 'Jeton révoqué',
lastTokenError: 'Impossible de révoquer le dernier jeton actif — créez-en un autre dabord.',
// Intégrations
integrations: 'Intégrations',
gitea: 'Gitea',
giteaUrlLabel: 'URL de linstance Gitea',
giteaUrlPlaceholder: 'https://git.exemple.com',
giteaUrlHint: 'Ajoute une icône de raccourci dans la navigation. Laissez vide pour la masquer.',
save: 'Enregistrer',
saved: 'Enregistré',
// Découverte des dépôts
discovery: 'Découverte des dépôts',
discoveryHint: 'Arboretum scanne ces dossiers à la recherche de dépôts git et les enregistre automatiquement. Les dépôts masqués sont conservés et jamais ré-ajoutés.',
scanRoots: 'Dossiers à scanner',
scanRootsEmpty: 'Aucun dossier configuré — votre dossier personnel est utilisé par défaut.',
addRoot: 'Ajouter un dossier',
removeRoot: 'Retirer',
scanInterval: 'Intervalle de re-scan (minutes)',
scanIntervalHint: '0 désactive le scan périodique. Les changements prennent effet au prochain redémarrage du daemon.',
// Serveur (lecture seule)
server: 'Serveur',
serverHint: 'Définis au démarrage via des flags CLI — les modifier nécessite de redémarrer le daemon.',
version: 'Version',
port: 'Port',
bind: 'Adresse de liaison',
allowedOrigins: 'Origines autorisées',
dataDir: 'Répertoire de données',
vapidPublicKey: 'Clé publique VAPID',
vapidContact: 'Contact VAPID',
none: 'aucune',
flagHint: 'Flag CLI : {flag}',
},
help: {
title: 'Aide',
intro: 'Tout ce quArboretum sait faire, et comment lutiliser.',
searchPlaceholder: 'Rechercher dans laide…',
noMatch: 'Aucun sujet correspondant',
},
};
export default fr;

View File

@@ -18,6 +18,8 @@ export const router = createRouter({
{ path: '/sessions/:id', name: 'session', component: () => import('../views/SessionView.vue'), meta: { layout: 'fullbleed' } },
{ path: '/groups', name: 'groups', component: () => import('../views/GroupsListView.vue'), meta: { layout: 'shell' } },
{ path: '/groups/:id', name: 'group', component: () => import('../views/GroupView.vue'), meta: { layout: 'shell' } },
{ path: '/settings', name: 'settings', component: () => import('../views/SettingsView.vue'), meta: { layout: 'shell' } },
{ path: '/help', name: 'help', component: () => import('../views/HelpView.vue'), meta: { layout: 'shell' } },
{ path: '/:pathMatch(.*)*', redirect: '/' },
],
});

View File

@@ -0,0 +1,38 @@
import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { ServerInfo, SettingsResponse, UpdateSettingsRequest } from '@arboretum/shared';
import { api } from '../lib/api';
// Réglages serveur + intégrations. `giteaUrl` alimente l'item de nav Gitea (affiché si défini).
// Les préférences purement client (langue) restent gérées par l'i18n/localStorage.
export const useSettingsStore = defineStore('settings', () => {
const server = ref<ServerInfo | null>(null);
const giteaUrl = ref<string | null>(null);
const scanRoots = ref<string[]>([]);
const scanIntervalMin = ref(0);
const loaded = ref(false);
const saving = ref(false);
function apply(res: SettingsResponse): void {
server.value = res.server;
giteaUrl.value = res.settings.giteaUrl;
scanRoots.value = res.settings.scanRoots;
scanIntervalMin.value = res.settings.scanIntervalMin;
loaded.value = true;
}
async function fetch(): Promise<void> {
apply(await api.get<SettingsResponse>('/api/v1/settings'));
}
async function save(patch: UpdateSettingsRequest): Promise<void> {
saving.value = true;
try {
apply(await api.patch<SettingsResponse>('/api/v1/settings', patch));
} finally {
saving.value = false;
}
}
return { server, giteaUrl, scanRoots, scanIntervalMin, loaded, saving, fetch, save };
});

View File

@@ -3,6 +3,7 @@ import { ref } from 'vue';
import type {
CreateWorktreeRequest,
CreateWorktreeResponse,
DiscoverReposResponse,
RepoResponse,
ReposListResponse,
RepoSummary,
@@ -84,6 +85,19 @@ export const useWorktreesStore = defineStore('worktrees', () => {
removeRepoLocal(id);
}
/** Masque/ré-affiche un repo (persiste `hidden` côté serveur ; émis aussi par WS). */
async function setHidden(id: string, hidden: boolean): Promise<void> {
const res = await api.patch<RepoResponse>(`/api/v1/repos/${id}`, { hidden });
upsertRepo(res.repo);
}
/** Lance un scan de découverte ; les nouveaux repos arrivent par WS, on resynchronise par sûreté. */
async function discover(): Promise<DiscoverReposResponse> {
const res = await api.post<DiscoverReposResponse>('/api/v1/repos/discover');
await fetchAll();
return res;
}
async function createWorktree(repoId: string, req: CreateWorktreeRequest): Promise<CreateWorktreeResponse> {
const res = await api.post<CreateWorktreeResponse>(`/api/v1/repos/${repoId}/worktrees`, req);
upsertWorktree(res.worktree);
@@ -117,6 +131,9 @@ export const useWorktreesStore = defineStore('worktrees', () => {
fetchAll,
addRepo,
removeRepo,
setHidden,
discover,
refreshRepoWorktrees,
createWorktree,
deleteWorktree,
prune,

View File

@@ -1,5 +1,8 @@
<template>
<PageHeader :title="t('nav.worktrees')">
<BaseButton variant="ghost" size="sm" :icon="ScanSearch" :loading="scanning" @click="onDiscover">
{{ t('repos.scan') }}
</BaseButton>
<BaseButton variant="ghost" size="sm" :icon="RefreshCw" :loading="store.loading" @click="refresh">
{{ t('common.refresh') }}
</BaseButton>
@@ -33,6 +36,9 @@
<template v-else>
<!-- une seule toolbar pilote le tri/filtre des worktrees de toutes les sections -->
<ListToolbar :controls="view" search-placeholder-key="controls.searchPlaceholder" />
<label v-if="hiddenCount > 0" class="flex items-center gap-2 px-1 text-xs text-zinc-400">
<input v-model="showHidden" type="checkbox" /> {{ t('repos.showHidden', { n: hiddenCount }) }}
</label>
<EmptyState v-if="visibleRepos.length === 0" :icon="Search" :title="t('controls.results', 0)" />
<RepoSection v-for="repo in pagedRepos" :key="repo.id" :repo="repo" />
<Pagination
@@ -50,7 +56,7 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { GitBranch, RefreshCw, FolderOpen, Plus, Search } from '@lucide/vue';
import { GitBranch, RefreshCw, FolderOpen, Plus, Search, ScanSearch } from '@lucide/vue';
import { useWorktreesStore } from '../stores/worktrees';
import { useToastsStore } from '../stores/toasts';
import { useWorktreeView } from '../composables/useWorktreeView';
@@ -72,15 +78,29 @@ const view = useWorktreeView();
const newPath = ref('');
const showPicker = ref(false);
const adding = ref(false);
const scanning = ref(false);
const showHidden = ref(false);
// repos triés par libellé ; masqués quand un filtre/recherche worktree actif ne laisse rien dans le repo.
const sortedRepos = computed(() => [...store.repos].sort((a, b) => a.label.localeCompare(b.label)));
const hiddenCount = computed(() => store.repos.filter((r) => r.hidden).length);
// repos visibles : les masqués sont exclus sauf si « afficher les masqués » est coché. Triés par libellé ;
// puis masqués quand un filtre/recherche worktree actif ne laisse rien dans le repo.
const sortedRepos = computed(() =>
[...store.repos]
.filter((r) => showHidden.value || !r.hidden)
.sort((a, b) => a.label.localeCompare(b.label)),
);
const visibleRepos = computed(() =>
view.isActive()
? sortedRepos.value.filter((r) => view.apply(store.worktreesForRepo(r.id)).length > 0)
: sortedRepos.value,
);
// GET /worktrees exclut les repos masqués (perf) → charger paresseusement leurs worktrees au dévoilement.
watch(showHidden, (on) => {
if (on) for (const r of store.repos.filter((x) => x.hidden)) void store.refreshRepoWorktrees(r.id);
});
// pagination des repos (rarement nombreux → masquée par défaut).
const repoPage = ref(1);
const repoPageSize = ref(10);
@@ -110,6 +130,18 @@ function refresh(): void {
void store.fetchAll();
}
async function onDiscover(): Promise<void> {
scanning.value = true;
try {
const res = await store.discover();
toasts.success(t('repos.scanResult', res.added));
} catch (err) {
toasts.error(err);
} finally {
scanning.value = false;
}
}
async function onAddRepo(): Promise<void> {
adding.value = true;
try {

View File

@@ -0,0 +1,68 @@
<template>
<div class="flex flex-col gap-4">
<PageHeader :title="t('help.title')">
<template #search>
<div class="relative">
<Search :size="15" class="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-zinc-500" />
<input v-model="query" class="input pl-8" :placeholder="t('help.searchPlaceholder')" />
</div>
</template>
</PageHeader>
<p class="text-sm text-zinc-400">{{ t('help.intro') }}</p>
<section v-for="section in filtered" :key="section.id" class="card flex flex-col gap-3">
<header class="flex items-center gap-2">
<component :is="iconFor(section.id)" :size="18" class="text-emerald-400" :stroke-width="1.75" />
<h2 class="text-sm font-semibold text-zinc-100">{{ section.title }}</h2>
</header>
<p class="text-xs text-zinc-500">{{ section.blurb }}</p>
<dl class="flex flex-col gap-2">
<div v-for="(item, i) in section.items" :key="i" class="card-inset">
<dt class="text-sm font-medium text-zinc-200">{{ item.title }}</dt>
<dd class="mt-0.5 text-sm leading-relaxed text-zinc-400">{{ item.body }}</dd>
</div>
</dl>
</section>
<EmptyState v-if="!filtered.length" :icon="SearchX" :title="t('help.noMatch')" />
</div>
</template>
<script setup lang="ts">
import { computed, ref, type Component } from 'vue';
import { useI18n } from 'vue-i18n';
import { Boxes, Command, GitBranch, KeyRound, Puzzle, Search, SearchX, Settings, Smartphone, TerminalSquare } from '@lucide/vue';
import type { AppLocale } from '../i18n';
import { helpSections, type HelpSection } from './help-content';
import PageHeader from '../components/layout/PageHeader.vue';
import EmptyState from '../components/ui/EmptyState.vue';
const { t, locale } = useI18n();
const query = ref('');
const ICONS: Record<string, Component> = {
gettingStarted: KeyRound,
worktrees: GitBranch,
sessions: TerminalSquare,
mobile: Smartphone,
groups: Boxes,
productivity: Command,
settings: Settings,
integrations: Puzzle,
};
const iconFor = (id: string): Component => ICONS[id] ?? KeyRound;
const sections = computed<HelpSection[]>(() => helpSections[locale.value as AppLocale] ?? helpSections.en);
const filtered = computed<HelpSection[]>(() => {
const q = query.value.trim().toLowerCase();
if (!q) return sections.value;
return sections.value
.map((s) => {
const sectionMatches = (s.title + ' ' + s.blurb).toLowerCase().includes(q);
const items = sectionMatches ? s.items : s.items.filter((it) => (it.title + ' ' + it.body).toLowerCase().includes(q));
return items.length ? { ...s, items } : null;
})
.filter((s): s is HelpSection => s !== null);
});
</script>

View File

@@ -0,0 +1,322 @@
<template>
<div class="flex flex-col gap-4">
<PageHeader :title="t('settings.title')" />
<!-- Préférences (client) -->
<section class="card flex flex-col gap-3">
<h2 class="flex items-center gap-2 text-sm font-semibold text-zinc-100">
<SlidersHorizontal :size="16" /> {{ t('settings.preferences') }}
</h2>
<p class="text-xs text-zinc-500">{{ t('settings.preferencesHint') }}</p>
<div class="flex items-center justify-between gap-3">
<span class="text-sm text-zinc-300">{{ t('settings.language') }}</span>
<LanguageSwitcher />
</div>
<div class="flex flex-col gap-2 border-t border-zinc-800/80 pt-3">
<div class="flex items-center justify-between gap-3">
<div class="min-w-0">
<p class="text-sm text-zinc-300">{{ t('settings.notifications') }}</p>
<p class="text-xs text-zinc-500">
{{ push.supported ? (push.enabled ? t('settings.notificationsEnabled') : t('settings.notificationsDisabled')) : t('settings.pushUnsupported') }}
</p>
</div>
<BaseButton
v-if="push.supported"
:variant="push.enabled ? 'secondary' : 'primary'"
size="sm"
:icon="push.enabled ? BellOff : Bell"
:loading="push.busy"
@click="push.toggle()"
>
{{ push.enabled ? t('settings.disableNotifications') : t('settings.enableNotifications') }}
</BaseButton>
</div>
<div v-if="push.enabled">
<BaseButton variant="ghost" size="sm" :icon="Send" :loading="testing" @click="sendTest">
{{ t('settings.testNotification') }}
</BaseButton>
</div>
</div>
</section>
<!-- Accès & sécurité : tokens -->
<section class="card flex flex-col gap-3">
<h2 class="flex items-center gap-2 text-sm font-semibold text-zinc-100">
<Shield :size="16" /> {{ t('settings.security') }}
</h2>
<p class="text-xs text-zinc-500">{{ t('settings.securityHint') }}</p>
<!-- Création -->
<form class="flex flex-wrap items-end gap-2" @submit.prevent="createToken">
<label class="flex min-w-40 flex-1 flex-col gap-1">
<span class="text-xs text-zinc-400">{{ t('settings.newTokenLabel') }}</span>
<input v-model="newLabel" class="input" :placeholder="t('settings.newTokenPlaceholder')" maxlength="64" />
</label>
<BaseButton type="submit" variant="primary" :icon="Plus" :loading="creating" :disabled="!newLabel.trim()">
{{ t('settings.createToken') }}
</BaseButton>
</form>
<!-- Valeur en clair (une seule fois) -->
<div v-if="createdToken" class="card-inset flex flex-col gap-2 border-emerald-800/60 bg-emerald-950/20">
<p class="text-xs text-emerald-300">{{ t('settings.copyTokenHint') }}</p>
<div class="flex items-center gap-2">
<code class="min-w-0 flex-1 truncate rounded bg-zinc-950 px-2 py-1 font-mono text-xs text-zinc-100">{{ createdToken.token }}</code>
<BaseButton size="sm" :icon="copiedNew ? Check : Copy" @click="copy(createdToken.token, 'new')">
{{ copiedNew ? t('settings.copied') : t('settings.copy') }}
</BaseButton>
<BaseButton size="sm" variant="ghost" icon-only :icon="X" :aria-label="t('common.close')" @click="createdToken = null" />
</div>
</div>
<!-- Liste -->
<ul class="flex flex-col gap-2">
<li
v-for="tok in tokens"
:key="tok.id"
class="card-inset flex flex-wrap items-center gap-x-3 gap-y-1"
>
<KeyRound :size="15" class="shrink-0 text-zinc-500" />
<div class="min-w-0 flex-1">
<p class="flex items-center gap-2 truncate text-sm text-zinc-200">
{{ tok.label }}
<span v-if="tok.current" class="badge bg-emerald-500/15 text-emerald-300">{{ t('settings.current') }}</span>
</p>
<p class="text-[11px] text-zinc-500">
{{ t('settings.created', { date: fmt(tok.createdAt) }) }} ·
{{ tok.lastUsedAt ? t('settings.lastUsed', { date: fmt(tok.lastUsedAt) }) : t('settings.neverUsed') }}
</p>
</div>
<BaseButton
v-if="!tok.current"
size="sm"
:variant="confirmId === tok.id ? 'danger' : 'ghost'"
:icon="Trash2"
@click="revoke(tok)"
>
{{ confirmId === tok.id ? t('settings.confirmRevoke') : t('settings.revoke') }}
</BaseButton>
</li>
</ul>
</section>
<!-- Intégrations : Gitea -->
<section class="card flex flex-col gap-3">
<h2 class="flex items-center gap-2 text-sm font-semibold text-zinc-100">
<Puzzle :size="16" /> {{ t('settings.integrations') }}
</h2>
<form class="flex flex-col gap-2" @submit.prevent="saveGitea">
<label class="flex flex-col gap-1">
<span class="text-xs text-zinc-400">{{ t('settings.giteaUrlLabel') }}</span>
<div class="flex flex-wrap items-center gap-2">
<input v-model="giteaInput" type="url" class="input min-w-48 flex-1" :placeholder="t('settings.giteaUrlPlaceholder')" />
<BaseButton type="submit" variant="primary" :loading="settings.saving" :disabled="!giteaDirty">
{{ t('settings.save') }}
</BaseButton>
</div>
</label>
<p class="text-xs text-zinc-500">{{ t('settings.giteaUrlHint') }}</p>
</form>
</section>
<!-- Découverte des dépôts -->
<section class="card flex flex-col gap-3">
<h2 class="flex items-center gap-2 text-sm font-semibold text-zinc-100">
<ScanSearch :size="16" /> {{ t('settings.discovery') }}
</h2>
<p class="text-xs text-zinc-500">{{ t('settings.discoveryHint') }}</p>
<div class="flex flex-col gap-2">
<span class="text-xs text-zinc-400">{{ t('settings.scanRoots') }}</span>
<p v-if="rootsDraft.length === 0" class="text-xs text-zinc-600">{{ t('settings.scanRootsEmpty') }}</p>
<ul v-else class="flex flex-col gap-1">
<li v-for="(root, i) in rootsDraft" :key="root" class="card-inset flex items-center gap-2">
<span class="min-w-0 flex-1 truncate font-mono text-xs text-zinc-200" :title="root">{{ root }}</span>
<BaseButton size="sm" variant="ghost" icon-only :icon="X" :aria-label="t('settings.removeRoot')" @click="rootsDraft.splice(i, 1)" />
</li>
</ul>
<div>
<BaseButton size="sm" :icon="FolderOpen" @click="showRootPicker = !showRootPicker">{{ t('settings.addRoot') }}</BaseButton>
</div>
<DirectoryPicker v-if="showRootPicker" mode="dir" @select="onAddRoot" @close="showRootPicker = false" />
</div>
<label class="flex flex-col gap-1">
<span class="text-xs text-zinc-400">{{ t('settings.scanInterval') }}</span>
<input v-model.number="intervalDraft" type="number" min="0" max="1440" class="input w-32" />
<span class="text-xs text-zinc-500">{{ t('settings.scanIntervalHint') }}</span>
</label>
<div>
<BaseButton variant="primary" :loading="settings.saving" :disabled="!discoveryDirty" @click="saveDiscovery">
{{ t('settings.save') }}
</BaseButton>
</div>
</section>
<!-- Serveur (lecture seule) -->
<section class="card flex flex-col gap-3">
<h2 class="flex items-center gap-2 text-sm font-semibold text-zinc-100">
<Server :size="16" /> {{ t('settings.server') }}
</h2>
<p class="text-xs text-zinc-500">{{ t('settings.serverHint') }}</p>
<dl v-if="settings.server" class="flex flex-col divide-y divide-zinc-800/80">
<ServerRow :label="t('settings.version')" :value="settings.server.version" />
<ServerRow :label="t('settings.port')" :value="String(settings.server.port)" flag="--port" />
<ServerRow :label="t('settings.bind')" :value="settings.server.bind" flag="--bind" />
<ServerRow
:label="t('settings.allowedOrigins')"
:value="settings.server.allowedOrigins.length ? settings.server.allowedOrigins.join(', ') : t('settings.none')"
flag="--allow-origin"
/>
<ServerRow :label="t('settings.dataDir')" :value="settings.server.dataDir" />
<ServerRow :label="t('settings.vapidContact')" :value="settings.server.vapidContact" flag="--vapid-contact" />
<ServerRow :label="t('settings.vapidPublicKey')" :value="settings.server.vapidPublicKey ?? t('settings.none')" mono />
</dl>
<SkeletonRow v-else />
</section>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Bell, BellOff, Check, Copy, FolderOpen, KeyRound, Plus, Puzzle, ScanSearch, Send, Server, Shield, SlidersHorizontal, Trash2, X } from '@lucide/vue';
import type { CreateTokenResponse, TokenInfo, TokensListResponse } from '@arboretum/shared';
import { api, ApiError } from '../lib/api';
import { useSettingsStore } from '../stores/settings';
import { usePushStore } from '../stores/push';
import { useToastsStore } from '../stores/toasts';
import PageHeader from '../components/layout/PageHeader.vue';
import LanguageSwitcher from '../components/LanguageSwitcher.vue';
import BaseButton from '../components/ui/BaseButton.vue';
import SkeletonRow from '../components/ui/SkeletonRow.vue';
import ServerRow from '../components/settings/ServerRow.vue';
import DirectoryPicker from '../components/DirectoryPicker.vue';
const { t, locale } = useI18n();
const settings = useSettingsStore();
const push = usePushStore();
const toasts = useToastsStore();
// ---- Préférences ----
const testing = ref(false);
async function sendTest(): Promise<void> {
testing.value = true;
try {
await api.post('/api/v1/push/test');
toasts.success(t('settings.testSent'));
} catch (e) {
toasts.error(e);
} finally {
testing.value = false;
}
}
// ---- Tokens ----
const tokens = ref<TokenInfo[]>([]);
const newLabel = ref('');
const creating = ref(false);
const createdToken = ref<CreateTokenResponse | null>(null);
const confirmId = ref<string | null>(null);
const copiedNew = ref(false);
const fmt = (iso: string): string => new Date(iso).toLocaleString(locale.value);
async function loadTokens(): Promise<void> {
tokens.value = (await api.get<TokensListResponse>('/api/v1/auth/tokens')).tokens;
}
async function createToken(): Promise<void> {
const label = newLabel.value.trim();
if (!label) return;
creating.value = true;
try {
createdToken.value = await api.post<CreateTokenResponse>('/api/v1/auth/tokens', { label });
newLabel.value = '';
toasts.success(t('settings.tokenCreated'));
await loadTokens();
} catch (e) {
toasts.error(e);
} finally {
creating.value = false;
}
}
async function revoke(tok: TokenInfo): Promise<void> {
if (confirmId.value !== tok.id) {
confirmId.value = tok.id;
return;
}
confirmId.value = null;
try {
await api.delete(`/api/v1/auth/tokens/${tok.id}`);
toasts.success(t('settings.tokenRevoked'));
await loadTokens();
} catch (e) {
toasts.error(e instanceof ApiError && e.code === 'LAST_TOKEN' ? t('settings.lastTokenError') : e);
}
}
async function copy(text: string, target?: 'new'): Promise<void> {
try {
await navigator.clipboard.writeText(text);
if (target === 'new') {
copiedNew.value = true;
setTimeout(() => (copiedNew.value = false), 1500);
}
} catch {
/* presse-papiers indisponible (http non sécurisé) : silencieux */
}
}
// ---- Gitea ----
const giteaInput = ref('');
const giteaDirty = computed(() => giteaInput.value.trim() !== (settings.giteaUrl ?? ''));
async function saveGitea(): Promise<void> {
try {
await settings.save({ giteaUrl: giteaInput.value.trim() || null });
giteaInput.value = settings.giteaUrl ?? '';
toasts.success(t('settings.saved'));
} catch (e) {
toasts.error(e);
}
}
// ---- Découverte des dépôts ----
const rootsDraft = ref<string[]>([]);
const intervalDraft = ref(0);
const showRootPicker = ref(false);
const discoveryDirty = computed(
() =>
intervalDraft.value !== settings.scanIntervalMin ||
rootsDraft.value.length !== settings.scanRoots.length ||
rootsDraft.value.some((r, i) => r !== settings.scanRoots[i]),
);
function syncDiscoveryDraft(): void {
rootsDraft.value = [...settings.scanRoots];
intervalDraft.value = settings.scanIntervalMin;
}
function onAddRoot(path: string): void {
if (!rootsDraft.value.includes(path)) rootsDraft.value.push(path);
showRootPicker.value = false;
}
async function saveDiscovery(): Promise<void> {
try {
await settings.save({ scanRoots: rootsDraft.value, scanIntervalMin: intervalDraft.value });
syncDiscoveryDraft();
toasts.success(t('settings.saved'));
} catch (e) {
toasts.error(e);
}
}
onMounted(async () => {
await Promise.all([loadTokens(), settings.loaded ? Promise.resolve() : settings.fetch()]);
giteaInput.value = settings.giteaUrl ?? '';
syncDiscoveryDraft();
void push.refresh();
});
</script>

View File

@@ -0,0 +1,352 @@
// Contenu de l'onglet Aide, bilingue. Texte long-format → gardé hors des fichiers i18n
// (en.ts/fr.ts) pour ne pas les alourdir. HelpView mappe chaque `id` vers une icône Lucide.
import type { AppLocale } from '../i18n';
export interface HelpItem {
title: string;
body: string;
}
export interface HelpSection {
id: string;
title: string;
blurb: string;
items: HelpItem[];
}
const en: HelpSection[] = [
{
id: 'gettingStarted',
title: 'Getting started & access',
blurb:
'Arboretum is a single daemon that serves this dashboard to drive your git worktrees and the Claude Code sessions running on them, from any device.',
items: [
{
title: 'Sign in with a token',
body: 'On first start the daemon prints a one-time access token. Paste it on the login screen. You can create extra tokens (one per device) and revoke old ones in Settings → Access & security.',
},
{
title: 'Remote access via Tailscale Serve',
body: 'The daemon binds to 127.0.0.1. To reach it from your phone, run tailscale serve --bg 7317 and start Arboretum with --allow-origin https://<machine>.<tailnet>.ts.net. The HTTPS that Tailscale provides is also what makes Web Push work.',
},
{
title: 'Install as an app (PWA)',
body: 'On mobile, open Arboretum and choose Add to Home Screen. On iOS this install step is required before notifications can work.',
},
],
},
{
id: 'worktrees',
title: 'Repositories & worktrees',
blurb: 'Register your git repos, then spin up an isolated worktree per branch — each can auto-start a session.',
items: [
{
title: 'Add a repository',
body: 'On the Worktrees page, type or browse to the absolute path of a git repo and add it. Per-repo post-create hooks (e.g. npm ci) run automatically on new worktrees.',
},
{
title: 'Create a worktree',
body: 'In a repo section, click New worktree, enter a branch (optionally create it), and optionally start a claude or bash session in it. Hooks run automatically.',
},
{
title: 'Read worktree state',
body: 'Each card shows the branch, ahead/behind counts, dirty file count and flags (main, locked, prunable), plus the live state of any linked session.',
},
{
title: 'Delete & prune',
body: 'Delete a worktree from its card (force-delete if dirty or locked), or prune all orphaned worktrees at the repo level.',
},
],
},
{
id: 'sessions',
title: 'Sessions & the web terminal',
blurb: 'Run, observe, resume and answer Claude Code (or bash) sessions in a full xterm terminal, right in the browser.',
items: [
{
title: 'Start a session',
body: 'On the Sessions page, set a working directory and a command (claude or bash) and launch. Open it to get an interactive terminal.',
},
{
title: 'Discovered sessions',
body: 'Sessions you start in your own terminal are detected automatically and tagged as discovered. Observe them read-only, or resume/fork them once stopped.',
},
{
title: 'Resume & fork',
body: 'Resume restarts a stopped session in its original working directory, with full scrollback replayed. Fork creates a fresh independent copy with the same command and cwd.',
},
{
title: 'Observe vs interact',
body: 'Anyone opening a live session can type; open it as an observer for read-only monitoring that never slows the session down.',
},
{
title: 'Fine-grained state',
body: 'Managed Claude sessions report waiting / busy / idle in real time. Waiting sessions are surfaced first and can trigger notifications.',
},
{
title: 'Kill a session',
body: 'Kill a live session from its row (confirm to avoid accidents); it receives SIGTERM, then SIGKILL after a short grace delay.',
},
],
},
{
id: 'mobile',
title: 'Mobile supervision',
blurb: 'Keep sessions moving from your phone, without opening a terminal.',
items: [
{
title: 'Needs attention',
body: 'A banner at the top of the dashboard lists every session blocked on a dialog, with inline answer buttons.',
},
{
title: 'Answer dialogs',
body: 'When Claude asks for trust, a permission or a choice, pick an option (or Deny) right from the card — no terminal needed.',
},
{
title: 'Web Push notifications',
body: 'Enable notifications in Settings (or the footer bell). You get a push when a session starts waiting; tap it to answer. Requires HTTPS; on iOS, install the app first.',
},
],
},
{
id: 'groups',
title: 'Work groups',
blurb: 'Bundle related repos (API, web, shared lib…) and operate on them together.',
items: [
{
title: 'Create a group',
body: 'On the Groups page, name a group and pick its repos. Membership is lightweight and editable anytime.',
},
{
title: 'List vs terminal grid',
body: 'A group view shows all its repos worktrees and sessions as a list, or switch to the terminal grid to watch several live sessions side by side.',
},
{
title: 'Cross-repo feature',
body: 'Create the same worktree (and an optional session) across every repo of the group in one action; partial failures can be retried per repo.',
},
],
},
{
id: 'productivity',
title: 'Productivity',
blurb: 'Find anything fast and tailor each list.',
items: [
{
title: 'Command palette',
body: 'Press ⌘K (or Ctrl+K) to fuzzy-jump to any repo, worktree, session or group, or to run a quick action.',
},
{
title: 'Sort, filter & search',
body: 'Every list has a toolbar to sort, filter (state, command, source, flags…) and search. Your choices persist in the URL, so links are shareable.',
},
{
title: 'Pagination',
body: 'Long lists are paginated with a configurable page size; choose All to show everything at once.',
},
{
title: 'Language',
body: 'Switch the interface between English and French anytime, from Settings or the footer.',
},
],
},
{
id: 'settings',
title: 'Settings & security',
blurb: 'Configure the app and manage who can reach the daemon.',
items: [
{
title: 'Notifications',
body: 'Enable or disable Web Push and send a test notification from Settings → Preferences.',
},
{
title: 'Access tokens',
body: 'Create a token per device and revoke any you no longer trust. A new token value is shown only once — copy it immediately. The last active token cannot be revoked, to avoid locking yourself out.',
},
{
title: 'Server info',
body: 'Settings → Server shows the running version and the startup configuration (port, bind, allowed origins, data directory, VAPID). These are set via CLI flags and need a daemon restart to change.',
},
],
},
{
id: 'integrations',
title: 'Integrations',
blurb: 'Shortcuts to the tools around your repos.',
items: [
{
title: 'Gitea',
body: 'Set your Gitea instance URL in Settings → Integrations to add a one-click Gitea icon to the navigation. Leave it empty to hide the icon.',
},
],
},
];
const fr: HelpSection[] = [
{
id: 'gettingStarted',
title: 'Prise en main & accès',
blurb:
'Arboretum est un daemon unique qui sert ce dashboard pour piloter vos worktrees git et les sessions Claude Code qui tournent dessus, depuis nimporte quel appareil.',
items: [
{
title: 'Se connecter avec un jeton',
body: 'Au premier démarrage, le daemon affiche un jeton daccès à usage unique. Collez-le sur lécran de connexion. Vous pouvez créer des jetons supplémentaires (un par appareil) et révoquer les anciens dans Réglages → Accès & sécurité.',
},
{
title: 'Accès distant via Tailscale Serve',
body: 'Le daemon écoute sur 127.0.0.1. Pour y accéder depuis votre téléphone, lancez tailscale serve --bg 7317 et démarrez Arboretum avec --allow-origin https://<machine>.<tailnet>.ts.net. Le HTTPS fourni par Tailscale est aussi ce qui permet au Web Push de fonctionner.',
},
{
title: 'Installer comme une app (PWA)',
body: 'Sur mobile, ouvrez Arboretum et choisissez Ajouter à lécran daccueil. Sur iOS, cette installation est requise avant que les notifications puissent fonctionner.',
},
],
},
{
id: 'worktrees',
title: 'Dépôts & worktrees',
blurb: 'Enregistrez vos dépôts git, puis créez un worktree isolé par branche — chacun peut démarrer une session automatiquement.',
items: [
{
title: 'Ajouter un dépôt',
body: 'Sur la page Worktrees, saisissez (ou parcourez) le chemin absolu dun dépôt git et ajoutez-le. Les hooks post-création par dépôt (ex. npm ci) sexécutent automatiquement sur les nouveaux worktrees.',
},
{
title: 'Créer un worktree',
body: 'Dans une section de dépôt, cliquez sur Nouveau worktree, saisissez une branche (à créer éventuellement) et démarrez si besoin une session claude ou bash. Les hooks sexécutent automatiquement.',
},
{
title: 'Lire létat dun worktree',
body: 'Chaque carte affiche la branche, lavance/le retard, le nombre de fichiers modifiés et des indicateurs (main, verrouillé, élagable), ainsi que létat en direct de la session liée.',
},
{
title: 'Supprimer & élaguer',
body: 'Supprimez un worktree depuis sa carte (suppression forcée sil est sale ou verrouillé), ou élaguez tous les worktrees orphelins au niveau du dépôt.',
},
],
},
{
id: 'sessions',
title: 'Sessions & terminal web',
blurb: 'Lancez, observez, reprenez et répondez aux sessions Claude Code (ou bash) dans un vrai terminal xterm, directement dans le navigateur.',
items: [
{
title: 'Démarrer une session',
body: 'Sur la page Sessions, indiquez un répertoire de travail et une commande (claude ou bash) puis lancez. Ouvrez-la pour obtenir un terminal interactif.',
},
{
title: 'Sessions découvertes',
body: 'Les sessions lancées dans votre propre terminal sont détectées automatiquement et marquées « découvertes ». Observez-les en lecture seule, ou reprenez/forkez-les une fois arrêtées.',
},
{
title: 'Reprendre & forker',
body: 'Reprendre relance une session arrêtée dans son répertoire dorigine, avec tout lhistorique rejoué. Forker crée une copie indépendante neuve avec la même commande et le même cwd.',
},
{
title: 'Observer ou interagir',
body: 'Quiconque ouvre une session vivante peut écrire ; ouvrez-la en observateur pour une supervision en lecture seule qui ne ralentit jamais la session.',
},
{
title: 'États fins',
body: 'Les sessions Claude gérées rapportent en temps réel les états en attente / occupé / inactif. Les sessions en attente sont remontées en premier et peuvent déclencher des notifications.',
},
{
title: 'Arrêter une session',
body: 'Arrêtez une session vivante depuis sa ligne (confirmation pour éviter les accidents) ; elle reçoit SIGTERM, puis SIGKILL après un court délai de grâce.',
},
],
},
{
id: 'mobile',
title: 'Supervision mobile',
blurb: 'Faites avancer vos sessions depuis votre téléphone, sans ouvrir de terminal.',
items: [
{
title: 'À traiter',
body: 'Une bannière en haut du dashboard liste toutes les sessions bloquées sur un dialogue, avec des boutons de réponse en ligne.',
},
{
title: 'Répondre aux dialogues',
body: 'Quand Claude demande une confiance, une permission ou un choix, sélectionnez une option (ou Refuser) directement depuis la carte — sans terminal.',
},
{
title: 'Notifications Web Push',
body: 'Activez les notifications dans Réglages (ou via la cloche du pied de page). Vous recevez un push quand une session passe en attente ; touchez-le pour répondre. Exige HTTPS ; sur iOS, installez dabord lapp.',
},
],
},
{
id: 'groups',
title: 'Groupes de travail',
blurb: 'Regroupez des dépôts liés (API, web, lib partagée…) et agissez dessus ensemble.',
items: [
{
title: 'Créer un groupe',
body: 'Sur la page Groupes, nommez un groupe et choisissez ses dépôts. Lappartenance est légère et modifiable à tout moment.',
},
{
title: 'Liste ou grille de terminaux',
body: 'La vue dun groupe affiche les worktrees et sessions de tous ses dépôts en liste, ou basculez sur la grille de terminaux pour suivre plusieurs sessions vivantes côte à côte.',
},
{
title: 'Feature cross-repo',
body: 'Créez le même worktree (et une session optionnelle) dans chaque dépôt du groupe en une seule action ; les échecs partiels sont rejouables dépôt par dépôt.',
},
],
},
{
id: 'productivity',
title: 'Productivité',
blurb: 'Trouvez tout rapidement et adaptez chaque liste.',
items: [
{
title: 'Palette de commandes',
body: 'Appuyez sur ⌘K (ou Ctrl+K) pour sauter en recherche floue vers nimporte quel dépôt, worktree, session ou groupe, ou lancer une action rapide.',
},
{
title: 'Trier, filtrer & rechercher',
body: 'Chaque liste a une barre doutils pour trier, filtrer (état, commande, source, indicateurs…) et rechercher. Vos choix persistent dans lURL, donc les liens sont partageables.',
},
{
title: 'Pagination',
body: 'Les longues listes sont paginées avec une taille de page configurable ; choisissez Tout pour afficher lensemble.',
},
{
title: 'Langue',
body: 'Basculez linterface entre langlais et le français à tout moment, depuis les Réglages ou le pied de page.',
},
],
},
{
id: 'settings',
title: 'Réglages & sécurité',
blurb: 'Configurez lapplication et gérez qui peut atteindre le daemon.',
items: [
{
title: 'Notifications',
body: 'Activez ou désactivez le Web Push et envoyez une notification de test depuis Réglages → Préférences.',
},
{
title: 'Jetons daccès',
body: 'Créez un jeton par appareil et révoquez ceux en lesquels vous navez plus confiance. La valeur dun nouveau jeton nest affichée quune seule fois — copiez-la immédiatement. Le dernier jeton actif ne peut pas être révoqué, pour éviter de vous verrouiller dehors.',
},
{
title: 'Infos serveur',
body: 'Réglages → Serveur affiche la version en cours et la configuration de démarrage (port, bind, origines autorisées, répertoire de données, VAPID). Ces valeurs se définissent via des flags CLI et nécessitent un redémarrage du daemon.',
},
],
},
{
id: 'integrations',
title: 'Intégrations',
blurb: 'Des raccourcis vers les outils autour de vos dépôts.',
items: [
{
title: 'Gitea',
body: 'Renseignez lURL de votre instance Gitea dans Réglages → Intégrations pour ajouter une icône Gitea en un clic dans la navigation. Laissez vide pour masquer licône.',
},
],
},
];
export const helpSections: Record<AppLocale, HelpSection[]> = { en, fr };