diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 6465acf0..3235a2d1 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -968,6 +968,14 @@ async function api(req, res, path, method, url) { if (!found) return error(res, 404, 'No such Time-skip run.'); return json(res, 200, found); } + /* One picture of a run, original or updated, for the Compare view. Only pictures inside the run's own folders; served as an image and nothing else. */ + if (path === '/api/timeskip/file' && method === 'GET') { + const found = timeskip.image(url.searchParams.get('id'), url.searchParams.get('path'), url.searchParams.get('version')); + if (!found) return error(res, 404, 'No such picture in this Time-skip run.'); + res.writeHead(200, { 'content-type': found.type, 'cache-control': 'private, max-age=300', 'x-content-type-options': 'nosniff', 'content-security-policy': "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:" }); + createReadStream(found.path).pipe(res); + return; + } if (path === '/api/timeskip/stop' && method === 'POST') { const body = await readBody(req); return json(res, 200, { stopped: timeskip.cancel(String(body.id ?? '')) }); diff --git a/apps/host/server/timeskip.mjs b/apps/host/server/timeskip.mjs index 0b05d592..61475e42 100644 --- a/apps/host/server/timeskip.mjs +++ b/apps/host/server/timeskip.mjs @@ -19,7 +19,7 @@ */ import { spawn } from 'node:child_process'; import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'; -import { join, relative } from 'node:path'; +import { isAbsolute, join, relative, resolve } from 'node:path'; import { timeSkipDir } from './platform-paths.mjs'; /** Where runs are recorded. Mirrors the CLI's own default resolution. */ @@ -160,15 +160,36 @@ export function measureFolder(root, { maxFiles = 3000, maxBytes = 300 * 1024 * 1 * What a run changed, file by file: the saved original against the revision, for the Compare view. * Reads the folders the job itself kept; it decides nothing. */ -export function diffRun(record) { +/** Pictures the Compare view shows side by side (read as bytes through /api/timeskip/file, never as text). */ +export const IMAGE_TYPES = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml', bmp: 'image/bmp' }; +const MAX_IMAGE_BYTES = 12 * 1024 * 1024; +export const imageTypeOf = path => IMAGE_TYPES[String(path).split('.').pop().toLowerCase()] ?? null; + +/** The two folders a run compares: the saved original and the revision (or the last attempt when the checks kept nothing). */ +export function runRoots(record) { const baseline = (record.checkpoints ?? []).find(c => c.label === 'baseline'); const selected = (record.checkpoints ?? []).find(c => c.id === record.selected_checkpoint); const attempts = record.attempts ?? []; const last = attempts[attempts.length - 1] ?? null; - // A kept checkpoint is the revision; when nothing was kept (the checks could not decide) the person looks at the last attempt. const useAttempt = !selected || selected.id === baseline?.id; - const updatedRoot = useAttempt ? last?.path : selected?.path; - const baseRoot = baseline?.path; + return { baseRoot: baseline?.path ?? null, updatedRoot: (useAttempt ? last?.path : selected?.path) ?? null, useAttempt, last }; +} + +/** The absolute path of one picture of a run, for one side, or null: not a picture, not inside the run's folder, missing or too big. */ +export function runImagePath(record, relPath, version) { + if (!imageTypeOf(relPath)) return null; + const { baseRoot, updatedRoot } = runRoots(record); + const root = version === 'original' ? baseRoot : version === 'updated' ? updatedRoot : null; + if (!root) return null; + const full = resolve(root, ...String(relPath).split('/')); + const inside = relative(resolve(root), full); + if (!inside || inside.startsWith('..') || isAbsolute(inside)) return null; + try { const st = statSync(full); return st.isFile() && st.size <= MAX_IMAGE_BYTES ? full : null; } catch { return null; } +} + +export function diffRun(record) { + // A kept checkpoint is the revision; when nothing was kept (the checks could not decide) the person looks at the last attempt. + const { baseRoot, updatedRoot, useAttempt, last } = runRoots(record); if (!baseRoot || !updatedRoot) return { files: [], applyAttempt: null, more: 0 }; const paths = [...new Set([...walkFiles(baseRoot), ...walkFiles(updatedRoot)])].sort(); const files = []; @@ -178,6 +199,15 @@ export function diffRun(record) { const status = a.missing ? 'added' : b.missing ? 'removed' : null; const same = !status && a.text !== undefined && a.text === b.text; if (same) continue; + if (imageTypeOf(path)) { + // A picture is compared as bytes and shown from the file itself, never read as text. + let differs = true; + try { differs = a.missing || b.missing || !readFileSync(join(baseRoot, path)).equals(readFileSync(join(updatedRoot, path))); } catch { /* treat as changed */ } + if (!differs) continue; + if (files.length >= MAX_LISTED) { more += 1; continue; } + files.push({ path, status: status ?? 'changed', image: true }); + continue; + } if (!status && !a.text && !b.text && !a.big && !b.big) { // Both binary: compare sizes only. try { if (statSync(join(baseRoot, path)).size === statSync(join(updatedRoot, path)).size && readFileSync(join(baseRoot, path)).equals(readFileSync(join(updatedRoot, path)))) continue; } catch { /* treat as changed */ } @@ -290,6 +320,14 @@ export function createTimeSkip({ repoRoot, python, pythonArgs = [], timeoutMs = return run ? diffRun(run) : null; }, + /** One picture of a run (original or updated), for the Compare view: { path, type } or null. */ + image: (id, relPath, version) => { + if (!/^[0-9a-f]{8,64}$/.test(String(id ?? ''))) return null; + const run = readRun(stateDir(env), id); + const full = run ? runImagePath(run, relPath, version) : null; + return full ? { path: full, type: imageTypeOf(relPath) } : null; + }, + /** Stop a run this host is driving. The saved version stays; the run reads as interrupted. */ cancel: id => { const child = live.get(id); diff --git a/apps/host/src/components/TimeSkipCompare.tsx b/apps/host/src/components/TimeSkipCompare.tsx new file mode 100644 index 00000000..f29ecffc --- /dev/null +++ b/apps/host/src/components/TimeSkipCompare.tsx @@ -0,0 +1,111 @@ +import { useEffect, useMemo, useState } from 'react'; +import { tr } from '../lib/i18n'; +import type { TimeSkipFile } from '../lib/time-skip'; +import { diffStats, fileKind, htmlPreviewDocument, lineDiff, segmentLines, timeSkipImageUrl, wordDiff, type Segment } from '../lib/time-skip-compare'; +import { Btn, Dialog, Icon } from './ui'; + +const baseName = (path: string) => path.split('/').pop() || path; +const statusText = (status: TimeSkipFile['status']) => tr(status === 'added' ? 'new' : status === 'removed' ? 'removed' : 'changed'); + +/** Lines of marked words laid out as the document they are: headings, list items, code fences and paragraphs (Markdown), or plain lines. */ +function MarkedDoc({ segments, markdown }: { segments: Segment[]; markdown: boolean }) { + const lines = segmentLines(segments); + let fenced = false; + return
+ {lines.map((line, i) => { + const plain = line.map(s => s.text).join(''); + const marks = (parts: Segment[]) => parts.map((s, k) => s.changed ? {s.text} : {s.text}); + if (!markdown) return

{plain ? marks(line) :
}

; + if (/^\s*```/.test(plain)) { fenced = !fenced; return

{plain ? marks(line) : null}

; } + if (fenced) return

{plain ? marks(line) :
}

; + const heading = /^(#{1,6})\s+/.exec(plain); + if (heading) return

{marks(stripLead(line, heading[0].length))}

; + const item = /^(\s*)([-*+]|\d+[.)])\s+/.exec(plain); + if (item) return

{marks(stripLead(line, item[0].length))}

; + return

{plain ? marks(line) :
}

; + })} +
; +} + +/** Drop the first `count` characters (the Markdown marker) from the front of a line of segments. */ +function stripLead(line: Segment[], count: number): Segment[] { + const out: Segment[] = []; let left = count; + for (const seg of line) { + if (left >= seg.text.length) { left -= seg.text.length; continue; } + out.push({ text: seg.text.slice(left), changed: seg.changed }); left = 0; + } + return out; +} + +function DiffView({ original, updated }: { original: string; updated: string }) { + const rows = useMemo(() => lineDiff(original, updated), [original, updated]); + const stats = diffStats(rows); + return
+
+{stats.added}−{stats.removed}
+ {rows.map((r, i) => r.t === 'gap' + ?
{tr('{0} unchanged lines', [r.n])}
+ :
{r.text || ' '}
)} +
; +} + +function Picture({ src, label, missing, onOpen }: { src: string; label: string; missing?: string; onOpen: () => void }) { + const [failed, setFailed] = useState(false); + useEffect(() => { setFailed(false); }, [src]); + if (missing || failed) return
{missing ?? tr("This picture could not be loaded.")}
; + return ; +} + +function FileView({ jobId, file }: { jobId: string; file: TimeSkipFile }) { + const kind = fileKind(file.path, file); + const [code, setCode] = useState(false); + const [big, setBig] = useState<'original' | 'updated' | null>(null); + useEffect(() => { setCode(false); setBig(null); }, [file.path]); + const original = file.original ?? '', updated = file.updated ?? ''; + const words = useMemo(() => (kind === 'markdown' || kind === 'text') ? wordDiff(original, updated) : null, [kind, original, updated]); + const heads =
A · {tr("Original")}B · {tr("Updated")}
; + if (kind === 'other') return

{tr("This file is too big, or not text, so it is listed but not shown.")}

; + if (kind === 'image') { + const a = timeSkipImageUrl(jobId, file.path, 'original'), b = timeSkipImageUrl(jobId, file.path, 'updated'); + return <>{heads}
+ setBig('original')}/> + setBig('updated')}/> +
+ setBig(null)} sheet> + {big ? {baseName(file.path)}/ : null} + ; + } + if (kind === 'html') return <> +
setCode(v => !v)}>{tr(code ? 'View preview' : 'View code')}
+ {code ? : <>{heads}
+ {/* No permissions at all: no scripts, no forms, no navigation. The page also carries a policy that blocks every outside request. */} +