diff --git a/backend/src/routes/internal/repo-mirror.ts b/backend/src/routes/internal/repo-mirror.ts index e971dd47..b933c448 100644 --- a/backend/src/routes/internal/repo-mirror.ts +++ b/backend/src/routes/internal/repo-mirror.ts @@ -273,8 +273,7 @@ export function createInternalRepoMirrorRoutes(db: Database) { return new Response(stream, { headers: { - 'Content-Type': 'application/x-tar', - ...(compress ? { 'Content-Encoding': 'gzip' } : {}), + ...(compress ? { 'Content-Type': 'application/gzip' } : { 'Content-Type': 'application/x-tar' }), }, }) }) diff --git a/backend/test/routes/internal/repo-mirror.test.ts b/backend/test/routes/internal/repo-mirror.test.ts index 47d3199a..6ffce21b 100644 --- a/backend/test/routes/internal/repo-mirror.test.ts +++ b/backend/test/routes/internal/repo-mirror.test.ts @@ -182,6 +182,35 @@ describe('internal-repo-mirror routes', () => { expect(readFileSync(join(extractDir, 'test.txt'), 'utf-8')).toBe('hello world') }) + it('returns gzip-compressed stream when ?compress=gzip', async () => { + const repoDir = join(getTmpRoot(), 'test-repo') + mkdirSync(repoDir, { recursive: true }) + writeFileSync(join(repoDir, 'test.txt'), 'hello world') + + mockGetRepoById.mockReturnValue({ id: 1, fullPath: repoDir }) + + const res = await app.request('/api/internal/repos/1/mirror?compress=gzip') + expect(res.status).toBe(200) + expect(res.headers.get('content-type')).toBe('application/gzip') + expect(res.headers.get('content-encoding')).toBeNull() + + const body = Buffer.from(await res.arrayBuffer()) + expect(body.length).toBeGreaterThan(0) + + // Verify the body is gzip-compressed (starts with gzip magic bytes) + expect(body[0]).toBe(0x1f) + expect(body[1]).toBe(0x8b) + + // Verify it extracts correctly via tar -xz + const extractDir = join(getTmpRoot(), 'extract-compressed') + mkdirSync(extractDir, { recursive: true }) + const tarFile = join(getTmpRoot(), 'test.tar.gz') + writeFileSync(tarFile, body) + spawnSync('tar', ['-xz', '-C', extractDir, '-f', tarFile], { stdio: 'inherit' }) + expect(existsSync(join(extractDir, 'test.txt'))).toBe(true) + expect(readFileSync(join(extractDir, 'test.txt'), 'utf-8')).toBe('hello world') + }) + it('returns 404 for non-existent repo', async () => { mockGetRepoById.mockReturnValue(null) diff --git a/ocm-cli/README.md b/ocm-cli/README.md index 1247f320..6836091b 100644 --- a/ocm-cli/README.md +++ b/ocm-cli/README.md @@ -69,6 +69,6 @@ export default [ocm] ## Requirements - `opencode` available on `PATH` -- `git` and `tar` available on `PATH` +- `git` and `tar` (with gzip support, i.e. the `-z` flag) available on `PATH` - macOS `security` CLI for Keychain-backed token storage - An OpenCode Manager URL and bearer token diff --git a/ocm-cli/bin/ocm.ts b/ocm-cli/bin/ocm.ts index 57ad386a..e08a78ad 100644 --- a/ocm-cli/bin/ocm.ts +++ b/ocm-cli/bin/ocm.ts @@ -296,11 +296,7 @@ export async function cmdPush(args: string[]): Promise { const repos = await fetchRepos(state.managerUrl, token) const progress = createProgressReporter('push') - const onProgress = (p: MirrorProgress) => { - if (p.phase === 'committing') progress.tick(p.bytesSent) - else if (p.totalBytes > 0) progress.update(p.bytesSent, p.totalBytes) - else progress.tick(p.bytesSent) - } + const onProgress = (p: MirrorProgress) => progress.tick(p.bytesSent) const remotes: RemoteRepoSummary[] = repos.map((r) => ({ repoId: r.repoId, diff --git a/ocm-cli/package.json b/ocm-cli/package.json index 9fcaa349..3a88447b 100644 --- a/ocm-cli/package.json +++ b/ocm-cli/package.json @@ -1,6 +1,6 @@ { "name": "@opencode-manager/ocm-cli", - "version": "0.1.3", + "version": "0.1.4", "description": "OpenCode Manager CLI: attach a local OpenCode TUI to a Manager-hosted repo.", "license": "MIT", "repository": { diff --git a/ocm-cli/src/manager-api.ts b/ocm-cli/src/manager-api.ts index 41fdf613..c9a2a7bc 100644 --- a/ocm-cli/src/manager-api.ts +++ b/ocm-cli/src/manager-api.ts @@ -90,12 +90,12 @@ export class ManagerApi { if (!res.ok) throw await formatErrorResponse(res, `mirror part ${index}`) } - async mirrorCommit(repoId: number, uploadId: string, totalParts: number): Promise { + async mirrorCommit(repoId: number, uploadId: string, totalParts: number, gzip: boolean): Promise { const url = `${this.baseUrl}/api/internal/repos/${repoId}/mirror/commit` const res = await fetch(url, { method: 'POST', headers: { ...this.headers(), 'Content-Type': 'application/json' }, - body: JSON.stringify({ uploadId, totalParts }), + body: JSON.stringify({ uploadId, totalParts, gzip }), }) if (!res.ok) throw await formatErrorResponse(res, 'mirror commit') return (await res.json()) as MirrorCommitResult @@ -106,8 +106,9 @@ export class ManagerApi { await fetch(url, { method: 'DELETE', headers: this.headers() }).catch(() => { /* best-effort */ }) } - async mirrorDown(repoId: number): Promise> { - const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror`, { + async mirrorDown(repoId: number, gzip: boolean): Promise> { + const query = gzip ? '?compress=gzip' : '' + const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror${query}`, { headers: this.headers(), }) diff --git a/ocm-cli/src/mirror.ts b/ocm-cli/src/mirror.ts index 3ca0cee1..566ecc9c 100644 --- a/ocm-cli/src/mirror.ts +++ b/ocm-cli/src/mirror.ts @@ -1,5 +1,5 @@ import { spawnSync, spawn } from 'child_process' -import { existsSync, statSync } from 'fs' +import { existsSync } from 'fs' import * as fsp from 'fs/promises' import { Readable } from 'stream' import { join, dirname } from 'path' @@ -11,6 +11,7 @@ import { ManagerApiError } from './manager-api.js' const HARDCODED_EXCLUDES = ['node_modules', 'dist', '.next', '.venv', '__pycache__', '.turbo', '.DS_Store', '._*'] const PART_RETRIES = 3 const PART_BACKOFF_MS = [500, 2000, 8000] +const MIRROR_GZIP = true function getGitignoreExclusions(repoRoot: string): string[] { const res = spawnSync('git', ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory'], { @@ -34,32 +35,6 @@ async function carryOverIgnored(fromDir: string, toDir: string): Promise { } } -function listIncludedFiles(repoRoot: string): string[] { - const tracked = spawnSync('git', ['ls-files', '-z'], { cwd: repoRoot, encoding: 'utf-8' }) - const untracked = spawnSync('git', ['ls-files', '--others', '--exclude-standard', '-z'], { cwd: repoRoot, encoding: 'utf-8' }) - const split = (out: string | null): string[] => (out ?? '').split('\0').filter((p) => p.length > 0) - const all = [...split(tracked.stdout), ...split(untracked.stdout)] - return all.filter((p) => { - const top = p.split('/')[0] ?? p - return !HARDCODED_EXCLUDES.includes(top) - }) -} - -export function estimateTarSize(repoRoot: string): number { - const files = listIncludedFiles(repoRoot) - let total = 0 - for (const rel of files) { - let size = 0 - try { - size = statSync(join(repoRoot, rel)).size - } catch { - continue - } - total += 512 + Math.ceil(size / 512) * 512 - } - return total + 1024 -} - export class MirrorAbort extends Error { constructor(message: string) { super(message) @@ -93,9 +68,7 @@ export function prepareMirror(cwd: string, remotes: RemoteRepoSummary[]): Mirror } export interface MirrorProgress { - phase: 'uploading' | 'committing' bytesSent: number - totalBytes: number } export interface MirrorUpOpts { @@ -192,10 +165,10 @@ export async function mirrorUp( const begin = await opts.api.mirrorBegin(repoId, { force: opts.force, create: opts.create }) - const totalBytes = estimateTarSize(plan.repoRoot) let bytesSent = 0 const tarArgs = ['-c', '-C', plan.repoRoot] + if (MIRROR_GZIP) tarArgs.unshift('-z') for (const dir of HARDCODED_EXCLUDES) tarArgs.push('--exclude', dir) const ignoredPaths = getGitignoreExclusions(plan.repoRoot) @@ -234,12 +207,12 @@ export async function mirrorUp( for await (const chunk of child.stdout as AsyncIterable) { await flusher.push(chunk) bytesSent += chunk.length - opts.onProgress?.({ phase: 'uploading', bytesSent, totalBytes }) + opts.onProgress?.({ bytesSent }) } await tarExit const totalParts = await flusher.finish() - opts.onProgress?.({ phase: 'committing', bytesSent, totalBytes }) - const result = await opts.api.mirrorCommit(begin.repoId, begin.uploadId, totalParts) + opts.onProgress?.({ bytesSent }) + const result = await opts.api.mirrorCommit(begin.repoId, begin.uploadId, totalParts, MIRROR_GZIP) return result } catch (err) { if (!child.killed) child.kill('SIGKILL') @@ -266,9 +239,11 @@ export async function mirrorDown( await fsp.mkdir(staging, { recursive: true }) try { - const tarball = await api.mirrorDown(repoId) + const tarball = await api.mirrorDown(repoId, MIRROR_GZIP) - const child = spawn('tar', ['-x', '-f', '-', '-C', staging], { stdio: ['pipe', 'pipe', 'pipe'] }) + const tarArgs = ['-x', '-f', '-', '-C', staging] + if (MIRROR_GZIP) tarArgs.unshift('-z') + const child = spawn('tar', tarArgs, { stdio: ['pipe', 'pipe', 'pipe'] }) const stderrChunks: Buffer[] = [] child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk)) diff --git a/ocm-cli/src/progress.ts b/ocm-cli/src/progress.ts index d1ad37b5..be7dec98 100644 --- a/ocm-cli/src/progress.ts +++ b/ocm-cli/src/progress.ts @@ -19,7 +19,6 @@ export interface ProgressSink { } export interface ProgressReporter { - update(current: number, total: number): void tick(bytes: number): void done(): void } @@ -31,30 +30,11 @@ export function createProgressReporter( ): ProgressReporter { let finished = false let lastRenderAt = -Infinity - let lastBucket = -1 let lastNonTtyTickAt = -Infinity let frameIndex = 0 const isTTY = out.isTTY === true return { - update(current: number, total: number): void { - if (finished) return - - if (isTTY) { - const t = now() - if (t - lastRenderAt < 80) return - lastRenderAt = t - const pct = total > 0 ? Math.min(99, Math.floor((current / total) * 100)) : 0 - out.write(`\r\x1b[K${label}: ${pct}% (${formatBytes(current)} / ${formatBytes(total)})`) - } else { - const pct = total > 0 ? Math.min(99, Math.floor((current / total) * 100)) : 0 - const bucket = Math.floor(pct / 10) - if (bucket === lastBucket) return - lastBucket = bucket - out.write(`${label}: ${pct}% (${formatBytes(current)} / ${formatBytes(total)})\n`) - } - }, - tick(bytes: number): void { if (finished) return const t = now() diff --git a/ocm-cli/test/mirror.test.ts b/ocm-cli/test/mirror.test.ts index fe5df27f..c4d8ff11 100644 --- a/ocm-cli/test/mirror.test.ts +++ b/ocm-cli/test/mirror.test.ts @@ -2,8 +2,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readdirSync, readFileSync } from 'fs' import { join } from 'path' import { tmpdir } from 'os' +import { randomBytes } from 'crypto' import { spawnSync, execSync } from 'child_process' -import { prepareMirror, MirrorAbort, estimateTarSize, mirrorDown, mirrorUp } from '../src/mirror' +import { prepareMirror, MirrorAbort, mirrorDown, mirrorUp } from '../src/mirror' describe('prepareMirror', () => { let tmpDir: string @@ -66,51 +67,6 @@ describe('prepareMirror', () => { }) }) -describe('estimateTarSize', () => { - let tmpDir: string - - beforeEach(() => { - tmpDir = mkdtempSync(join(tmpdir(), 'estimate-tar-test-')) - }) - - afterEach(() => { - rmSync(tmpDir, { recursive: true, force: true }) - }) - - it('returns a value > 0 for a repo with content, and respects 512-byte tar block alignment', () => { - const repoRoot = join(tmpDir, 'repo') - mkdirSync(repoRoot) - spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' }) - const fileSize = 12345 - writeFileSync(join(repoRoot, 'data.bin'), Buffer.alloc(fileSize, 0xab)) - spawnSync('git', ['add', 'data.bin'], { cwd: repoRoot, stdio: 'ignore' }) - - const size = estimateTarSize(repoRoot) - expect(size).toBeGreaterThan(0) - expect(size).toBeGreaterThanOrEqual(fileSize) - expect((size - 1024) % 512).toBe(0) - }) - - it('excludes files under HARDCODED_EXCLUDES directories', () => { - const repoRoot = join(tmpDir, 'repo-excl') - mkdirSync(repoRoot) - spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' }) - - writeFileSync(join(repoRoot, 'tracked.txt'), 'hello') - spawnSync('git', ['add', 'tracked.txt'], { cwd: repoRoot, stdio: 'ignore' }) - - mkdirSync(join(repoRoot, 'node_modules')) - writeFileSync(join(repoRoot, 'node_modules', 'big.bin'), Buffer.alloc(99999, 0x42)) - - const sizeWithExcluded = estimateTarSize(repoRoot) - - rmSync(join(repoRoot, 'node_modules'), { recursive: true, force: true }) - const sizeWithoutExcluded = estimateTarSize(repoRoot) - - expect(sizeWithExcluded).toBe(sizeWithoutExcluded) - }) -}) - describe('cmdPush', () => { let originalArgv: string[] let originalIsTTY: boolean | undefined @@ -174,12 +130,20 @@ describe('mirrorDown', () => { rmSync(tmpDir, { recursive: true, force: true }) }) - function createTarball(dir: string): Buffer { - const tarFile = join(tmpDir, 'test.tar') - execSync(`tar -cf "${tarFile}" -C "${dir}" .`) + function createGzipTarball(dir: string): Buffer { + const tarFile = join(tmpDir, 'test.tar.gz') + execSync(`tar -czf "${tarFile}" -C "${dir}" .`) return require('fs').readFileSync(tarFile) } + const streamOf = (buf: Buffer): ReadableStream => + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(buf)) + controller.close() + }, + }) + it('stages tarball in sibling directory next to repoRoot', async () => { const repoRoot = join(tmpDir, 'repo') mkdirSync(repoRoot) @@ -189,17 +153,10 @@ describe('mirrorDown', () => { mkdirSync(contentDir) writeFileSync(join(contentDir, 'file.txt'), 'hello') - const tarData = createTarball(contentDir) + const tarData = createGzipTarball(contentDir) const mockApi = { - mirrorDown: vi.fn().mockResolvedValue( - new ReadableStream({ - start(controller) { - controller.enqueue(new Uint8Array(tarData)) - controller.close() - }, - }) - ), + mirrorDown: vi.fn().mockResolvedValue(streamOf(tarData)), } as any await mirrorDown(1, repoRoot, mockApi, { force: true }) @@ -220,17 +177,10 @@ describe('mirrorDown', () => { mkdirSync(contentDir) writeFileSync(join(contentDir, 'new-file.txt'), 'new content') - const tarData = createTarball(contentDir) + const tarData = createGzipTarball(contentDir) const mockApi = { - mirrorDown: vi.fn().mockResolvedValue( - new ReadableStream({ - start(controller) { - controller.enqueue(new Uint8Array(tarData)) - controller.close() - }, - }) - ), + mirrorDown: vi.fn().mockResolvedValue(streamOf(tarData)), } as any try { @@ -277,17 +227,10 @@ describe('mirrorDown', () => { writeFileSync(join(contentDir, 'new-file.txt'), 'new content') writeFileSync(join(contentDir, 'updated.txt'), 'updated content') - const tarData = createTarball(contentDir) + const tarData = createGzipTarball(contentDir) const mockApi = { - mirrorDown: vi.fn().mockResolvedValue( - new ReadableStream({ - start(controller) { - controller.enqueue(new Uint8Array(tarData)) - controller.close() - }, - }) - ), + mirrorDown: vi.fn().mockResolvedValue(streamOf(tarData)), } as any const originalCwd = process.cwd() @@ -317,17 +260,10 @@ describe('mirrorDown', () => { mkdirSync(contentDir) writeFileSync(join(contentDir, 'new-file.txt'), 'new content') - const tarData = createTarball(contentDir) + const tarData = createGzipTarball(contentDir) const mockApi = { - mirrorDown: vi.fn().mockResolvedValue( - new ReadableStream({ - start(controller) { - controller.enqueue(new Uint8Array(tarData)) - controller.close() - }, - }) - ), + mirrorDown: vi.fn().mockResolvedValue(streamOf(tarData)), } as any await mirrorDown(1, repoRoot, mockApi, { force: true }) @@ -361,17 +297,10 @@ describe('mirrorDown', () => { writeFileSync(join(contentDir, 'tracked.txt'), 'new tracked') writeFileSync(join(contentDir, 'added.txt'), 'added') - const tarData = createTarball(contentDir) + const tarData = createGzipTarball(contentDir) const mockApi = { - mirrorDown: vi.fn().mockResolvedValue( - new ReadableStream({ - start(controller) { - controller.enqueue(new Uint8Array(tarData)) - controller.close() - }, - }) - ), + mirrorDown: vi.fn().mockResolvedValue(streamOf(tarData)), } as any await mirrorDown(1, repoRoot, mockApi, { force: true }) @@ -395,17 +324,10 @@ describe('mirrorDown', () => { mkdirSync(contentDir) writeFileSync(join(contentDir, 'file.txt'), 'hello') - const tarData = createTarball(contentDir) + const tarData = createGzipTarball(contentDir) const mockApi = { - mirrorDown: vi.fn().mockResolvedValue( - new ReadableStream({ - start(controller) { - controller.enqueue(new Uint8Array(tarData)) - controller.close() - }, - }) - ), + mirrorDown: vi.fn().mockResolvedValue(streamOf(tarData)), } as any const onProgress = vi.fn() @@ -422,6 +344,30 @@ describe('mirrorDown', () => { prev = v } }) + + it('extracts a gzipped tarball produced by tar -czf', async () => { + const repoRoot = join(tmpDir, 'repo-gzip') + mkdirSync(repoRoot) + spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' }) + + const contentDir = join(tmpDir, 'content-gzip') + mkdirSync(contentDir) + writeFileSync(join(contentDir, 'file.txt'), 'hello from gzip') + + const tarData = createGzipTarball(contentDir) + + const mockApi = { + mirrorDown: vi.fn().mockResolvedValue(streamOf(tarData)), + } as any + + await mirrorDown(1, repoRoot, mockApi, { force: true }) + + expect(existsSync(join(repoRoot, 'file.txt'))).toBe(true) + expect(readFileSync(join(repoRoot, 'file.txt'), 'utf-8')).toBe('hello from gzip') + + const entries = readdirSync(tmpDir).filter((e) => e.startsWith('repo-gzip.ocm-recv-')) + expect(entries.length).toBe(0) + }) }) describe('mirrorUp chunked upload', () => { @@ -450,7 +396,7 @@ describe('mirrorUp chunked upload', () => { } partsReceived[index] = Buffer.from(chunk) }), - mirrorCommit: vi.fn().mockImplementation(async (_repoId: number, _uploadId: string, totalParts: number) => { + mirrorCommit: vi.fn().mockImplementation(async (_repoId: number, _uploadId: string, totalParts: number, _gzip: boolean) => { committed = true commitTotalParts = totalParts return { repoId: 1, fullPath: '/tmp/x', branch: 'main', head: 'abc', created: false } @@ -491,8 +437,8 @@ describe('mirrorUp chunked upload', () => { const repoRoot = join(tmpDir, 'repo-multi') mkdirSync(repoRoot) spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' }) - writeFileSync(join(repoRoot, 'a.bin'), Buffer.alloc(200 * 1024, 0xab)) - writeFileSync(join(repoRoot, 'b.bin'), Buffer.alloc(200 * 1024, 0xcd)) + writeFileSync(join(repoRoot, 'a.bin'), randomBytes(200 * 1024)) + writeFileSync(join(repoRoot, 'b.bin'), randomBytes(200 * 1024)) const ctx = makeMockApi({ chunkSize: 128 * 1024 }) const plan = { @@ -546,7 +492,7 @@ describe('mirrorUp chunked upload', () => { expect(ctx.api.mirrorAbort).toHaveBeenCalledWith(1, 'upload-1') }) - it('calls onProgress with monotonically non-decreasing bytesSent and a terminal committing phase', async () => { + it('calls onProgress with monotonically non-decreasing bytesSent', async () => { const repoRoot = join(tmpDir, 'repo-progress') mkdirSync(repoRoot) spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' }) @@ -564,19 +510,32 @@ describe('mirrorUp chunked upload', () => { expect(onProgress).toHaveBeenCalled() - const uploadingCalls = onProgress.mock.calls.filter(([p]) => p.phase === 'uploading') - expect(uploadingCalls.length).toBeGreaterThanOrEqual(1) - let prevBytes = -1 - for (const [p] of uploadingCalls) { + for (const [p] of onProgress.mock.calls) { expect(p.bytesSent).toBeGreaterThanOrEqual(prevBytes) - expect(p.totalBytes).toBeGreaterThan(0) prevBytes = p.bytesSent } + }) - const committingCalls = onProgress.mock.calls.filter(([p]) => p.phase === 'committing') - expect(committingCalls.length).toBe(1) - expect(committingCalls[0][0].totalBytes).toBeGreaterThan(0) - expect(committingCalls[0][0].bytesSent).toBeGreaterThanOrEqual(0) + it('commits with gzip=true and produces a gzip-magic tar stream', async () => { + const repoRoot = join(tmpDir, 'repo-small') + mkdirSync(repoRoot) + spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' }) + writeFileSync(join(repoRoot, 'tracked.txt'), 'tracked content') + + const ctx = makeMockApi() + const plan = { + repoRoot, + localOrigin: 'https://github.com/test/repo.git', + matched: [{ repoId: 1, name: 'test-repo', originUrl: 'https://github.com/test/repo.git', branch: 'main' }], + } + + await mirrorUp(plan, { api: ctx.api as any, force: false }) + + expect(ctx.api.mirrorCommit.mock.calls[0]![3]).toBe(true) + + const combined = Buffer.concat(ctx.partsReceived) + expect(combined[0]).toBe(0x1f) + expect(combined[1]).toBe(0x8b) }) }) diff --git a/ocm-cli/test/progress.test.ts b/ocm-cli/test/progress.test.ts index e89e64cb..845310d3 100644 --- a/ocm-cli/test/progress.test.ts +++ b/ocm-cli/test/progress.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest' import { formatBytes, createProgressReporter } from '../src/progress' -import type { ProgressSink, ProgressReporter } from '../src/progress' +import type { ProgressSink } from '../src/progress' describe('formatBytes', () => { it('returns "0 B" for 0', () => { @@ -41,111 +41,6 @@ describe('createProgressReporter', () => { return { sink, writes } } - describe('non-TTY update', () => { - it('emits a line only when the 10%-bucket advances', () => { - let fakeTime = 100_000 - const now = () => fakeTime - const { sink, writes } = createSink(false) - const reporter = createProgressReporter('Test', sink, now) - - // 0% — bucket 0, previous bucket -1, writes - reporter.update(0, 100) - expect(writes).toHaveLength(1) - expect(writes[0]).toBe('Test: 0% (0 B / 100 B)\n') - fakeTime += 1000 - - // 5% — bucket 0, same bucket, no write - reporter.update(5, 100) - expect(writes).toHaveLength(1) - - // 15% — bucket 1, advances, writes - reporter.update(15, 100) - expect(writes).toHaveLength(2) - expect(writes[1]).toBe('Test: 15% (15 B / 100 B)\n') - fakeTime += 1000 - - // 25% — bucket 2, advances, writes - reporter.update(25, 100) - expect(writes).toHaveLength(3) - expect(writes[2]).toBe('Test: 25% (25 B / 100 B)\n') - fakeTime += 1000 - - // 100% — pct clamped to 99, bucket 9, advances, writes - reporter.update(100, 100) - expect(writes).toHaveLength(4) - expect(writes[3]).toContain('99%') - }) - - it('never renders a percentage above 99 even when current exceeds total', () => { - const { sink, writes } = createSink(false) - const reporter = createProgressReporter('Test', sink) - - reporter.update(200, 100) - expect(writes.length).toBeGreaterThanOrEqual(1) - for (const w of writes) { - expect(w).toMatch(/\d+%/) - const pct = parseInt(w.match(/(\d+)%/)![1]!, 10) - expect(pct).toBeLessThanOrEqual(99) - } - }) - - it('emits a line on the first update even at 0%', () => { - const { sink, writes } = createSink(false) - const reporter = createProgressReporter('Test', sink) - - reporter.update(0, 100) - expect(writes).toHaveLength(1) - expect(writes[0]).toBe('Test: 0% (0 B / 100 B)\n') - }) - }) - - describe('TTY update', () => { - it('output begins with carriage return and clear line', () => { - let fakeTime = 100_000 - const now = () => fakeTime - const { sink, writes } = createSink(true) - const reporter = createProgressReporter('Test', sink, now) - - reporter.update(10, 100) - expect(writes).toHaveLength(1) - expect(writes[0]).toMatch(/^\r\x1b\[K/) - expect(writes[0]).toContain('Test: 10%') - expect(writes[0]).toContain('10 B') - expect(writes[0]).toContain('100 B') - }) - - it('throttles renders to at least 80ms apart', () => { - let fakeTime = 100_000 - const now = () => fakeTime - const { sink, writes } = createSink(true) - const reporter = createProgressReporter('Test', sink, now) - - // First render - reporter.update(10, 100) - expect(writes).toHaveLength(1) - - // Too soon — 40ms later - fakeTime += 40 - reporter.update(20, 100) - expect(writes).toHaveLength(1) - - // After 80ms — should render - fakeTime += 40 - reporter.update(30, 100) - expect(writes).toHaveLength(2) - }) - - it('clamps percentage at 99', () => { - let fakeTime = 100_000 - const now = () => fakeTime - const { sink, writes } = createSink(true) - const reporter = createProgressReporter('Test', sink, now) - - reporter.update(200, 100) - expect(writes[0]).toContain('99%') - }) - }) - describe('TTY tick', () => { it('output begins with carriage return and clear line and uses spinner frames', () => { let fakeTime = 100_000 @@ -266,19 +161,6 @@ describe('createProgressReporter', () => { }) describe('finished guard', () => { - it('update is a no-op after done()', () => { - let fakeTime = 100_000 - const now = () => fakeTime - const { sink, writes } = createSink(true) - const reporter = createProgressReporter('Test', sink, now) - - reporter.done() - const before = writes.length - - reporter.update(50, 100) - expect(writes.length).toBe(before) - }) - it('tick is a no-op after done()', () => { let fakeTime = 100_000 const now = () => fakeTime