Ajoute le choix « créer un worktree OU bosser sur la branche principale » au moment de démarrer le travail, sur deux surfaces : - bouton « Démarrer » (claude/bash) sur chaque WorktreeCard, y compris le checkout principal (badge « principal ») — comblait un manque : impossible jusqu'ici de lancer une session sur un worktree existant depuis le dashboard ; - toggle de mode (Worktree / Branche principale) dans le formulaire d'entête de RepoSection. Option git « créer & basculer » : nouvel endpoint POST /api/v1/repos/:id/session qui lance UNE session dans le checkout principal (repo.path), avec création ou bascule de branche optionnelle (git switch[-c]) — refusée en 409 si l'arbre est sale. Pas de hooks ni de pré-trust (c'est le dépôt réel de l'utilisateur). - shared : type additif StartRepoSessionRequest. - server : git.switchBranch + WorktreeManager.startMainSession + route. - web : store worktrees.startMainSession, UI WorktreeCard/RepoSection, i18n fr/en. - tests : +5 unitaires (switchBranch, startMainSession) ; acceptance-p3 étendue.
160 lines
7.5 KiB
JavaScript
160 lines
7.5 KiB
JavaScript
#!/usr/bin/env node
|
|
// Acceptation P3 (sans navigateur, sans quota Claude) : worktrees multi-repo + dashboard.
|
|
// Vrai daemon + vrai repo git tmp. Couvre : enregistrement repo, création worktree avec hook
|
|
// post-create, broadcast WS worktree_update, corrélation worktree↔session (bash), suppression.
|
|
import { spawn, execFileSync } from 'node:child_process';
|
|
import { mkdtempSync, rmSync, existsSync, writeFileSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import { join, dirname, basename } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { createRequire } from 'node:module';
|
|
|
|
const require = createRequire(import.meta.url);
|
|
const WebSocket = require('ws');
|
|
|
|
const PORT = 7543;
|
|
const ORIGIN = `http://127.0.0.1:${PORT}`;
|
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
const results = [];
|
|
const check = (name, ok, detail = '') => {
|
|
results.push({ name, ok, detail });
|
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`);
|
|
};
|
|
|
|
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p3-'));
|
|
const repo = join(tmp, 'demo-repo');
|
|
const wtPath = join(tmp, 'demo-repo-wt-feat');
|
|
execFileSync('mkdir', ['-p', repo]);
|
|
const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' });
|
|
git('init', '-b', 'main');
|
|
git('config', 'user.email', 'test@arboretum.dev');
|
|
git('config', 'user.name', 'Test');
|
|
execFileSync('bash', ['-lc', 'echo "# demo" > README.md'], { cwd: repo });
|
|
git('add', '-A');
|
|
git('commit', '-m', 'init');
|
|
|
|
const srv = spawn(
|
|
'node',
|
|
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
|
|
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
|
|
);
|
|
let srvOut = '';
|
|
srv.stdout.on('data', (d) => (srvOut += d));
|
|
srv.stderr.on('data', (d) => (srvOut += d));
|
|
|
|
function wsClient(cookie) {
|
|
const ws = new WebSocket(`ws://127.0.0.1:${PORT}/ws`, { headers: { Origin: ORIGIN, Cookie: cookie } });
|
|
const state = { msgs: [] };
|
|
ws.on('message', (data, isBinary) => {
|
|
if (!isBinary) state.msgs.push(JSON.parse(String(data)));
|
|
});
|
|
const waitMsg = async (pred, timeout = 8000) => {
|
|
const t0 = Date.now();
|
|
while (Date.now() - t0 < timeout) {
|
|
const m = state.msgs.find(pred);
|
|
if (m) return m;
|
|
await sleep(50);
|
|
}
|
|
return null;
|
|
};
|
|
return { ws, state, waitMsg, send: (m) => ws.send(JSON.stringify(m)) };
|
|
}
|
|
|
|
const j = (path, method, cookie, body) =>
|
|
fetch(`${ORIGIN}${path}`, {
|
|
method,
|
|
headers: { Origin: ORIGIN, Cookie: cookie, ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
|
...(body ? { body: JSON.stringify(body) } : {}),
|
|
});
|
|
|
|
try {
|
|
await sleep(1500);
|
|
const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0];
|
|
check('boot + token bootstrap', !!token);
|
|
|
|
const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json', Origin: ORIGIN },
|
|
body: JSON.stringify({ token }),
|
|
});
|
|
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? '';
|
|
check('login → cookie', login.status === 200);
|
|
|
|
const c = wsClient(cookie);
|
|
await new Promise((res, rej) => (c.ws.on('open', res), c.ws.on('error', rej)));
|
|
c.send({ type: 'hello', protocol: 1 });
|
|
await c.waitMsg((m) => m.type === 'hello_ok');
|
|
c.send({ type: 'sub', topics: ['sessions', 'worktrees'] });
|
|
|
|
// Enregistrement du repo (avec un hook post-create).
|
|
const addRepo = await j('/api/v1/repos', 'POST', cookie, {
|
|
path: repo,
|
|
postCreateHooks: [{ id: 'h1', label: 'touch', run: 'touch hook-ok.txt', enabled: true }],
|
|
});
|
|
const repoSummary = (await addRepo.json()).repo;
|
|
check('POST /repos → 201 (repo valide)', addRepo.status === 201 && repoSummary?.valid === true);
|
|
|
|
const wlist0 = await (await j('/api/v1/worktrees', 'GET', cookie)).json();
|
|
check('GET /worktrees → main worktree présent', wlist0.worktrees.some((w) => w.isMain && w.branch === 'main'));
|
|
|
|
// Création d'un worktree + hook + session bash.
|
|
const created = await j(`/api/v1/repos/${repoSummary.id}/worktrees`, 'POST', cookie, {
|
|
branch: 'feat',
|
|
newBranch: true,
|
|
runHooks: true,
|
|
startSession: 'bash',
|
|
});
|
|
const createdBody = await created.json();
|
|
check('POST worktree → 201', created.status === 201 && createdBody.worktree?.branch === 'feat');
|
|
check('hook post-create exécuté', createdBody.hookResults?.[0]?.exitCode === 0 && existsSync(join(wtPath, 'hook-ok.txt')));
|
|
check('startSession bash → session managée', createdBody.session?.command === 'bash');
|
|
|
|
const pushed = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.branch === 'feat');
|
|
check('broadcast WS worktree_update', !!pushed);
|
|
|
|
// Corrélation worktree ↔ session par cwd.
|
|
await sleep(300);
|
|
const wlist1 = await (await j('/api/v1/worktrees', 'GET', cookie)).json();
|
|
const feat = wlist1.worktrees.find((w) => w.branch === 'feat');
|
|
check('corrélation worktree ↔ session (cwd)', feat?.sessions?.some((s) => s.command === 'bash' && s.live));
|
|
|
|
// Session sur le checkout principal (« bosser sur la branche principale ») avec création de branche.
|
|
const mainSess = await j(`/api/v1/repos/${repoSummary.id}/session`, 'POST', cookie, { command: 'bash', branch: 'mainfeat', newBranch: true });
|
|
const mainBody = await mainSess.json();
|
|
check('POST repo session → 201 (bash)', mainSess.status === 201 && mainBody.session?.command === 'bash');
|
|
check('session de branche principale : cwd = checkout principal', mainBody.session?.cwd === repoSummary.path);
|
|
const mainPush = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.isMain && m.worktree?.branch === 'mainfeat');
|
|
check('broadcast worktree_update (branche principale basculée)', !!mainPush);
|
|
await sleep(300);
|
|
const wlistM = await (await j('/api/v1/worktrees', 'GET', cookie)).json();
|
|
const mainWt = wlistM.worktrees.find((w) => w.isMain);
|
|
check('session corrélée au checkout principal', mainWt?.branch === 'mainfeat' && mainWt.sessions.some((s) => s.id === mainBody.session.id));
|
|
|
|
// Refus 409 quand le checkout principal est sale.
|
|
writeFileSync(join(repo, 'scratch.txt'), 'wip\n');
|
|
const dirtyRefused = await j(`/api/v1/repos/${repoSummary.id}/session`, 'POST', cookie, { command: 'bash', branch: 'other', newBranch: true });
|
|
check('repo session sur checkout sale → 409', dirtyRefused.status === 409);
|
|
rmSync(join(repo, 'scratch.txt'), { force: true });
|
|
|
|
// Suppression forcée (une session vit dans le worktree).
|
|
const refused = await j(`/api/v1/repos/${repoSummary.id}/worktrees?path=${encodeURIComponent(wtPath)}&force=false`, 'DELETE', cookie);
|
|
check('delete sans force (session live) → 409', refused.status === 409);
|
|
const del = await j(`/api/v1/repos/${repoSummary.id}/worktrees?path=${encodeURIComponent(wtPath)}&force=true`, 'DELETE', cookie);
|
|
check('delete force → 200', del.status === 200);
|
|
const removed = await c.waitMsg((m) => m.type === 'worktree_removed', 8000);
|
|
check('broadcast WS worktree_removed', !!removed);
|
|
|
|
c.ws.close();
|
|
} catch (err) {
|
|
check('exception', false, String(err));
|
|
} finally {
|
|
srv.kill('SIGTERM');
|
|
await sleep(1500);
|
|
check('arrêt propre du daemon (SIGTERM)', srv.exitCode === 0 || srv.signalCode === null || srv.exitCode === null);
|
|
rmSync(tmp, { recursive: true, force: true });
|
|
const failed = results.filter((r) => !r.ok);
|
|
console.log(failed.length === 0 ? '\nACCEPTANCE P3: ALL GREEN' : `\nACCEPTANCE P3: ${failed.length} FAILURE(S)`);
|
|
process.exit(failed.length === 0 ? 0 : 1);
|
|
}
|