diff --git a/src/archive-route.ts b/src/archive-route.ts index 8cfe81ee..a4cd9f8a 100644 --- a/src/archive-route.ts +++ b/src/archive-route.ts @@ -1,50 +1,91 @@ /** - * Helpers for the `/sidebar/archive` route (the file tree's "zip and - * download" action): the download-name sanitizer and the recursive entry - * walk. Kept apart from index.ts so both are directly unit-testable — the - * walk's bounds live inside the collector, and the route module is a - * cordis plugin whose setup needs a whole fake context. + * The `/sidebar/archive` flow: the file tree's "zip and download" action. * - * The walk is the security-relevant half: every row comes from an already - * fenced path (index.ts resolves each selection through - * `ensureWorkspacePath` first), and a symlink is skipped rather than followed, - * so it can neither escape the workspace nor cycle. + * Three steps, unchanged from before: `archive.build` fences every `path` and + * answers with an id immediately; `archive.status` reports + * `building → ready | error`; `GET /sidebar/archive` serves the finished bytes + * once. What changed is what happens in between. + * + * The archive is no longer BUILT BY US. The system's `zip` (or `tar` — see + * archive-tools.ts) writes it, straight into a temp file in the OS temp + * directory, and that file is what gets streamed out. Consequences worth + * stating plainly: + * + * - **No memory ceiling.** The old path concatenated every member into one + * `Buffer`, held it on the task table, and `res.end()`-ed it; a selection + * large enough to matter took the host down. Now only the OS's disk usage + * grows. + * - **No per-entry progress.** The old build reported `done / total` because + * our own writer visited each entry. A child process tells us nothing per + * entry, so the status reports BYTES written so far (the temp file's size) + * and the UI shows a plain "packing" line. Inventing an entry count would + * mean walking the tree a second time just to have a number to display. + * - **Failures still arrive before the download starts.** The tool runs to + * completion in the background; a non-zero exit settles the task as `error` + * with the tool's own stderr, which the client renders. That ordering is the + * whole reason the temp file exists rather than piping the tool directly + * into the response — a mid-stream tool failure would otherwise be a 200 + * response carrying half an archive. + * + * A temp archive is removed on every exit path: a completed download, the TTL + * sweep, and plugin teardown (which also kills a build still running). */ import { randomUUID } from 'node:crypto' -import { lstat, readdir } from 'node:fs/promises' -import { basename, dirname, join } from 'node:path' +import { open, rm, stat } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { SidebarHttpResponse } from './context-types.ts' +import { streamFileToResponse } from './file-stream.ts' +import { + archiveFileName, + archiveTempName, + planArchive, + resolveArchiveTool, + runArchiveTool, + type ArchivePlan, + type ArchiveSpawn, + type ArchiveToolSpec, +} from './archive-tools.ts' import { SidebarError } from './wire.ts' -import { buildZip, ZIP_MAX_ENTRIES, type ZipEntry } from './zip.ts' -/** Maximum archive-name length (keeps the Content-Disposition header sane). */ -export const ARCHIVE_NAME_MAX = 120 +/** How many archives one host may build at the same time. */ +export const ARCHIVE_MAX_BUILDING = 4 +/** How long a finished (or failed) archive stays downloadable. */ +export const ARCHIVE_TTL_MS = 5 * 60 * 1000 -/** - * Sanitize the archive's download name: one flat file name, never a path. - * Separators, control characters, quotes and leading dots are stripped (a - * name cannot look like a traversal or hide as a dotfile); an empty result - * falls back to `archive.zip`, and a `.zip` suffix is applied once. - */ -export function archiveNameOf(raw: string | null): string { - // A bare `.zip` (or nothing at all) is the caller asking for the default: - // check BEFORE the leading-dot strip below, which would turn it into `zip`. - const trimmed = (raw ?? '').trim() - if (trimmed === '' || trimmed === '.zip') return 'archive.zip' - // Character filter (not a character-class regex): separators, quotes and - // C0/DEL control characters cannot survive into the header. - const cleaned = [...trimmed] - .filter((char) => { - const code = char.codePointAt(0)! - return char !== '\\' && char !== '/' && char !== '"' && char !== '\'' && code >= 0x20 && code !== 0x7F - }) - .join('') - .trim() - .replace(/^\.+/, '') - .slice(0, ARCHIVE_NAME_MAX) - if (cleaned === '') return 'archive.zip' - return cleaned.toLowerCase().endsWith('.zip') ? cleaned : `${cleaned}.zip` +/** The finished archive on disk. */ +interface ArchiveFile { + path: string + size: number } +/** One archive build: the state the client polls, plus the finished file. */ +interface ArchiveTask { + id: string + sessionId: string + /** The final download name (the tool's extension already applied). */ + name: string + state: 'building' | 'ready' | 'error' + /** Bytes written so far (the temp file's size while building). */ + bytes: number + error?: string + file?: ArchiveFile + /** When the task stops being downloadable (set when it settles). */ + expiresAt: number +} + +/** The status shape the client reads (never carries the bytes). */ +export interface ArchiveStatus { + state: 'building' | 'ready' | 'error' + bytes: number + error?: string +} + +/** Why a download/status read could not be served. */ +export type ArchiveLookup = + | { ok: true; task: ArchiveTask } + | { ok: false; reason: 'missing' | 'forbidden' | 'building' | 'expired' | 'error'; message: string } + /** * The `content-disposition` value for one archive download. * @@ -74,163 +115,11 @@ function asciiFallbackOf(name: string): string { return code >= 0x20 && code <= 0x7E && char !== '"' && char !== '\\' }) .join('') - const stem = ascii.replace(/\.zip$/i, '') + const stem = ascii.replace(/\.(?:zip|tar\.gz)$/i, '') if (stem === '' || /^\.+$/.test(stem)) return 'download.zip' return ascii } -/** - * The in-archive name of every selection, disambiguated. - * - * The common case keeps the intuition "one selection is named by its own - * basename" — archive `/ws/src` and the entries live under `src/`. Two - * selections that would collide (multi-select `/ws/a/index.ts` and - * `/ws/b/index.ts` both wanting `index.ts`) are extended with parent - * segments until every name is unique, so an extractor cannot silently - * overwrite one member with another. A path that runs out of ancestors - * (selecting the filesystem root, or `/a` twice) falls back to the full - * '/'-joined path, which is unique by construction. - * - * @param selections - absolute (already fenced) paths, in selection order. - * @returns one '/'-separated archive name per selection, same order. - */ -export function disambiguateArchiveNames(selections: readonly string[]): string[] { - const segmentsOf = (absolute: string, depth: number): string => { - const parts: string[] = [] - let current = absolute - for (let level = 0; level < depth; level += 1) { - const part = basename(current) - const parent = dirname(current) - if (part === '' || parent === current) break - parts.unshift(part) - current = parent - } - return parts.join('/') - } - const deepEnough = (absolute: string, name: string): string => { - const full = segmentsOf(absolute, Number.MAX_SAFE_INTEGER) - // Still colliding after every segment is in play (two identical paths, or - // a root-level duplicate): the full path is the best available identity. - return full === name ? absolute.replace(/^\/+/, '') : name - } - const depth = new Map(selections.map(path => [path, 1])) - for (let round = 0; round < 64; round += 1) { - const names = selections.map(path => segmentsOf(path, depth.get(path)!)) - const counts = new Map() - for (const name of names) counts.set(name, (counts.get(name) ?? 0) + 1) - if ([...counts.values()].every(count => count === 1)) return names - const grown = new Set() - for (const [index, path] of selections.entries()) { - if ((counts.get(names[index]!) ?? 0) <= 1) continue - depth.set(path, depth.get(path)! + 1) - grown.add(path) - } - if (grown.size === 0) break - } - return selections.map(path => deepEnough(path, segmentsOf(path, depth.get(path)!))) -} - -/** - * Collect one selected path into the archive: a file becomes one entry, a - * directory is walked depth-first and each level contributes its own entry - * (a trailing '/' name), files keep their layout under the directory's own - * name. Symlinks are skipped, never followed. Iterative (an explicit stack) - * because a deep tree must not blow the JS stack, and the count bound is - * enforced HERE so a runaway directory fails before its rows pile up. - * - * @param absolute - the (already fenced) absolute path of the selection. - * @param name - the in-archive name of that selection (its basename). - * @param out - the entry list appended to, in archive order. - * @param maxEntries - entry-count bound. - * @throws {SidebarError} fs-error when a row cannot be read or the bound is hit. - */ -export async function collectZipEntries( - absolute: string, - name: string, - out: ZipEntry[], - maxEntries = ZIP_MAX_ENTRIES, -): Promise { - const stack: Array<{ path: string; name: string }> = [{ path: absolute, name }] - while (stack.length > 0) { - const item = stack.pop()! - if (out.length >= maxEntries) { - throw new SidebarError('fs-error', `too many entries for one archive (> ${maxEntries})`, 400) - } - const info = await lstat(item.path).catch((error: unknown) => { - throw new SidebarError('fs-error', `cannot read "${item.path}": ${error instanceof Error ? error.message : String(error)}`, 400) - }) - if (info.isSymbolicLink()) { - // A link row is not a file to read and not a directory to walk: it is - // skipped (an archive of a dangling link has nothing to store). Never - // followed — no escape and no cycle. - continue - } - if (!info.isDirectory()) { - out.push({ path: item.path, name: item.name }) - continue - } - out.push({ path: item.path, name: item.name, isDir: true }) - let level - try { - level = await readdir(item.path, { withFileTypes: true }) - } catch (error) { - throw new SidebarError('fs-error', `cannot list "${item.path}": ${error instanceof Error ? error.message : String(error)}`, 400) - } - // Reverse order: the stack pops the first child next, so the archive reads - // top-down in directory order. - for (let index = level.length - 1; index >= 0; index -= 1) { - const child = level[index]! - stack.push({ path: join(item.path, child.name), name: `${item.name}/${child.name}` }) - } - } -} - -/** How many archives one host may build at the same time. */ -export const ARCHIVE_MAX_BUILDING = 4 -/** How long a finished (or failed) archive stays downloadable. */ -export const ARCHIVE_TTL_MS = 5 * 60 * 1000 - -/** One archive build: the state the client polls, plus the finished bytes. */ -interface ArchiveTask { - id: string - sessionId: string - name: string - state: 'building' | 'ready' | 'error' - done: number - total: number - bytes: number - error?: string - zip?: Buffer - /** When the task stops being downloadable (set when it settles). */ - expiresAt: number -} - -/** The status shape the client reads (never carries the bytes). */ -export interface ArchiveStatus { - state: 'building' | 'ready' | 'error' - done: number - total: number - bytes: number - error?: string -} - -/** Why a download/status read could not be served. */ -export type ArchiveLookup = - | { ok: true; task: ArchiveTask } - | { ok: false; reason: 'missing' | 'forbidden' | 'building' | 'expired' | 'error'; message: string } - -/** A resolved download: the bytes plus the sanitized name they were built for. */ -export interface ArchiveDownload { - name: string - zip: Buffer -} - -/** The response face {@link respondArchiveDownload} writes through. */ -export interface ArchiveDownloadResponse { - writeHead(status: number, headers?: Record): void - end(chunk?: Buffer | string): void -} - /** * Answer one `GET /sidebar/archive?id=&sessionId=` from the task table. * @@ -239,75 +128,104 @@ export interface ArchiveDownloadResponse { * for a failed build, 404 for unknown/expired/already-downloaded, 200 with the * RFC 5987 disposition otherwise. Kept here so all six branches are testable * without a live cordis mount. + * + * The bytes are STREAMED from the temp file and the task is released only once + * the stream settles: releasing first (as the buffered version could) would + * unlink the file the response is still reading from. + * * @param tasks - the plugin's task table. * @param query - the request's `sessionId` / `id` values (null = absent). - * @param res - a minimal response face. + * @param res - the response face. * @throws {SidebarError} for every non-200 branch (callers turn it into the - * JSON error envelope they already use). + * JSON error envelope they already use). Thrown BEFORE any header commits, so + * the envelope is still deliverable. */ -export function respondArchiveDownload( +export async function respondArchiveDownload( tasks: ArchiveTasks, query: { sessionId: string | null; id: string | null }, - res: ArchiveDownloadResponse, -): void { + res: SidebarHttpResponse, +): Promise { if (query.sessionId === null || query.id === null || query.id === '') { throw new SidebarError('bad-request', 'sessionId and id are required') } const found = tasks.lookup(query.id, query.sessionId) - if (!found.ok || found.task.state !== 'ready' || found.task.zip === undefined) { + if (!found.ok || found.task.state !== 'ready' || found.task.file === undefined) { if (found.ok) throw new SidebarError('not-found', 'archive is gone', 404) if (found.reason === 'building') throw new SidebarError('bad-request', found.message, 409) if (found.reason === 'forbidden') throw new SidebarError('forbidden', found.message, 403) if (found.reason === 'error') throw new SidebarError('fs-error', found.message, 410) throw new SidebarError('not-found', found.message, 404) } - const { name, zip } = found.task - // A download consumes the task: the bytes are not kept for a second fetch - // (the task table is a queue, not a store). - tasks.release(found.task.id) - res.writeHead(200, { - 'content-type': 'application/zip', - // Never the raw name: a non-latin1 value (中文目录 → 报告.zip) makes Node's - // writeHead throw and turns the download into a 500. - 'content-disposition': contentDispositionOf(name), - 'content-length': String(zip.byteLength), - 'cache-control': 'no-cache', - }) - res.end(zip) + const { name, file } = found.task + const id = found.task.id + try { + await streamFileToResponse(file.path, file.size, res, { + // The extension follows the TOOL, not the client's guess: a host with + // only `tar` sends a real .tar.gz rather than a mislabelled .zip. + 'content-type': name.endsWith('.tar.gz') ? 'application/gzip' : 'application/zip', + // Never the raw name: a non-latin1 value (中文目录 → 报告.zip) makes Node's + // writeHead throw and turns the download into a 500. + 'content-disposition': contentDispositionOf(name), + 'cache-control': 'no-cache', + }) + } finally { + // A download consumes the task: the bytes are not kept for a second fetch + // (the task table is a queue, not a store). + tasks.release(id) + } } /** * The host-side archive task table. * - * A selection is collected up front (cheap: names + sizes) and then zipped in - * the BACKGROUND, so the client can show progress instead of staring at a - * spinner: `start` returns an id immediately, `status` reports - * `building → ready | error`, and `download` hands over the bytes exactly once. - * The table is bounded twice — {@link ARCHIVE_MAX_BUILDING} concurrent builds - * and {@link ARCHIVE_TTL_MS} since a finished one — and every read is + * A selection is planned up front (cheap: one probe + a couple of path joins) + * and then packed in the BACKGROUND, so the client gets an id immediately and + * the download only starts once the bytes actually exist. The table is bounded + * twice — {@link ARCHIVE_MAX_BUILDING} concurrent builds and + * {@link ARCHIVE_TTL_MS} since a finished one — and every read is * session-scoped, so one session can never fetch another's archive. */ export interface ArchiveTasks { - /** Start a build; rejects with bad-request when the concurrency cap is hit. */ - start(input: { sessionId: string; name: string; entries: readonly ZipEntry[] }): { id: string; entries: number } + /** Start a build; rejects when the tool is missing or the cap is hit. */ + start(input: { sessionId: string; name: string; paths: readonly string[] }): Promise<{ id: string; name: string; entries: number }> /** Poll one task (a settled task past its TTL reads as missing). */ status(id: string, sessionId: string): ArchiveStatus /** Look one task up for a download; `sessionId` must match the builder's. */ lookup(id: string, sessionId: string): ArchiveLookup - /** Release a task (called after its bytes were served). */ + /** Release a task (called after its bytes were served): deletes the temp file. */ release(id: string): void /** Number of live tasks (tests / diagnostics). */ size(): number + /** Kill every running build and delete every temp file (plugin teardown). */ + dispose(): void +} + +/** Options of {@link createArchiveTasks} (tests inject the spawn + temp dir). */ +export interface ArchiveTaskOptions { + spawn?: ArchiveSpawn + /** Directory the temp archives live in (defaults to the OS temp directory). */ + tempDir?: string + /** Resolve the archive tool (defaults to the real probe). `spawner` is + * undefined when the table was built without an injected spawn. */ + resolveTool?: (spawner: ArchiveSpawn | undefined) => Promise } /** Create one archive task table (one per plugin mount). */ -export function createArchiveTasks(): ArchiveTasks { +export function createArchiveTasks(options: ArchiveTaskOptions = {}): ArchiveTasks { const tasks = new Map() + /** Running children, by task id (teardown kills them). */ + const children = new Map() + const spawner = options.spawn ?? undefined - /** Drop settled tasks past their TTL (called on every access). */ + const tempPathOf = (id: string, ext: string): string => + join(options.tempDir ?? tmpdir(), archiveTempName(id, ext)) + + /** Drop settled tasks past their TTL, deleting the temp files they held. */ const sweep = (now: number): void => { for (const [id, task] of tasks) { - if (task.state !== 'building' && task.expiresAt <= now) tasks.delete(id) + if (task.state === 'building' || task.expiresAt > now) continue + tasks.delete(id) + if (task.file !== undefined) void rm(task.file.path, { force: true }).catch(() => {}) } } @@ -323,42 +241,44 @@ export function createArchiveTasks(): ArchiveTasks { } return { - start({ sessionId, name, entries }) { + async start({ sessionId, name, paths }) { sweep(Date.now()) let building = 0 for (const task of tasks.values()) if (task.state === 'building') building += 1 if (building >= ARCHIVE_MAX_BUILDING) { throw new SidebarError('bad-request', `too many archives are being built (max ${ARCHIVE_MAX_BUILDING})`, 409) } + const resolve = options.resolveTool ?? resolveArchiveTool + // One call either way: `spawn` has a default, so passing `undefined` + // selects the real implementation without a second code path. + const spec = await resolve(spawner) + if (spec === undefined) { + // A NEW wire code, and deliberately its own: "this machine has no zip + // and no tar" is not a failure of the selection, and the client shows + // it as an actionable sentence rather than a raw English message. + throw new SidebarError( + 'unavailable', + 'no archive tool is available: neither zip nor tar could be run', + 501, + ) + } + const plan = planArchive(paths, spec) + const id = `ar-${randomUUID()}` + const finalName = archiveFileName(name, spec.ext) + const tempPath = tempPathOf(id, spec.ext) const task: ArchiveTask = { - id: `ar-${randomUUID()}`, + id, sessionId, - name, + name: finalName, state: 'building', - done: 0, - total: entries.length, bytes: 0, expiresAt: Number.POSITIVE_INFINITY, } - tasks.set(task.id, task) + tasks.set(id, task) // Detached on purpose: the POST answers as soon as the id exists, and the // task table (not the request) owns the error from here on. - void buildZip([...entries], { - onProgress: (progress) => { - task.done = progress.done - task.bytes = progress.bytes - }, - }).then((zip) => { - task.zip = zip - task.state = 'ready' - task.done = task.total - task.expiresAt = Date.now() + ARCHIVE_TTL_MS - }, (error: unknown) => { - task.state = 'error' - task.error = error instanceof Error ? error.message : String(error) - task.expiresAt = Date.now() + ARCHIVE_TTL_MS - }) - return { id: task.id, entries: entries.length } + void pack(id, task, plan, tempPath, spawner) + return { id, name: finalName, entries: paths.length } }, status(id, sessionId) { sweep(Date.now()) @@ -367,19 +287,82 @@ export function createArchiveTasks(): ArchiveTasks { if (task.sessionId !== sessionId) throw new SidebarError('forbidden', 'archive belongs to another session', 403) return { state: task.state, - done: task.done, - total: task.total, bytes: task.bytes, ...(task.error === undefined ? {} : { error: task.error }), } }, lookup, release(id) { + const task = tasks.get(id) tasks.delete(id) + if (task?.file !== undefined) void rm(task.file.path, { force: true }).catch(() => {}) }, size() { sweep(Date.now()) return tasks.size }, + dispose() { + for (const child of children.values()) { + try { + child.kill() + } catch { + // A child that already exited cannot be killed; nothing to do. + } + } + children.clear() + for (const task of tasks.values()) { + if (task.file !== undefined) void rm(task.file.path, { force: true }).catch(() => {}) + } + tasks.clear() + }, + } + + /** + * Pack one task: open the temp file, hand its descriptor to the tool, and + * settle the task from the exit code. + * + * The descriptor stays open across the spawn and is closed only after the + * child exits — closing it earlier would truncate output still being written. + */ + async function pack( + id: string, + task: ArchiveTask, + plan: ArchivePlan, + tempPath: string, + spawner: ArchiveSpawn | undefined, + ): Promise { + const settle = (error: string | undefined): void => { + task.state = error === undefined ? 'ready' : 'error' + if (error !== undefined) task.error = error + task.expiresAt = Date.now() + ARCHIVE_TTL_MS + children.delete(id) + } + let handle: Awaited> | undefined + try { + handle = await open(tempPath, 'w') + const result = await runArchiveTool(plan, handle.fd, spawner, child => { children.set(id, child) }) + await handle.close() + handle = undefined + if (result.code !== 0) { + settle(result.stderr === '' ? `${plan.spec.bin} exited with code ${result.code}` : result.stderr) + await rm(tempPath, { force: true }).catch(() => {}) + return + } + const info = await stat(tempPath).catch(() => undefined) + if (info === undefined) { + settle(`${plan.spec.bin} produced no archive`) + return + } + task.bytes = info.size + task.file = { path: tempPath, size: info.size } + settle(undefined) + } catch (error: unknown) { + // A tool that cannot be started at all, or a disk that refuses the temp + // file. Either way the task must not stay `building` forever. + await handle?.close().catch(() => {}) + task.bytes = await stat(tempPath).then(info => info.size).catch(() => 0) + settle(error instanceof Error ? error.message : String(error)) + await rm(tempPath, { force: true }).catch(() => {}) + } } } diff --git a/src/archive-tools.ts b/src/archive-tools.ts new file mode 100644 index 00000000..915a36fb --- /dev/null +++ b/src/archive-tools.ts @@ -0,0 +1,329 @@ +/** + * Archive packing by the system's own tool, not by a writer of ours. + * + * This module replaces a hand-written ZIP encoder (~300 lines of local file + * headers, central directory, CRC-32 and raw DEFLATE) plus a recursive walk. + * Everything it did, `zip -r` does better: real DEFLATE, the platform's own + * path handling, and streaming output that grows with the data instead of a + * `Buffer.concat` of the whole archive. + * + * Two tools, tried in order, because neither is universal: + * + * - `zip` — what the file tree asks for, present on macOS and most Linux + * distributions. Always passed `-y`: without it Info-ZIP FOLLOWS symlinks, + * and a symlink loop (`a -> .`) then recurses until it is killed. `-y` + * stores the link itself, which is both loop-proof and a truer archive. + * (Verified against a real loop before this was written.) + * - `tar` — present everywhere the plugin realistically runs, including + * Windows 10 1803+, where it is a built-in `bsdtar` and there is no `zip` at + * all. GNU tar and bsdtar both take the same `-czf -` invocation. + * + * Output always goes to stdout (`-` as the archive name) so the caller decides + * where the bytes land; the route redirects them into a temp file, which is + * what keeps the download streamable without holding the archive in memory. + * + * Nothing in this module runs a shell: `spawn` takes an argv array, and every + * path is data. A path is never interpolated into a command string, so a + * filename with `;` or `$(...)` in it is a filename. + * + * The spawn/probe functions are injectable so the test suite never depends on + * a real `zip` being installed (AGENTS §6) — the same pattern `open-external` + * and `search-engines` use. + */ +import { spawn } from 'node:child_process' +import { dirname, relative, sep } from 'node:path' +import { SidebarError } from './wire.ts' + +/** The archive tool actually in use. */ +export type ArchiveTool = 'zip' | 'tar' + +/** One available tool: its binary name, the invocation flags, and its suffix. */ +export interface ArchiveToolSpec { + tool: ArchiveTool + bin: string + /** `-czf -` / `-r -q -X -y -`: everything before the entry names. */ + flags: readonly string[] + /** The download-name extension this tool produces. */ + ext: string +} + +/** + * The invocation of one tool. + * + * `zip`'s `-` as the archive name means stdout, and the leading `-` in the + * argv is understood as that operand rather than as an option because it + * follows other flags. + */ +const TOOL_SPECS: Readonly> = { + zip: { tool: 'zip', bin: 'zip', flags: ['-r', '-q', '-X', '-y', '-'], ext: '.zip' }, + tar: { tool: 'tar', bin: 'tar', flags: ['-czf', '-'], ext: '.tar.gz' }, +} + +/** Order the tools are tried in (the `.zip` output is the better default). */ +const TOOL_ORDER: readonly ArchiveTool[] = ['zip', 'tar'] + +/** How long one availability probe may take before the tool counts as absent. */ +const PROBE_TIMEOUT_MS = 3000 + +/** How much stderr is kept for the failure message (tail, not head). */ +export const ARCHIVE_STDERR_LIMIT = 4096 + +/** The spawn face this module needs (injectable for tests). */ +export type ArchiveSpawn = typeof spawn + +/** A resolved plan: where to run, what to run, and what to name the result. */ +export interface ArchivePlan { + spec: ArchiveToolSpec + /** Working directory the tool runs in (the selections' common ancestor). */ + cwd: string + /** Relative entry names, '/'-separated. */ + args: string[] +} + +/** + * Whether one candidate binary actually runs. + * + * `--version` rather than `--help`: Info-ZIP's `zip -h` is fine but bsdtar's + * help exits non-zero on some builds, and a tool that cannot answer + * `--version` is not one worth handing a user's directory to. + */ +function probeTool(bin: string, spawner: ArchiveSpawn): Promise { + return new Promise((resolve) => { + let settled = false + const finish = (ok: boolean): void => { + if (settled) return + settled = true + clearTimeout(timer) + resolve(ok) + } + let child: ReturnType + try { + child = spawner(bin, ['--version'], { stdio: 'ignore', windowsHide: true }) + } catch { + finish(false) + return + } + const timer = setTimeout(() => { + child.kill() + finish(false) + }, PROBE_TIMEOUT_MS) + child.once('error', () => { finish(false) }) + child.once('exit', (code) => { finish(code === 0) }) + }) +} + +/** Probe result cache: one process-wide answer per tool. */ +const availability = new Map>() + +/** + * The archive tool this host will use, or undefined when it has neither. + * + * The answer is cached for the process: `zip` does not appear or disappear + * between two file-tree clicks, and a probe costs a process spawn. + * + * @param spawner - the spawn implementation (tests inject a fake). + * @returns the tool spec, or undefined when no tool is available. + */ +export function resolveArchiveTool(spawner: ArchiveSpawn = spawn): Promise { + return tryTools(TOOL_ORDER, spawner) +} + +/** + * Resolve the first available tool from an ordered list. + * + * @param order - tool names to try, in order. + * @param spawner - the spawn implementation. + * @returns the first tool that answers, or undefined. + */ +export async function tryTools( + order: readonly ArchiveTool[], + spawner: ArchiveSpawn = spawn, +): Promise { + for (const tool of order) { + const spec = TOOL_SPECS[tool] + let pending = availability.get(tool) + if (pending === undefined) { + pending = probeTool(spec.bin, spawner).then(ok => (ok ? spec : undefined)) + availability.set(tool, pending) + } + // Sequential on purpose: the tools are tried in preference order, and a + // parallel probe would spawn a binary we may never use. + const found = await pending + if (found !== undefined) return found + } + return undefined +} + +/** Drop the cached probe results (tests, and a profile change in dev). */ +export function resetArchiveToolCache(): void { + availability.clear() +} + +/** `/`-joined path segments, whatever separator the platform produced. */ +function toArchiveName(path: string): string { + return sep === '/' ? path : path.split(sep).join('/') +} + +/** + * Build the argv/cwd plan for one selection. + * + * The tool's working directory is the selections' deepest COMMON ancestor, and + * every selection is passed as its path relative to that directory — so the + * archive names reproduce the tree the user sees: one selection is named by + * its own basename (`src/`), two same-named files from different folders land + * under different parents, and a selection that IS the common ancestor pushes + * the base one level up so its name keeps a component. + * + * This replaces the old per-path "grow parent segments until unique" logic. + * A path relative to a common ancestor is unique by construction, so the + * disambiguation it performed is now a property of the layout instead of an + * algorithm. + * + * @param selections - absolute paths, already fenced by the caller. + * @param spec - the resolved tool. + * @returns the plan to spawn. + * @throws {SidebarError} bad-request when a selection has no usable name. + */ +export function planArchive(selections: readonly string[], spec: ArchiveToolSpec): ArchivePlan { + if (selections.length === 0) { + throw new SidebarError('bad-request', 'no paths to archive') + } + let base = commonAncestor(selections) + // A selection that IS the base would produce an empty argument. Step the + // base up so every argument keeps at least one component — which is also + // what gives the archive a sensible top-level entry. + if (selections.some(selection => relative(base, selection) === '')) { + const parent = dirname(base) + if (parent === base) { + throw new SidebarError('bad-request', 'cannot archive the filesystem root') + } + base = parent + } + const args = selections.map(selection => toArchiveName(relative(base, selection))) + if (args.some(name => name === '' || name === '..' || name.startsWith('../'))) { + throw new SidebarError('bad-request', 'selection is not below the archive root') + } + return { spec, cwd: base, args: [...spec.flags, ...args] } +} + +/** + * The deepest directory containing every selection. + * + * Walked segment by segment rather than by `dirname` until the paths agree, so + * a single selection resolves to its OWN directory (the case the archive needs: + * `zip -r archive.zip src` from the parent, not `zip -r archive.zip .` from + * inside `src`). + */ +function commonAncestor(selections: readonly string[]): string { + const [first, ...rest] = selections + if (first === undefined) throw new SidebarError('bad-request', 'no paths to archive') + if (rest.length === 0) return dirname(first) + let base = first + for (const selection of rest) { + while (!isWithin(base, selection)) { + const parent = dirname(base) + if (parent === base) return parent + base = parent + } + } + return base +} + +/** Whether `target` is `base` itself or lives below it (lexically). */ +function isWithin(base: string, target: string): boolean { + if (base === target) return true + const rel = relative(base, target) + return rel !== '' && !rel.startsWith('..') && !rel.startsWith(`..${sep}`) +} + +/** The outcome of one tool run. */ +export interface ArchiveRunResult { + /** The tool's exit code (0 = success). */ + code: number + /** The tail of stderr, for the failure message. */ + stderr: string +} + +/** + * Run one planned tool, writing the archive to an already-open file handle. + * + * The caller owns the file descriptor: it stays open across the spawn so the + * tool writes straight into the temp file, and the caller closes it once this + * promise settles (closing it earlier would truncate a running child's output). + * + * @param plan - the plan from {@link planArchive}. + * @param outputFd - writable file descriptor for the archive bytes. + * @param spawner - the spawn implementation. + * @param onSpawn - receives the child as soon as it exists, so the caller can + * hold on to it (plug-in teardown kills the builds it started). + * @returns the exit code and the stderr tail; never rejects for a tool that + * ran and failed (a non-zero code is a result, not an exception). + * @throws {SidebarError} fs-error when the tool cannot be started at all. + */ +export function runArchiveTool( + plan: ArchivePlan, + outputFd: number, + spawner: ArchiveSpawn = spawn, + onSpawn?: (child: ReturnType) => void, +): Promise { + return new Promise((resolve, reject) => { + const child = spawner(plan.spec.bin, plan.args, { + cwd: plan.cwd, + stdio: ['ignore', outputFd, 'pipe'], + windowsHide: true, + }) + onSpawn?.(child) + let stderr = '' + child.stderr?.on('data', (chunk: Buffer | string) => { + stderr += typeof chunk === 'string' ? chunk : chunk.toString('utf8') + // Keep only the tail: the last lines are the ones that name the actual + // problem, and an unbounded log from a failed walk is not worth holding. + if (stderr.length > ARCHIVE_STDERR_LIMIT * 2) { + stderr = stderr.slice(-ARCHIVE_STDERR_LIMIT) + } + }) + child.once('error', (error: Error) => { + reject(new SidebarError('fs-error', `cannot run ${plan.spec.bin}: ${error.message}`)) + }) + child.once('close', (code: number | null) => { + resolve({ code: code ?? 1, stderr: stderr.slice(-ARCHIVE_STDERR_LIMIT).trim() }) + }) + }) +} + +/** The default in-archive stem when the caller named nothing usable. */ +const DEFAULT_STEM = 'archive' + +/** Maximum stem length, so the Content-Disposition header stays sane. */ +export const ARCHIVE_STEM_MAX = 100 + +/** + * Sanitize a caller-supplied archive NAME into a stem, then apply the tool's + * extension. Separators, control characters and quotes are stripped (a name + * must never look like a path), and any archive suffix the caller guessed is + * removed — the tool decides the real extension, not the client. + * + * @param raw - the requested name ('' or a bare suffix yields the default). + * @param ext - the extension the resolved tool produces ('.zip' / '.tar.gz'). + * @returns a flat file name with that extension. + */ +export function archiveFileName(raw: string, ext: string): string { + const stripped = raw.trim() + .replace(/\.(?:zip|tar(?:\.gz)?|tgz)$/i, '') + .trim() + const cleaned = [...stripped] + .filter((char) => { + const code = char.codePointAt(0)! + return char !== '/' && char !== '\\' && char !== '"' && char !== '\'' && code >= 0x20 && code !== 0x7F + }) + .join('') + .trim() + .replace(/^\.+/, '') + .slice(0, ARCHIVE_STEM_MAX) + return `${cleaned === '' ? DEFAULT_STEM : cleaned}${ext}` +} + +/** The temporary archive file's name in the OS temp directory. */ +export function archiveTempName(id: string, ext: string): string { + return `dsh-better-sidebar-${id}${ext}` +} \ No newline at end of file diff --git a/src/client/EditorHost.tsx b/src/client/EditorHost.tsx index c787f27b..aa99da34 100644 --- a/src/client/EditorHost.tsx +++ b/src/client/EditorHost.tsx @@ -50,7 +50,7 @@ import css from './sidebar.module.css' type EditorLoad = | { status: 'loading' } | { status: 'error'; message: string } - | { status: 'ready'; viewer: FileViewerDescriptor; content?: string; truncated?: boolean; mtimeMs?: number; mediaUrl?: string; customData?: unknown } + | { status: 'ready'; viewer: FileViewerDescriptor; content?: string; size?: number; largeFile?: { size: number }; mtimeMs?: number; mediaUrl?: string; customData?: unknown } | { status: 'binary' } /** The docked tree panel's width bounds (drag-resize clamps into them). */ @@ -398,7 +398,8 @@ export function EditorHost(props: { status: 'ready', viewer: action.viewer, content: action.content, - truncated: action.truncated, + size: action.size, + largeFile: action.largeFile, mediaUrl: action.mediaUrl, customData: action.customData, }) @@ -415,13 +416,9 @@ export function EditorHost(props: { case 'fetchFsRead': api.fsRead(scope, path).then((result) => { if (cancelled) return - // Binary reads carry the head bytes for the detect re-match. - const outcome = planFsReadOutcome(action.viewer, { - binary: result.kind === 'binary', - content: result.kind === 'text' ? result.content : '', - truncated: result.truncated, - head: result.kind === 'binary' ? result.head : undefined, - }, (head) => ctx.get('betterSidebar')?.matchFileViewer(path, head), mediaUrlOf) + // The host answers one of three shapes; binary and too-large both + // carry the head bytes for the detect re-match (see editor-load.ts). + const outcome = planFsReadOutcome(action.viewer, result, (head) => ctx.get('betterSidebar')?.matchFileViewer(path, head), mediaUrlOf) // Carry the read's mtime into the rendered viewer: the text // editor uses it as the save baseline (fs-conflict on drift). if (outcome.kind === 'render') setLoad({ ...outcome, status: 'ready', mtimeMs: result.mtimeMs }) @@ -568,7 +565,7 @@ export function EditorHost(props: { )} {toolbar?.dirty === true && } - {toolbar?.editable === true && toolbar?.truncated !== true && ( + {toolbar?.editable === true && toolbar?.largeFile !== true && ( + + {records + ? t('jsonlRecordRange', { from: pager.firstLine, to: numberAt(Math.max(0, rows.length - 1)) }) + : t('pagedLineRange', { from: pager.firstLine, to: numberAt(Math.max(0, rows.length - 1)) })} + {' · '} + {pager.atEnd ? t('pagedPageOfTotal', { page: pager.page, total: pager.page }) : t('pagedPage', { page: pager.page })} + + + + + + ) +} + +/** One JSONL record row: a summary line, expanding into the host's JSON tree. */ +function RecordRow(props: { + number: number + /** The raw line, shown verbatim when the record does not parse. */ + line: string + record: ReturnType + expanded: boolean + labels: JsonTreeLabels + onToggle: () => void +}): ReactNode { + const { number, line, record, expanded, labels, onToggle } = props + if (!record.ok) { + // A blank line is not a broken record — JSONL files normally end with one, + // and the host's pages are line-aligned, so it lands as its own row. + if (record.error === '') return null + return ( +
  • + +
    +
    {t('jsonlInvalidRecord')}
    +
    {line}
    +
    +
  • + ) + } + const value = record.value + const tree = isTreeRecord(value) + return ( +
  • + +
    + + {tree && expanded && ( +
    + +
    + )} +
    +
  • + ) +} diff --git a/src/client/TextEditor.tsx b/src/client/TextEditor.tsx index d7f6ecf9..9476f246 100644 --- a/src/client/TextEditor.tsx +++ b/src/client/TextEditor.tsx @@ -43,6 +43,7 @@ import { useSelectionPopup } from './selection-popup.ts' import { buildSelectionInsert, linesOfSelection } from './selection-payload.ts' import { analyzeMarkdownHtml } from './markdown-html.ts' import { LazyMermaidMarkdown, MarkdownDocument, type MarkdownHtmlMedia } from './MarkdownHtml.tsx' +import { LargeFileView } from './LargeFileView.tsx' import { useMarkdownSurface } from './use-markdown-surface.ts' import { MdToc } from './md-toc.tsx' import { splitMermaidBlocks } from './mermaid-blocks.ts' @@ -72,7 +73,7 @@ function sameDocument(a: string, b: string): boolean { } export function TextEditor(props: FileViewerProps) { - const { ctx, scope, path, viewerId, content, truncated, line } = props + const { ctx, scope, path, viewerId, content, size, largeFile, line } = props const [mode, setMode] = useState('preview') /** The editor's current text (null while clean); preview renders this. */ const [draft, setDraft] = useState(null) @@ -123,6 +124,12 @@ export function TextEditor(props: FileViewerProps) { }, [markdownSurfaceRef]) const markdown = viewerId === 'markdown' const html = viewerId === 'html' + /** Newline-delimited JSON: it has its own preview (one card per record) on + * top of the shared editable CodeMirror surface. */ + const jsonl = viewerId === 'jsonl' + /** The file is above the editable threshold: the viewer renders the + * read-only paged preview and no editor at all. */ + const readOnly = largeFile !== undefined /** The uncommitted-change gutter (issue #212): the `code` viewer only, * gated by ONE boolean setting (on by default). Nothing else — no * end-of-line author widget, no badges, no animation. Read reactively @@ -136,7 +143,7 @@ export function TextEditor(props: FileViewerProps) { // client-side), so the store answers on both sides alike. useCallback(() => props.store.getSnapshot().prefs.editorGitGutter !== false, [props.store]), ) - const gitGutterEnabled = viewerId === 'code' && gitGutterPref + const gitGutterEnabled = (viewerId === 'code' || viewerId === 'jsonl') && gitGutterPref /** Bumped by every save: the uncommitted diff moved while the file's git * status entry (which only tracks its XY code) did not. */ const [gitRevision, setGitRevision] = useState(0) @@ -262,11 +269,6 @@ export function TextEditor(props: FileViewerProps) { // is open, and the save key stays in the editor keymap unchanged. ...cmSearchExtensions(), searchPhrases.of(), - // A truncated read only carries the first readLimit bytes; edits made - // on partial content must never be saved over the full file (issue - // #732), so the document is rendered read-only until a full read - // replaces it. - ...(truncated === true ? [EditorState.readOnly.of(true)] : []), ...(language !== null ? [language] : []), CodeMirrorView.updateListener.of((update) => { if (update.docChanged) { @@ -286,7 +288,7 @@ export function TextEditor(props: FileViewerProps) { // selection anchors the floating "add to conversation" button above // its head. Scrolling (geometry/viewport change) or losing focus // hides it; typing collapses the selection and hides it too. - ...(viewerId === 'code' || viewerId === 'markdown' ? [ + ...(viewerId === 'code' || viewerId === 'markdown' || viewerId === 'jsonl' ? [ CodeMirrorView.updateListener.of((update) => { if (update.geometryChanged || update.viewportChanged) { selectionPopup.hide() @@ -340,7 +342,7 @@ export function TextEditor(props: FileViewerProps) { // tab's lifetime, and the dark flip is handled by the reconfigure // effect below (recreating the view here would drop the draft). // eslint-disable-next-line react-hooks/exhaustive-deps - }, [content, path, truncated]) + }, [content, path]) // Native sidebar tabs stay mounted while another tab is active. If a file // is opened while that host is hidden, CodeMirror can measure its viewport at @@ -408,10 +410,10 @@ export function TextEditor(props: FileViewerProps) { if (view === null) return const key = `${path}#${line}` if (landedAtRef.current === key) return - // A markdown/html file opens in preview, which has no source lines to put - // a cursor on. The reference asked for source, so land in the editor; the - // key is NOT recorded yet, so the re-run after the flip does the jump. - if ((markdown || html) && mode === 'preview') { + // A markdown/html/jsonl file opens in a preview, which has no source lines + // to put a cursor on. The reference asked for source, so land in the + // editor; the key is NOT recorded yet, so the re-run after the flip jumps. + if ((markdown || html || jsonl) && mode === 'preview') { setMode('edit') return } @@ -474,14 +476,14 @@ export function TextEditor(props: FileViewerProps) { view.dispatch({ effects: gitComp.reconfigure(gitGutterEnabled ? gitHost : null) }) }, [gitGutterEnabled, gitHost]) - // Push the line map into the live view. `content` / `truncated` re-run this - // after the view was rebuilt for a new file, and `gitGutterEnabled` after a - // re-install (a reconfigured state field starts empty). + // Push the line map into the live view. `content` re-runs this after the + // view was rebuilt for a new file, and `gitGutterEnabled` after a re-install + // (a reconfigured state field starts empty). useEffect(() => { const view = viewRef.current if (view === null) return applyGitLineKinds(view, gitKinds) - }, [gitKinds, gitGutterEnabled, content, path, truncated]) + }, [gitKinds, gitGutterEnabled, content, path]) // The editor may have been display:none while previewing; re-measure when // it becomes visible again (CodeMirror sizes itself on reveal). A mode @@ -558,11 +560,6 @@ export function TextEditor(props: FileViewerProps) { const save = (): void => { const view = viewRef.current if (view === null || savingRef.current) return - // Defense in depth for issue #732: a truncated read only holds the first - // readLimit bytes, and fs.write replaces the whole file — saving partial - // content would destroy the tail. The readOnly extension already blocks - // edits; this guards the keymap path against future trigger points. - if (truncated === true) return savingRef.current = true setSaveState('saving') // Optimistic concurrency: the draft was based on the bytes read at @@ -701,6 +698,16 @@ export function TextEditor(props: FileViewerProps) { ) } const editable = content !== undefined + /** + * Whether the preview/edit toggle applies. It needs BOTH surfaces to exist: + * a read-only paged preview has no editor to switch to, and the `code` + * catch-all has no preview to switch to. + */ + const toggleable = !readOnly && (markdown || html || jsonl) + /** A non-CodeMirror surface currently owns the pane (markdown/html render, or + * the JSONL record list): the CodeMirror host stays mounted but hidden, so + * unsaved edits survive the round trip. */ + const showingPreview = !readOnly && mode === 'preview' && (markdown || html || jsonl) const saveLabel = saveState === 'saving' ? t('loading') : saveState === 'saved' ? t('saved') : saveState === 'failed' ? t('saveFailed') : '' // Per-feature sandbox escape hatch: the global side card setting (warned) // plus a per-surface temporary unlock. The unlock state starts at the @@ -719,7 +726,7 @@ export function TextEditor(props: FileViewerProps) { const lastToolbarRef = useRef('') useEffect(() => { if (!hostToolbar) return - const state: EditorToolbarState = { modes: markdown || html, mode, dirty, editable, truncated: truncated === true, saveState } + const state: EditorToolbarState = { modes: toggleable, mode, dirty, editable, ...(readOnly ? { largeFile: true } : {}), saveState } const key = JSON.stringify(state) if (lastToolbarRef.current === key) return lastToolbarRef.current = key @@ -734,11 +741,27 @@ export function TextEditor(props: FileViewerProps) { // eslint-disable-next-line react-hooks/exhaustive-deps }, [hostToolbar]) + // Above the editable threshold there is no document to edit: the viewer is + // the read-only paged preview and nothing else. Returning before the editor + // subtree exists is deliberate — it is what guarantees no CodeMirror state + // can be built for a file we never loaded. + if (readOnly && largeFile !== undefined) { + return ( + + ) + } + return ( <> {!hostToolbar && (
    - {(markdown || html) && ( + {toggleable && (
    )} - {editable && truncated !== true && ( + {editable && (