feat(p8): vue IDE /workspace (arbre + Monaco + diff + terminal)

- backend: garde-fou conflit d'édition par mtime (GET renvoie mtime, PUT refuse en 409 STALE_FILE si baseMtime périmé)
- lib: wt-key (base64url du chemin worktree), diff-parse (parseur pur du diff unifié → hunks)
- composables: useMonaco (import dynamique → chunk isolé), useWorkspaceLayout (largeurs/panneau persistés)
- components/workspace: GitStatusBadge, FileTree+FileTreeNode (lazy fs/list includeFiles), ChangedFilesPanel, DiffViewer (coloration +/-), MonacoEditor (Ctrl+S + bannière conflit reload/overwrite)
- views/WorkspaceView: 3 colonnes desktop redimensionnables + SegmentedControl mobile, header live (GitStatusBadge), watchWorktree → refresh diff/changements, terminal de la session corrélée
- router meta 'ide' + route /workspace/:repoId/:wt ; App.vue plein écran sans AppShell ; WorktreeCard bouton « Ouvrir l'IDE »
- deps: monaco-editor (lazy, vendor-monaco isolé, 0 impact bundle initial) ; vite manualChunks
- i18n EN+FR (workspace/editor/diff/git) ; tests diff-parse + wt-key ; acceptance-p8.mjs (mtime/409 + diff)
This commit is contained in:
2026-06-27 13:47:10 +02:00
parent c8dd539571
commit 75efecf93f
26 changed files with 1142 additions and 6 deletions

View File

@@ -0,0 +1,122 @@
#!/usr/bin/env node
// Acceptation P8 (sans navigateur) : API fichiers de l'éditeur Monaco + garde-fou conflit (mtime).
// Vrai daemon + vrai repo git tmp. Couvre : GET content (+mtime), PUT avec baseMtime correct → 200,
// PUT avec baseMtime périmé → 409 STALE_FILE, PUT sans baseMtime (overwrite) → 200, diff après
// édition cohérent, fs/list?includeFiles=1 (isFile), refus de traversal.
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const PORT = 7552;
const ORIGIN = `http://127.0.0.1:${PORT}`;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
const results = [];
const check = (name, ok, detail = '') => {
results.push({ name, ok, detail });
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `${detail}` : ''}`);
};
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p8-'));
const repo = join(tmp, 'demo-repo');
execFileSync('mkdir', ['-p', repo]);
const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' });
git('init', '-b', 'main');
git('config', 'user.email', 'test@arboretum.dev');
git('config', 'user.name', 'Test');
writeFileSync(join(repo, 'README.md'), '# demo\n');
git('add', '-A');
git('commit', '-m', 'init');
const srv = spawn(
'node',
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
);
let srvOut = '';
srv.stdout.on('data', (d) => (srvOut += d));
srv.stderr.on('data', (d) => (srvOut += d));
const j = (path, method, cookie, body) =>
fetch(`${ORIGIN}${path}`, {
method,
headers: { Origin: ORIGIN, Cookie: cookie, ...(body ? { 'Content-Type': 'application/json' } : {}) },
...(body ? { body: JSON.stringify(body) } : {}),
});
try {
await sleep(1500);
const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0];
check('boot + token bootstrap', !!token);
const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Origin: ORIGIN },
body: JSON.stringify({ token }),
});
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? '';
check('login → cookie', login.status === 200);
const addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo });
const repoId = (await addRepo.json()).repo.id;
check('POST /repos → 201', addRepo.status === 201 && !!repoId);
const enc = encodeURIComponent(repo);
// ---- GET content : contenu + mtime ----
const get1 = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=README.md`, 'GET', cookie)).json();
check('GET /files/content : contenu + mtime', get1.content === '# demo\n' && typeof get1.mtime === 'number');
const mtime0 = get1.mtime;
// ---- PUT avec baseMtime correct → 200 + nouveau mtime ----
const put1 = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, {
wt: repo, path: 'README.md', content: '# demo\nedited via editor\n', baseMtime: mtime0,
});
const put1Body = await put1.json();
check('PUT (baseMtime correct) → 200 + mtime', put1.status === 200 && typeof put1Body.mtime === 'number');
// ---- PUT avec baseMtime périmé (l'ancien) → 409 STALE_FILE ----
const putStale = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, {
wt: repo, path: 'README.md', content: 'concurrent overwrite\n', baseMtime: mtime0,
});
const staleBody = await putStale.json();
check('PUT (baseMtime périmé) → 409 STALE_FILE', putStale.status === 409 && staleBody.error?.code === 'STALE_FILE');
// ---- PUT sans baseMtime (overwrite forcé) → 200 ----
const putForce = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, {
wt: repo, path: 'README.md', content: '# demo\nforced\n',
});
check('PUT (sans baseMtime, overwrite) → 200', putForce.status === 200);
// ---- diff après édition ----
const ch = await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json();
check('GET /changes : README.md modifié', (ch.changes ?? []).some((c) => c.path === 'README.md' && c.unstaged));
const diff = await (await j(`/api/v1/repos/${repoId}/worktrees/diff?path=${enc}&file=README.md`, 'GET', cookie)).json();
check('GET /diff : contient la ligne ajoutée', typeof diff.diff === 'string' && diff.diff.includes('+forced'));
// ---- création d'un nouveau fichier + lecture du langage ----
const putNew = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, { wt: repo, path: 'src/app.ts', content: 'export const x = 1\n' });
check('PUT (création src/app.ts) → 200', putNew.status === 200);
const getNew = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=src/app.ts`, 'GET', cookie)).json();
check('GET nouveau fichier : langage typescript', getNew.language === 'typescript');
// ---- fs/list?includeFiles=1 : remonte les fichiers (arbre IDE) ----
const fs = await (await j(`/api/v1/fs/list?path=${enc}&includeFiles=1`, 'GET', cookie)).json();
const readme = (fs.entries ?? []).find((e) => e.name === 'README.md');
check('fs/list?includeFiles=1 : README.md (isFile)', readme?.isFile === true);
// ---- refus de traversal ----
const trav = await j(`/api/v1/repos/${repoId}/files/content`, 'PUT', cookie, { wt: repo, path: '../escape.txt', content: 'x' });
check('PUT traversal ../ refusé', trav.status === 400 || trav.status === 403);
} catch (err) {
check('exception', false, String(err));
} finally {
srv.kill('SIGTERM');
await sleep(1500);
check('arrêt propre du daemon (SIGTERM)', srv.exitCode === 0 || srv.signalCode === null || srv.exitCode === null);
rmSync(tmp, { recursive: true, force: true });
const failed = results.filter((r) => !r.ok);
console.log(failed.length === 0 ? '\nACCEPTANCE P8: ALL GREEN' : `\nACCEPTANCE P8: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}

View File

@@ -54,6 +54,7 @@ export function registerFileRoutes(app: FastifyInstance, wt: WorktreeManager, db
content: buf.toString('utf-8'),
encoding: 'utf-8',
size: st.size,
mtime: st.mtimeMs,
...(lang ? { language: lang } : {}),
};
return reply.send(res);
@@ -74,10 +75,19 @@ export function registerFileRoutes(app: FastifyInstance, wt: WorktreeManager, db
}
try {
const abs = await wt.assertPathInWorktree(id, body.wt, body.path);
// Garde-fou conflit (P8) : si le client a chargé le fichier (baseMtime) et qu'il a changé
// depuis (ex. Claude a écrit en parallèle), on refuse pour ne pas écraser silencieusement.
if (typeof body.baseMtime === 'number') {
const cur = await stat(abs).catch(() => null);
if (cur && cur.isFile() && cur.mtimeMs !== body.baseMtime) {
return reply.status(409).send({ error: { code: 'STALE_FILE', message: 'File changed on disk since it was loaded' } });
}
}
await mkdir(dirname(abs), { recursive: true }); // dirname reste sous le worktree (abs validé)
await writeFile(abs, body.content, 'utf-8');
const after = await stat(abs);
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'file.write', resourceId: id, details: { path: body.path } });
const res: WriteFileResponse = { ok: true, size: Buffer.byteLength(body.content, 'utf-8') };
const res: WriteFileResponse = { ok: true, size: Buffer.byteLength(body.content, 'utf-8'), mtime: after.mtimeMs };
return reply.send(res);
} catch (err) {
return sendManagerError(reply, err);