From a7bac5b77557e0ad8ef3b0bdb75ff2b182133728 Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Wed, 22 Jul 2026 15:19:44 +0000 Subject: [PATCH 1/3] feat(upgrade): progress bars for delta-patch apply and full download MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `sentry upgrade` currently gives no feedback during the slow phases. Adds two byte-driven progress bars, gated on interactive output (isPlainOutput()), so they self-suppress under NO_COLOR, piped stdout, and CI. - Apply phase: a determinate bar in applyChainAndReturn. Total is the final binary size (the last patch's declared newSize), so the number shown is the real output the user gets — not the sum of intermediate hop writes. Progress is byte-driven across all hops via an onBytes callback threaded through applyReaderToMemory/applyReaderToFile -> applyPatchChainInMemory -> applyPatchChain, so the bar advances smoothly through the whole chain. - Full-binary download: an indeterminate byte counter in streamDecompressToFile. The decompressed size isn't known ahead of time (Content-Length covers only the compressed stream), so it shows a live byte count rather than a fake fraction. New src/lib/progress.ts (makeByteProgress): reuses the existing formatBytes and isPlainOutput helpers; cosmetic-only — a render failure never aborts the upgrade, and both onProgress and done() are guarded against throwing streams. Tests (test/lib/progress.test.ts, 7): determinate/indeterminate rendering, plain-output and non-TTY header-only behavior, byte accumulation, full-bar clamping, and the never-throws contract — mutation-verified: an unguarded done() turns the never-throws test RED. --- src/lib/bspatch.ts | 15 +++-- src/lib/delta-upgrade.ts | 43 ++++++++++-- src/lib/progress.ts | 100 ++++++++++++++++++++++++++++ src/lib/upgrade.ts | 7 ++ test/lib/progress.test.ts | 135 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 288 insertions(+), 12 deletions(-) create mode 100644 src/lib/progress.ts create mode 100644 test/lib/progress.test.ts diff --git a/src/lib/bspatch.ts b/src/lib/bspatch.ts index 7df06205e6..c795660ded 100644 --- a/src/lib/bspatch.ts +++ b/src/lib/bspatch.ts @@ -588,7 +588,8 @@ async function transformPatch( async function applyReaderToFile( oldReader: OldReader, patchData: Uint8Array, - destPath: string + destPath: string, + onBytes?: (bytes: number) => void ): Promise { const writer = createWriteStream(destPath); const hasher = createHash("sha256"); @@ -610,6 +611,7 @@ async function applyReaderToFile( } writer.write(chunk); hasher.update(chunk); + onBytes?.(chunk.byteLength); }); } finally { await new Promise((resolve, reject) => { @@ -642,7 +644,8 @@ async function applyReaderToFile( */ async function applyReaderToMemory( oldReader: OldReader, - patchData: Uint8Array + patchData: Uint8Array, + onBytes?: (bytes: number) => void ): Promise { // Preallocate the exact output size from the header so chunks can be copied // in place — avoids a final concat pass over ~100 MB of output. @@ -653,6 +656,7 @@ async function applyReaderToMemory( await transformPatch(oldReader, patchData, (chunk) => { output.set(chunk, offset); offset += chunk.byteLength; + onBytes?.(chunk.byteLength); }); return output; @@ -701,7 +705,8 @@ export function applyPatchToMemory( export async function applyPatchChainInMemory( oldPath: string, patches: Uint8Array[], - destPath: string + destPath: string, + onBytes?: (bytes: number) => void ): Promise { if (patches.length === 0) { throw new Error("Cannot apply an empty patch chain"); @@ -719,7 +724,7 @@ export async function applyPatchChainInMemory( if (!patch) { throw new Error(`Missing patch at index ${i}`); } - const next = await applyReaderToMemory(reader, patch); + const next = await applyReaderToMemory(reader, patch, onBytes); await reader.close(); reader = new MemoryOldReader(next); } @@ -729,7 +734,7 @@ export async function applyPatchChainInMemory( if (!finalPatch) { throw new Error("Missing final patch"); } - return await applyReaderToFile(reader, finalPatch, destPath); + return await applyReaderToFile(reader, finalPatch, destPath, onBytes); } finally { await reader.close(); } diff --git a/src/lib/delta-upgrade.ts b/src/lib/delta-upgrade.ts index b6e0a2fee5..7a97cbf61d 100644 --- a/src/lib/delta-upgrade.ts +++ b/src/lib/delta-upgrade.ts @@ -27,7 +27,7 @@ import { isDowngrade, isNightlyVersion, } from "./binary.js"; -import { applyPatchChainInMemory } from "./bspatch.js"; +import { applyPatchChainInMemory, parsePatchHeader } from "./bspatch.js"; import { CLI_VERSION } from "./constants.js"; import { customFetch } from "./custom-ca.js"; import { formatBytes } from "./formatters/numbers.js"; @@ -40,6 +40,7 @@ import { } from "./ghcr.js"; import { logger } from "./logger.js"; import { loadCachedChain, savePatchesToCache } from "./patch-cache.js"; +import { makeByteProgress } from "./progress.js"; import { withTracing, withTracingSpan } from "./telemetry.js"; /** Scoped logger for delta upgrade operations */ @@ -979,11 +980,37 @@ async function applyChainAndReturn( oldBinaryPath: string, destPath: string ): Promise { - const sha256 = await withTracing( - "apply-patch-chain", - "upgrade.delta.apply", - () => applyPatchChain(chain, oldBinaryPath, destPath) + // Progress bar for the apply phase. Total is the final binary size (the last + // patch's declared `newSize`), so the number shown is the real output the + // user gets — not the sum of intermediate hop writes. The bar advances per + // byte written across all hops, staying smooth through the chain. Cosmetic + // only: a render failure never aborts the apply, and it self-suppresses off + // an interactive TTY. + let finalSize: number | null = null; + try { + const last = chain.patches.at(-1); + if (last) { + finalSize = parsePatchHeader(last.data).newSize; + } + } catch { + // Header parse is best-effort for the bar; a corrupt header is rejected + // properly downstream. Leave the bar indeterminate in that case. + finalSize = null; + } + const progress = makeByteProgress( + `Applying ${chain.patches.length} patch(es)`, + finalSize ); + + let sha256: string; + try { + sha256 = await withTracing("apply-patch-chain", "upgrade.delta.apply", () => + applyPatchChain(chain, oldBinaryPath, destPath, progress.onProgress) + ); + } finally { + progress.done(); + } + return { sha256, patchBytes: chain.totalSize, @@ -1178,7 +1205,8 @@ async function resolveNightlyChainWithContext( export function applyPatchChain( chain: PatchChain, oldBinaryPath: string, - destPath: string + destPath: string, + onBytes?: (bytes: number) => void ): Promise { return withTracingSpan( "apply-patches", @@ -1197,7 +1225,8 @@ export function applyPatchChain( const sha256 = await applyPatchChainInMemory( oldBinaryPath, chain.patches.map((p) => p.data), - destPath + destPath, + onBytes ); // Verify the final SHA-256 matches diff --git a/src/lib/progress.ts b/src/lib/progress.ts new file mode 100644 index 0000000000..ed27c58a2e --- /dev/null +++ b/src/lib/progress.ts @@ -0,0 +1,100 @@ +/** + * Byte-driven progress bar for long-running upgrade phases (patch apply, + * full-binary download). + * + * Design contract: + * - Renders only when output is interactive (respects `isPlainOutput()`, so + * `NO_COLOR`, piped stdout, and CI all suppress the bar). In plain mode it + * prints the label once. + * - Cosmetic ONLY — rendering must never throw or abort the underlying work. + * - Determinate when a byte `total` is supplied; an indeterminate byte counter + * otherwise (the decompressed download size isn't known ahead of time). + * + * One line, redrawn in place via carriage return; `done()` clears the line so + * the next message prints cleanly. + */ + +import { formatBytes } from "./formatters/numbers.js"; +import { isPlainOutput } from "./formatters/plain-detect.js"; + +export type ByteProgressOut = { + isTTY?: boolean; + write: (s: string) => unknown; +}; + +export type ByteProgress = { + /** Report `bytes` additional bytes processed since the last call. */ + onProgress: (bytes: number) => void; + /** Clear the progress line (call before printing the next message). */ + done: () => void; +}; + +const BAR_WIDTH = 16; + +function renderBar(frac: number, width = BAR_WIDTH): string { + const filled = Math.max(0, Math.min(width, Math.round(width * frac))); + return "█".repeat(filled) + "░".repeat(width - filled); +} + +/** + * Create a byte-progress bar. + * + * @param label - Short label shown before the bar (e.g. "Applying 3 patches"). + * @param totalBytes - Expected total bytes; `null` renders an indeterminate + * byte counter instead of a bar. + * @param out - Output stream (defaults to stderr, the CLI's progress channel). + */ +export function makeByteProgress( + label: string, + totalBytes: number | null, + out: ByteProgressOut = process.stderr +): ByteProgress { + // Interactive only: a real TTY AND not forced into plain output. + const interactive = !!out.isTTY && !isPlainOutput(); + let written = 0; + let lastLen = 0; + let headerShown = false; + + const line = (): string => { + if (totalBytes === null || totalBytes <= 0) { + return `${label} ${formatBytes(written)}`; + } + const frac = Math.min(written / totalBytes, 1); + return ( + `${label} [${renderBar(frac)}] ` + + `${formatBytes(written)} / ${formatBytes(totalBytes)}` + ); + }; + + const onProgress = (bytes: number): void => { + // Cosmetic only — a rendering failure must never abort the operation. + try { + written += bytes; + if (!interactive) { + if (!headerShown) { + out.write(`${label}\n`); + headerShown = true; + } + return; + } + const l = line(); + lastLen = l.length; + out.write(`\r${l}`); + } catch { + // ignore — progress is cosmetic + } + }; + + const done = (): void => { + // Cosmetic only — must never throw, matching onProgress's contract. + try { + if (interactive && lastLen > 0) { + out.write(`\r${" ".repeat(lastLen)}\r`); + } + } catch { + // ignore — progress is cosmetic + } + }; + + return { onProgress, done }; +} diff --git a/src/lib/upgrade.ts b/src/lib/upgrade.ts index d15f036e9f..ab445dcd6a 100644 --- a/src/lib/upgrade.ts +++ b/src/lib/upgrade.ts @@ -50,6 +50,7 @@ import { } from "./ghcr.js"; import { logger } from "./logger.js"; import { clearPatchCache } from "./patch-cache.js"; +import { makeByteProgress } from "./progress.js"; /** Scoped logger for upgrade operations */ const log = logger.withTag("upgrade"); @@ -578,6 +579,10 @@ async function streamDecompressToFile( ): Promise { const stream = body.pipeThrough(new DecompressionStream("gzip")); const writer = createWriteStream(destPath); + // Indeterminate byte counter: the decompressed size isn't known ahead of + // time (Content-Length covers only the compressed stream), so we show a live + // byte count rather than a misleading fraction. Cosmetic — never aborts. + const progress = makeByteProgress("Downloading", null); // Capture write errors early — without a listener, Node crashes with // ERR_UNHANDLED_ERROR if a write fails (ENOSPC, EIO, etc.) during the loop. let writeError: Error | undefined; @@ -590,6 +595,7 @@ async function streamDecompressToFile( break; } const ok = writer.write(chunk); + progress.onProgress(chunk.byteLength); if (!(ok || writeError)) { // Race drain against error — an I/O failure (ENOSPC) while the // buffer is full would never emit 'drain', causing a hang. @@ -619,6 +625,7 @@ async function streamDecompressToFile( } }); }); + progress.done(); } } diff --git a/test/lib/progress.test.ts b/test/lib/progress.test.ts new file mode 100644 index 0000000000..383bc072ae --- /dev/null +++ b/test/lib/progress.test.ts @@ -0,0 +1,135 @@ +/** + * Unit tests for the byte-driven upgrade progress bar. + * + * The bar is cosmetic-only and must never abort the operation it decorates. + * Coverage: determinate fraction rendering, indeterminate byte counter, + * plain-output (non-interactive) header-only behavior, byte accumulation, + * full-bar clamping, and the never-throws contract for both onProgress and + * done(). + * + * Rendering is gated on `isPlainOutput()`, so we force rich output via + * SENTRY_PLAIN_OUTPUT=0 (see plain-detect.ts precedence) and drive a fake + * TTY stream. + */ + +import { afterEach, beforeEach, describe, expect, test } from "vitest"; + +import { makeByteProgress } from "../../src/lib/progress.js"; + +type FakeOut = { + isTTY: boolean; + writes: string[]; + write: (s: string) => boolean; +}; + +function fakeOut(isTTY: boolean): FakeOut { + const writes: string[] = []; + return { + isTTY, + writes, + write(s: string) { + writes.push(s); + return true; + }, + }; +} + +describe("makeByteProgress", () => { + const saved: Record = {}; + + beforeEach(() => { + // Force rich output so the interactive path renders regardless of CI env + // (NO_COLOR=1 etc.). SENTRY_PLAIN_OUTPUT has highest precedence. + for (const key of ["SENTRY_PLAIN_OUTPUT", "NO_COLOR", "FORCE_COLOR"]) { + saved[key] = process.env[key]; + delete process.env[key]; + } + process.env.SENTRY_PLAIN_OUTPUT = "0"; // force rich + }); + + afterEach(() => { + for (const key of ["SENTRY_PLAIN_OUTPUT", "NO_COLOR", "FORCE_COLOR"]) { + const v = saved[key]; + if (v === undefined) { + delete process.env[key]; + } else { + process.env[key] = v; + } + } + }); + + test("renders a determinate bar advancing with reported bytes", () => { + const out = fakeOut(true); + const p = makeByteProgress("Applying 3 patch(es)", 1000, out); + p.onProgress(500); + p.onProgress(500); + p.done(); + + const last = out.writes.at(-2); // last real line before the clear + expect(last).toContain("Applying 3 patch(es)"); + expect(last).toContain("█".repeat(16)); // 1000/1000 → full bar + }); + + test("renders an indeterminate byte counter when total is null", () => { + const out = fakeOut(true); + const p = makeByteProgress("Downloading", null, out); + p.onProgress(2048); + p.done(); + + const last = out.writes.at(-2); + expect(last).toContain("Downloading"); + expect(last).not.toContain("░"); // no bar in indeterminate mode + }); + + test("accumulates bytes across multiple onProgress calls", () => { + const out = fakeOut(true); + const p = makeByteProgress("Applying", 100, out); + p.onProgress(10); + p.onProgress(40); + p.onProgress(50); // total 100 → full + p.done(); + expect(out.writes.at(-2)).toContain("█".repeat(16)); + }); + + test("clamps the bar at full even if bytes exceed the total", () => { + const out = fakeOut(true); + const p = makeByteProgress("Applying", 100, out); + p.onProgress(5000); + p.done(); + const last = out.writes.at(-2); + expect(last).toContain("█".repeat(16)); + expect(last).not.toContain("░"); + }); + + test("prints the header once (no bar) in plain output", () => { + process.env.SENTRY_PLAIN_OUTPUT = "1"; // force plain + const out = fakeOut(true); + const p = makeByteProgress("Applying 3 patch(es)", 1000, out); + p.onProgress(500); + p.onProgress(500); + p.done(); + expect(out.writes).toEqual(["Applying 3 patch(es)\n"]); + }); + + test("prints the header once (no bar) off a TTY", () => { + const out = fakeOut(false); + const p = makeByteProgress("Applying", 1000, out); + p.onProgress(1000); + p.done(); + expect(out.writes).toEqual(["Applying\n"]); + }); + + test("never throws even if the output stream throws (onProgress and done)", () => { + const throwing = { + isTTY: true, + write(): boolean { + throw new Error("boom"); + }, + }; + const p = makeByteProgress("Applying", 100, throwing); + expect(() => { + p.onProgress(50); + p.done(); + }).not.toThrow(); + }); +}); From 9c039ad8de818fa8f0d3cad2e2dcfcb26970894f Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Wed, 22 Jul 2026 21:23:51 +0000 Subject: [PATCH 2/3] fix(upgrade): address bot review findings on the progress bars MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three fixes from Cursor Bugbot + Seer review of #1281: 1. Multi-hop apply bar total (Seer, medium): onBytes fires for the output bytes of EVERY hop — intermediate in-memory hops and the final disk write — so the bar total must be the SUM of all hops' newSize, not just the final binary's. The last-hop-only total made a multi-patch bar hit 100% after hop 1 and freeze. applyChainAndReturn now sums parsePatchHeader(p).newSize across all patches. 2. Progress not cleared on download failure (Bugbot, medium): streamDecompressToFile called progress.done() after the writer.end await in finally, so a rejecting end (ENOSPC/EIO) skipped it, leaving a stale bar merged into the error output. Wrapped the body in an outer try/finally so done() always runs. 3. Stale characters on shorter redraws (Bugbot, low): interactive redraws now pad the new frame with spaces to the previous frame's width, so a shrinking line (e.g. KB→MB boundary) can't leave leftover tail characters. Tests: bspatch onBytes test asserts a 2-hop chain reports sum of both hops' newSize (mutation-verified: dropping onBytes on in-memory hops → RED); progress test asserts a shorter redraw is padded to erase the tail (mutation-verified: removing the padding → RED). --- src/lib/delta-upgrade.ts | 24 +++++++-------- src/lib/progress.ts | 9 ++++-- src/lib/upgrade.ts | 65 +++++++++++++++++++++------------------ test/lib/bspatch.test.ts | 32 +++++++++++++++++++ test/lib/progress.test.ts | 18 +++++++++++ 5 files changed, 104 insertions(+), 44 deletions(-) diff --git a/src/lib/delta-upgrade.ts b/src/lib/delta-upgrade.ts index 7a97cbf61d..29deec2616 100644 --- a/src/lib/delta-upgrade.ts +++ b/src/lib/delta-upgrade.ts @@ -980,26 +980,26 @@ async function applyChainAndReturn( oldBinaryPath: string, destPath: string ): Promise { - // Progress bar for the apply phase. Total is the final binary size (the last - // patch's declared `newSize`), so the number shown is the real output the - // user gets — not the sum of intermediate hop writes. The bar advances per - // byte written across all hops, staying smooth through the chain. Cosmetic - // only: a render failure never aborts the apply, and it self-suppresses off - // an interactive TTY. - let finalSize: number | null = null; + // Progress bar for the apply phase. The `onBytes` callback fires for every + // output byte of every hop — intermediate in-memory hops AND the final disk + // write — so the bar's total must be the SUM of all hops' output sizes (each + // patch's declared `newSize`), not just the final binary size. Using only + // the last patch's size would make a multi-hop bar hit 100% after hop 1 and + // then freeze. Cosmetic only: a render failure never aborts the apply, and + // it self-suppresses off an interactive TTY. + let totalBytes: number | null = 0; try { - const last = chain.patches.at(-1); - if (last) { - finalSize = parsePatchHeader(last.data).newSize; + for (const p of chain.patches) { + totalBytes += parsePatchHeader(p.data).newSize; } } catch { // Header parse is best-effort for the bar; a corrupt header is rejected // properly downstream. Leave the bar indeterminate in that case. - finalSize = null; + totalBytes = null; } const progress = makeByteProgress( `Applying ${chain.patches.length} patch(es)`, - finalSize + totalBytes ); let sha256: string; diff --git a/src/lib/progress.ts b/src/lib/progress.ts index ed27c58a2e..5a1e843b9d 100644 --- a/src/lib/progress.ts +++ b/src/lib/progress.ts @@ -78,8 +78,13 @@ export function makeByteProgress( return; } const l = line(); - lastLen = l.length; - out.write(`\r${l}`); + // Pad with spaces to overwrite any leftover tail from a longer previous + // frame (e.g. when formatBytes shrinks at the KB→MB boundary), then track + // the full printed width so done() clears it completely. + const padded = + l.length < lastLen ? l + " ".repeat(lastLen - l.length) : l; + lastLen = padded.length; + out.write(`\r${padded}`); } catch { // ignore — progress is cosmetic } diff --git a/src/lib/upgrade.ts b/src/lib/upgrade.ts index ab445dcd6a..3b9dc65180 100644 --- a/src/lib/upgrade.ts +++ b/src/lib/upgrade.ts @@ -590,41 +590,46 @@ async function streamDecompressToFile( writeError ??= err; }); try { - for await (const chunk of stream) { - if (writeError) { - break; + try { + for await (const chunk of stream) { + if (writeError) { + break; + } + const ok = writer.write(chunk); + progress.onProgress(chunk.byteLength); + if (!(ok || writeError)) { + // Race drain against error — an I/O failure (ENOSPC) while the + // buffer is full would never emit 'drain', causing a hang. + // Clean up the unused listener to avoid MaxListenersExceededWarning. + await new Promise((resolve) => { + const onDrain = (): void => { + writer.removeListener("error", onError); + resolve(); + }; + const onError = (): void => { + writer.removeListener("drain", onDrain); + resolve(); + }; + writer.once("drain", onDrain); + writer.once("error", onError); + }); + } } - const ok = writer.write(chunk); - progress.onProgress(chunk.byteLength); - if (!(ok || writeError)) { - // Race drain against error — an I/O failure (ENOSPC) while the - // buffer is full would never emit 'drain', causing a hang. - // Clean up the unused listener to avoid MaxListenersExceededWarning. - await new Promise((resolve) => { - const onDrain = (): void => { - writer.removeListener("error", onError); + } finally { + await new Promise((resolve, reject) => { + writer.end((err?: Error | null) => { + const finalErr = err ?? writeError; + if (finalErr) { + reject(finalErr); + } else { resolve(); - }; - const onError = (): void => { - writer.removeListener("drain", onDrain); - resolve(); - }; - writer.once("drain", onDrain); - writer.once("error", onError); + } }); - } + }); } } finally { - await new Promise((resolve, reject) => { - writer.end((err?: Error | null) => { - const finalErr = err ?? writeError; - if (finalErr) { - reject(finalErr); - } else { - resolve(); - } - }); - }); + // Always clear the progress line, even if writer.end rejected (ENOSPC/EIO), + // so a stale bar never merges with the following error output. progress.done(); } } diff --git a/test/lib/bspatch.test.ts b/test/lib/bspatch.test.ts index 1d10bbb0c4..6e4cd59330 100644 --- a/test/lib/bspatch.test.ts +++ b/test/lib/bspatch.test.ts @@ -287,6 +287,38 @@ describe("applyPatchChainInMemory", () => { } }); + test("onBytes reports every hop's output — total = sum of all newSizes", async () => { + // The progress callback fires for the output bytes of EVERY hop (the + // in-memory intermediate AND the final disk write), so a multi-hop total + // must be the sum of all hops' newSize, not just the final binary's. + // (Guards the delta-upgrade progress-bar total; a last-hop-only total + // would freeze the bar at 100% after hop 1.) + const oldBytes = makeBytes(1, 4096); + const midBytes = makeBytes(2, 4096); + const newBytes = makeBytes(3, 4096); + const p1 = buildDiffOnlyPatch(oldBytes, midBytes); + const p2 = buildDiffOnlyPatch(midBytes, newBytes); + + const oldPath = tempFile("old-ob.bin"); + const destPath = tempFile("out-ob.bin"); + await writeFile(oldPath, oldBytes); + + try { + let reported = 0; + await applyPatchChainInMemory(oldPath, [p1, p2], destPath, (n) => { + reported += n; + }); + // Two hops, each emitting 4096 output bytes. + expect(reported).toBe(midBytes.length + newBytes.length); + } finally { + for (const p of [oldPath, destPath]) { + if (existsSync(p)) { + unlinkSync(p); + } + } + } + }); + test("single-element chain matches the on-disk patcher on a real fixture", async () => { // Exercises the fd-backed reader against a real zig-bsdiff patch whose // control entries include diff, extra, and seek operations. diff --git a/test/lib/progress.test.ts b/test/lib/progress.test.ts index 383bc072ae..b9306c9082 100644 --- a/test/lib/progress.test.ts +++ b/test/lib/progress.test.ts @@ -101,6 +101,24 @@ describe("makeByteProgress", () => { expect(last).not.toContain("░"); }); + test("overwrites the previous frame's tail when a redraw is shorter", () => { + // Indeterminate counter: a large byte count renders a long line, then a + // hypothetically shorter one would leave stale chars without padding. + // We can't easily shrink formatBytes mid-run, so assert the padding logic + // directly: after a long frame then a short one, the short frame is padded + // to the long frame's width so no stale tail remains. + const out = fakeOut(true); + const p = makeByteProgress("D", null, out); + p.onProgress(1024 * 1024 * 100); // "D 100 MB" — long + const longFrame = out.writes.at(-1) ?? ""; + p.onProgress(-(1024 * 1024 * 100 - 5)); // net 5 bytes → "D 5 B" — shorter + const shortFrame = out.writes.at(-1) ?? ""; + // The short frame (minus the leading \r) must be at least as wide as the + // long frame's content, i.e. padded to erase the tail. + expect(shortFrame.length).toBeGreaterThanOrEqual(longFrame.length); + expect(shortFrame).toContain("5 B"); + }); + test("prints the header once (no bar) in plain output", () => { process.env.SENTRY_PLAIN_OUTPUT = "1"; // force plain const out = fakeOut(true); From 903a83a8d653a7dda65aa3f57d49069acace598c Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Wed, 22 Jul 2026 21:52:24 +0000 Subject: [PATCH 3/3] fix(upgrade): feed progress into the spinner; fix error masking MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses two review findings on the progress bars: 1. Progress bars clash with the upgrade spinner (Cursor, medium): the main `sentry upgrade` path runs under withProgress, which animates a spinner on the same terminal line. A second in-place byte bar on stderr fought with it, making both unreadable. Reworked so progress feeds the spinner's setMessage callback instead of drawing its own bar — one animation, no clash. The setMessage is threaded from withProgress through executeUpgrade -> downloadBinaryToTemp -> {tryDeltaUpgrade -> attemptDeltaUpgrade -> resolve*Delta -> applyChainAndReturn, downloadFullBinary -> download*ToPath -> streamDecompressToFile}. When absent (JSON mode / non-TTY) it's a no-op. 2. writer.end() error masks the original stream error (Seer, medium): in streamDecompressToFile a rejection from writer.end() in the finally could overwrite the root-cause streaming error. Restructured so the original stream error is captured and rethrown preferentially; an end() failure that follows it is demoted to a debug log. progress.ts is now a throttled message formatter (determinate bar with % or an indeterminate byte counter) rather than a stream writer. Cosmetic-only: a formatting/callback failure never propagates. Tests: progress.test.ts rewritten for the setMessage API (7) — determinate/ indeterminate formatting, accumulation + clamp, throttling, final done() emit, no-op without setMessage, never-throws. Mutation-verified: removing the emit try/catch → never-throws RED; removing the throttle → throttle RED. --- src/commands/cli/upgrade.ts | 6 +- src/lib/delta-upgrade.ts | 48 ++++++--- src/lib/progress.ts | 101 +++++++++--------- src/lib/upgrade.ts | 138 ++++++++++++++---------- test/lib/progress.test.ts | 204 +++++++++++++++--------------------- 5 files changed, 256 insertions(+), 241 deletions(-) diff --git a/src/commands/cli/upgrade.ts b/src/commands/cli/upgrade.ts index 9ccac9801c..2b3fa1afb2 100644 --- a/src/commands/cli/upgrade.ts +++ b/src/commands/cli/upgrade.ts @@ -558,7 +558,8 @@ async function executeStandardUpgrade(opts: { channel === "nightly" && !versionArg ? NIGHTLY_TAG : undefined; const downloadResult = await withProgress( { message: `Downloading ${target}...`, json }, - async () => executeUpgrade(method, target, downloadTag, offline) + async (setMessage) => + executeUpgrade(method, target, downloadTag, offline, setMessage) ); if (downloadResult?.patchBytes) { @@ -629,7 +630,8 @@ async function migrateToStandaloneForNightly( const downloadTag = versionArg ? undefined : NIGHTLY_TAG; const downloadResult = await withProgress( { message: `Downloading ${target}...`, json }, - async () => executeUpgrade("curl", target, downloadTag) + async (setMessage) => + executeUpgrade("curl", target, downloadTag, undefined, setMessage) ); if (downloadResult?.patchBytes) { diff --git a/src/lib/delta-upgrade.ts b/src/lib/delta-upgrade.ts index 29deec2616..6225bcdb58 100644 --- a/src/lib/delta-upgrade.ts +++ b/src/lib/delta-upgrade.ts @@ -40,7 +40,7 @@ import { } from "./ghcr.js"; import { logger } from "./logger.js"; import { loadCachedChain, savePatchesToCache } from "./patch-cache.js"; -import { makeByteProgress } from "./progress.js"; +import { makeByteProgress, type SetMessage } from "./progress.js"; import { withTracing, withTracingSpan } from "./telemetry.js"; /** Scoped logger for delta upgrade operations */ @@ -836,11 +836,13 @@ export async function resolveNightlyChain(opts: { * @param destPath - Path to write the patched binary * @returns Delta result with SHA-256 and size info, or null if delta is unavailable */ +// biome-ignore lint/nursery/useMaxParams: established 4-param shape; setMessage is a defaulted spinner-progress extension export function attemptDeltaUpgrade( targetVersion: string, oldBinaryPath: string, destPath: string, - offline?: boolean + offline?: boolean, + setMessage?: SetMessage ): Promise { if (!canAttemptDelta(targetVersion)) { return Promise.resolve(null); @@ -866,13 +868,15 @@ export function attemptDeltaUpgrade( targetVersion, oldBinaryPath, destPath, - offline + offline, + setMessage ) : await resolveStableDelta( targetVersion, oldBinaryPath, destPath, - offline + offline, + setMessage ); if (result) { @@ -978,15 +982,16 @@ async function tryLoadCachedChain( async function applyChainAndReturn( chain: PatchChain, oldBinaryPath: string, - destPath: string + destPath: string, + setMessage?: SetMessage ): Promise { - // Progress bar for the apply phase. The `onBytes` callback fires for every + // Progress for the apply phase. The `onBytes` callback fires for every // output byte of every hop — intermediate in-memory hops AND the final disk - // write — so the bar's total must be the SUM of all hops' output sizes (each + // write — so the total must be the SUM of all hops' output sizes (each // patch's declared `newSize`), not just the final binary size. Using only // the last patch's size would make a multi-hop bar hit 100% after hop 1 and - // then freeze. Cosmetic only: a render failure never aborts the apply, and - // it self-suppresses off an interactive TTY. + // then freeze. Feeds the surrounding spinner via setMessage — cosmetic, a + // render failure never aborts the apply. let totalBytes: number | null = 0; try { for (const p of chain.patches) { @@ -999,7 +1004,8 @@ async function applyChainAndReturn( } const progress = makeByteProgress( `Applying ${chain.patches.length} patch(es)`, - totalBytes + totalBytes, + setMessage ); let sha256: string; @@ -1029,6 +1035,8 @@ type ResolveAndApplyOpts = { channel: string; /** When true, skip the network fallback — only use cached patches */ offline?: boolean; + /** Spinner message setter for apply-phase progress (from withProgress) */ + setMessage?: SetMessage; }; /** @@ -1048,6 +1056,7 @@ async function resolveAndApplyDelta( resolveFromNetwork, channel, offline, + setMessage, } = opts; // Check patch cache first — enables fully offline upgrades const cached = await tryLoadCachedChain(CLI_VERSION, targetVersion); @@ -1056,7 +1065,12 @@ async function resolveAndApplyDelta( log.debug( `Using cached patches: ${cached.patches.length} patch(es), ${formatBytes(cached.totalSize)} total` ); - return await applyChainAndReturn(cached, oldBinaryPath, destPath); + return await applyChainAndReturn( + cached, + oldBinaryPath, + destPath, + setMessage + ); } // In offline mode, skip the network resolution entirely — if the cache @@ -1078,7 +1092,7 @@ async function resolveAndApplyDelta( return null; } - return await applyChainAndReturn(chain, oldBinaryPath, destPath); + return await applyChainAndReturn(chain, oldBinaryPath, destPath, setMessage); } /** @@ -1089,11 +1103,13 @@ async function resolveAndApplyDelta( * * @returns Delta result with SHA-256 and size info, or null if delta is unavailable */ +// biome-ignore lint/nursery/useMaxParams: established 4-param shape; setMessage is a defaulted spinner-progress extension export function resolveStableDelta( targetVersion: string, oldBinaryPath: string, destPath: string, - offline?: boolean + offline?: boolean, + setMessage?: SetMessage ): Promise { return resolveAndApplyDelta({ targetVersion, @@ -1105,6 +1121,7 @@ export function resolveStableDelta( ), channel: "stable", offline, + setMessage, }); } @@ -1116,11 +1133,13 @@ export function resolveStableDelta( * * @returns Delta result with SHA-256 and size info, or null if delta is unavailable */ +// biome-ignore lint/nursery/useMaxParams: established 4-param shape; setMessage is a defaulted spinner-progress extension export function resolveNightlyDelta( targetVersion: string, oldBinaryPath: string, destPath: string, - offline?: boolean + offline?: boolean, + setMessage?: SetMessage ): Promise { return resolveAndApplyDelta({ targetVersion, @@ -1129,6 +1148,7 @@ export function resolveNightlyDelta( resolveFromNetwork: () => resolveNightlyChainWithContext(targetVersion), channel: "nightly", offline, + setMessage, }); } diff --git a/src/lib/progress.ts b/src/lib/progress.ts index 5a1e843b9d..e7000673b7 100644 --- a/src/lib/progress.ts +++ b/src/lib/progress.ts @@ -1,35 +1,36 @@ /** - * Byte-driven progress bar for long-running upgrade phases (patch apply, + * Byte-driven progress reporting for long-running upgrade phases (patch apply, * full-binary download). * - * Design contract: - * - Renders only when output is interactive (respects `isPlainOutput()`, so - * `NO_COLOR`, piped stdout, and CI all suppress the bar). In plain mode it - * prints the label once. - * - Cosmetic ONLY — rendering must never throw or abort the underlying work. - * - Determinate when a byte `total` is supplied; an indeterminate byte counter - * otherwise (the decompressed download size isn't known ahead of time). + * sentry upgrade already runs under `withProgress`, which animates a spinner + * and passes down a `setMessage(text)` callback. To avoid two competing + * in-place redraws fighting over the same terminal line, this helper does NOT + * draw its own bar — it formats a compact progress string and pushes it into + * that `setMessage` callback, so the byte counter rides on the existing spinner. * - * One line, redrawn in place via carriage return; `done()` clears the line so - * the next message prints cleanly. + * Design contract: + * - Cosmetic ONLY — a formatting/callback failure must never abort the work. + * - Determinate ("152 MB / 310 MB [====> ] 49%") when a byte `total` is given; + * an indeterminate byte counter ("38 MB") otherwise (the decompressed + * download size isn't known ahead of time). + * - Updates are throttled so a fast byte stream doesn't spam the spinner. */ import { formatBytes } from "./formatters/numbers.js"; -import { isPlainOutput } from "./formatters/plain-detect.js"; -export type ByteProgressOut = { - isTTY?: boolean; - write: (s: string) => unknown; -}; +/** Callback that sets the surrounding spinner's message text. */ +export type SetMessage = (message: string) => void; export type ByteProgress = { /** Report `bytes` additional bytes processed since the last call. */ onProgress: (bytes: number) => void; - /** Clear the progress line (call before printing the next message). */ + /** Emit a final message reflecting the total processed (best-effort). */ done: () => void; }; const BAR_WIDTH = 16; +/** Minimum gap between spinner message updates. */ +const THROTTLE_MS = 100; function renderBar(frac: number, width = BAR_WIDTH): string { const filled = Math.max(0, Math.min(width, Math.round(width * frac))); @@ -37,68 +38,62 @@ function renderBar(frac: number, width = BAR_WIDTH): string { } /** - * Create a byte-progress bar. + * Create a byte-progress reporter that feeds a spinner `setMessage` callback. * - * @param label - Short label shown before the bar (e.g. "Applying 3 patches"). + * @param label - Short label prefix (e.g. "Applying 3 patch(es)"). * @param totalBytes - Expected total bytes; `null` renders an indeterminate * byte counter instead of a bar. - * @param out - Output stream (defaults to stderr, the CLI's progress channel). + * @param setMessage - Spinner message setter (from `withProgress`). When + * undefined (JSON mode / non-TTY / no surrounding spinner), this is a no-op + * so nothing is drawn. + * @param nowMs - Injectable clock for tests. */ export function makeByteProgress( label: string, totalBytes: number | null, - out: ByteProgressOut = process.stderr + setMessage?: SetMessage, + nowMs: () => number = Date.now ): ByteProgress { - // Interactive only: a real TTY AND not forced into plain output. - const interactive = !!out.isTTY && !isPlainOutput(); let written = 0; - let lastLen = 0; - let headerShown = false; + let lastEmit = 0; - const line = (): string => { + const format = (): string => { if (totalBytes === null || totalBytes <= 0) { - return `${label} ${formatBytes(written)}`; + return `${label} ${formatBytes(written)}`; } const frac = Math.min(written / totalBytes, 1); + const pct = Math.round(frac * 100); return ( `${label} [${renderBar(frac)}] ` + - `${formatBytes(written)} / ${formatBytes(totalBytes)}` + `${formatBytes(written)} / ${formatBytes(totalBytes)} (${pct}%)` ); }; - const onProgress = (bytes: number): void => { - // Cosmetic only — a rendering failure must never abort the operation. + const emit = (): void => { + // Cosmetic only — a formatting or callback failure must never propagate. try { - written += bytes; - if (!interactive) { - if (!headerShown) { - out.write(`${label}\n`); - headerShown = true; - } - return; - } - const l = line(); - // Pad with spaces to overwrite any leftover tail from a longer previous - // frame (e.g. when formatBytes shrinks at the KB→MB boundary), then track - // the full printed width so done() clears it completely. - const padded = - l.length < lastLen ? l + " ".repeat(lastLen - l.length) : l; - lastLen = padded.length; - out.write(`\r${padded}`); + setMessage?.(format()); } catch { // ignore — progress is cosmetic } }; - const done = (): void => { - // Cosmetic only — must never throw, matching onProgress's contract. - try { - if (interactive && lastLen > 0) { - out.write(`\r${" ".repeat(lastLen)}\r`); - } - } catch { - // ignore — progress is cosmetic + const onProgress = (bytes: number): void => { + written += bytes; + if (!setMessage) { + return; + } + const now = nowMs(); + if (now - lastEmit < THROTTLE_MS) { + return; } + lastEmit = now; + emit(); + }; + + // Emit a final, un-throttled message so the last state is always shown. + const done = (): void => { + emit(); }; return { onProgress, done }; diff --git a/src/lib/upgrade.ts b/src/lib/upgrade.ts index 3b9dc65180..a56bb98a6a 100644 --- a/src/lib/upgrade.ts +++ b/src/lib/upgrade.ts @@ -50,7 +50,7 @@ import { } from "./ghcr.js"; import { logger } from "./logger.js"; import { clearPatchCache } from "./patch-cache.js"; -import { makeByteProgress } from "./progress.js"; +import { makeByteProgress, type SetMessage } from "./progress.js"; /** Scoped logger for upgrade operations */ const log = logger.withTag("upgrade"); @@ -575,63 +575,82 @@ export type DownloadResult = { */ async function streamDecompressToFile( body: ReadableStream, - destPath: string + destPath: string, + setMessage?: SetMessage ): Promise { const stream = body.pipeThrough(new DecompressionStream("gzip")); const writer = createWriteStream(destPath); // Indeterminate byte counter: the decompressed size isn't known ahead of // time (Content-Length covers only the compressed stream), so we show a live - // byte count rather than a misleading fraction. Cosmetic — never aborts. - const progress = makeByteProgress("Downloading", null); + // byte count rather than a misleading fraction. Feeds the surrounding + // spinner via setMessage — cosmetic, never aborts. + const progress = makeByteProgress("Downloading", null, setMessage); // Capture write errors early — without a listener, Node crashes with // ERR_UNHANDLED_ERROR if a write fails (ENOSPC, EIO, etc.) during the loop. let writeError: Error | undefined; writer.on("error", (err) => { writeError ??= err; }); + + // Track the original streaming error so a later writer.end() rejection can't + // mask it: an exception thrown from a finally overwrites a pending try + // exception. We rethrow the ORIGINAL error preferentially. + let streamError: unknown; try { - try { - for await (const chunk of stream) { - if (writeError) { - break; - } - const ok = writer.write(chunk); - progress.onProgress(chunk.byteLength); - if (!(ok || writeError)) { - // Race drain against error — an I/O failure (ENOSPC) while the - // buffer is full would never emit 'drain', causing a hang. - // Clean up the unused listener to avoid MaxListenersExceededWarning. - await new Promise((resolve) => { - const onDrain = (): void => { - writer.removeListener("error", onError); - resolve(); - }; - const onError = (): void => { - writer.removeListener("drain", onDrain); - resolve(); - }; - writer.once("drain", onDrain); - writer.once("error", onError); - }); - } + for await (const chunk of stream) { + if (writeError) { + break; } - } finally { - await new Promise((resolve, reject) => { - writer.end((err?: Error | null) => { - const finalErr = err ?? writeError; - if (finalErr) { - reject(finalErr); - } else { + const ok = writer.write(chunk); + progress.onProgress(chunk.byteLength); + if (!(ok || writeError)) { + // Race drain against error — an I/O failure (ENOSPC) while the + // buffer is full would never emit 'drain', causing a hang. + // Clean up the unused listener to avoid MaxListenersExceededWarning. + await new Promise((resolve) => { + const onDrain = (): void => { + writer.removeListener("error", onError); resolve(); - } + }; + const onError = (): void => { + writer.removeListener("drain", onDrain); + resolve(); + }; + writer.once("drain", onDrain); + writer.once("error", onError); }); - }); + } } + } catch (err) { + streamError = err; } finally { - // Always clear the progress line, even if writer.end rejected (ENOSPC/EIO), - // so a stale bar never merges with the following error output. progress.done(); } + + // Always flush/close the writer. If the stream already failed, surface THAT + // error (the root cause) and demote any end() rejection to a debug log so it + // can't mask the original. + try { + await new Promise((resolve, reject) => { + writer.end((err?: Error | null) => { + const finalErr = err ?? writeError; + if (finalErr) { + reject(finalErr); + } else { + resolve(); + } + }); + }); + } catch (endErr) { + if (streamError === undefined) { + throw endErr; + } + log.debug(`writer.end failed after a stream error: ${String(endErr)}`); + } + + if (streamError !== undefined) { + throw streamError; + } } /** @@ -663,7 +682,8 @@ function getNightlyGzFilename(): string { */ async function downloadNightlyToPath( destPath: string, - version?: string + version?: string, + setMessage?: SetMessage ): Promise { const token = await getAnonymousToken(); const manifest = version @@ -679,7 +699,7 @@ async function downloadNightlyToPath( "GHCR blob response had no body" ); } - await streamDecompressToFile(response.body, destPath); + await streamDecompressToFile(response.body, destPath, setMessage); } /** @@ -695,7 +715,8 @@ async function downloadNightlyToPath( */ async function downloadStableToPath( version: string, - destPath: string + destPath: string, + setMessage?: SetMessage ): Promise { const url = getBinaryDownloadUrl(version); const headers = getGitHubHeaders(); @@ -708,7 +729,7 @@ async function downloadStableToPath( "GitHub" ); if (gzResponse.ok && gzResponse.body) { - await streamDecompressToFile(gzResponse.body, destPath); + await streamDecompressToFile(gzResponse.body, destPath, setMessage); return; } } catch { @@ -835,7 +856,8 @@ async function waitForBinaryVisible(path: string): Promise { export async function downloadBinaryToTemp( version: string, downloadTag?: string, - offline?: OfflineMode + offline?: OfflineMode, + setMessage?: SetMessage ): Promise { const { tempPath, lockPath } = getCurlInstallPaths(); @@ -851,7 +873,12 @@ export async function downloadBinaryToTemp( // Try delta upgrade first — downloads tiny patches instead of full binary. // Falls back to full download on any failure (missing patches, hash mismatch, etc.) - const deltaResult = await tryDeltaUpgrade(version, tempPath, !!offline); + const deltaResult = await tryDeltaUpgrade( + version, + tempPath, + !!offline, + setMessage + ); let patchBytes: number | undefined; if (deltaResult) { patchBytes = deltaResult.patchBytes; @@ -866,7 +893,7 @@ export async function downloadBinaryToTemp( ); } else { log.debug("Downloading full binary"); - await downloadFullBinary(version, downloadTag, tempPath); + await downloadFullBinary(version, downloadTag, tempPath, setMessage); } // Verify the download produced a real, non-empty file before the caller @@ -910,13 +937,15 @@ export async function downloadBinaryToTemp( async function tryDeltaUpgrade( version: string, destPath: string, - offline?: boolean + offline?: boolean, + setMessage?: SetMessage ): Promise { return await attemptDeltaUpgrade( version, process.execPath, destPath, - offline + offline, + setMessage ); } @@ -930,12 +959,13 @@ async function tryDeltaUpgrade( async function downloadFullBinary( version: string, downloadTag: string | undefined, - destPath: string + destPath: string, + setMessage?: SetMessage ): Promise { if (isNightlyVersion(version)) { - await downloadNightlyToPath(destPath, version); + await downloadNightlyToPath(destPath, version, setMessage); } else { - await downloadStableToPath(downloadTag ?? version, destPath); + await downloadStableToPath(downloadTag ?? version, destPath, setMessage); } } @@ -1040,15 +1070,17 @@ function executeUpgradePackageManager( * @returns Download result with paths (curl), or null (package manager) * @throws {UpgradeError} When method is unknown or installation fails */ +// biome-ignore lint/nursery/useMaxParams: established 4-param shape; setMessage is a defaulted spinner-progress extension export async function executeUpgrade( method: InstallationMethod, version: string, downloadTag?: string, - offline?: OfflineMode + offline?: OfflineMode, + setMessage?: SetMessage ): Promise { switch (method) { case "curl": - return downloadBinaryToTemp(version, downloadTag, offline); + return downloadBinaryToTemp(version, downloadTag, offline, setMessage); case "brew": await executeUpgradeHomebrew(); return null; diff --git a/test/lib/progress.test.ts b/test/lib/progress.test.ts index b9306c9082..901cc8ee8d 100644 --- a/test/lib/progress.test.ts +++ b/test/lib/progress.test.ts @@ -1,152 +1,118 @@ /** - * Unit tests for the byte-driven upgrade progress bar. + * Unit tests for the byte-driven upgrade progress reporter. * - * The bar is cosmetic-only and must never abort the operation it decorates. - * Coverage: determinate fraction rendering, indeterminate byte counter, - * plain-output (non-interactive) header-only behavior, byte accumulation, - * full-bar clamping, and the never-throws contract for both onProgress and - * done(). + * The reporter is cosmetic-only and must never abort the operation it + * decorates. It feeds a `setMessage` callback (the surrounding withProgress + * spinner) rather than drawing its own bar, so there's no second in-place + * redraw competing with the spinner. * - * Rendering is gated on `isPlainOutput()`, so we force rich output via - * SENTRY_PLAIN_OUTPUT=0 (see plain-detect.ts precedence) and drive a fake - * TTY stream. + * Coverage: determinate vs indeterminate formatting, byte accumulation, + * full-bar clamping, update throttling, a final un-throttled done() emit, the + * no-op path when no setMessage is provided, and the never-throws contract. */ -import { afterEach, beforeEach, describe, expect, test } from "vitest"; +import { describe, expect, test, vi } from "vitest"; import { makeByteProgress } from "../../src/lib/progress.js"; -type FakeOut = { - isTTY: boolean; - writes: string[]; - write: (s: string) => boolean; -}; - -function fakeOut(isTTY: boolean): FakeOut { - const writes: string[] = []; - return { - isTTY, - writes, - write(s: string) { - writes.push(s); - return true; - }, - }; -} - describe("makeByteProgress", () => { - const saved: Record = {}; - - beforeEach(() => { - // Force rich output so the interactive path renders regardless of CI env - // (NO_COLOR=1 etc.). SENTRY_PLAIN_OUTPUT has highest precedence. - for (const key of ["SENTRY_PLAIN_OUTPUT", "NO_COLOR", "FORCE_COLOR"]) { - saved[key] = process.env[key]; - delete process.env[key]; - } - process.env.SENTRY_PLAIN_OUTPUT = "0"; // force rich - }); - - afterEach(() => { - for (const key of ["SENTRY_PLAIN_OUTPUT", "NO_COLOR", "FORCE_COLOR"]) { - const v = saved[key]; - if (v === undefined) { - delete process.env[key]; - } else { - process.env[key] = v; - } - } - }); - - test("renders a determinate bar advancing with reported bytes", () => { - const out = fakeOut(true); - const p = makeByteProgress("Applying 3 patch(es)", 1000, out); - p.onProgress(500); - p.onProgress(500); - p.done(); - - const last = out.writes.at(-2); // last real line before the clear + test("formats a determinate bar with size and percent", () => { + const msgs: string[] = []; + let now = 0; + const p = makeByteProgress( + "Applying 3 patch(es)", + 1000, + (m) => msgs.push(m), + () => now + ); + p.onProgress(500); // first call: now=0, lastEmit=0 → throttled (0-0 < 100) + now = 200; + p.onProgress(500); // now past throttle → emits at 1000/1000 + const last = msgs.at(-1) ?? ""; expect(last).toContain("Applying 3 patch(es)"); - expect(last).toContain("█".repeat(16)); // 1000/1000 → full bar + expect(last).toContain("1000 B / 1000 B"); + expect(last).toContain("100%"); + expect(last).toContain("█".repeat(16)); }); - test("renders an indeterminate byte counter when total is null", () => { - const out = fakeOut(true); - const p = makeByteProgress("Downloading", null, out); + test("formats an indeterminate byte counter when total is null", () => { + const msgs: string[] = []; + let now = 0; + const p = makeByteProgress( + "Downloading", + null, + (m) => msgs.push(m), + () => now + ); + now = 200; p.onProgress(2048); - p.done(); - - const last = out.writes.at(-2); + const last = msgs.at(-1) ?? ""; expect(last).toContain("Downloading"); + expect(last).toContain("2.0 KB"); expect(last).not.toContain("░"); // no bar in indeterminate mode }); - test("accumulates bytes across multiple onProgress calls", () => { - const out = fakeOut(true); - const p = makeByteProgress("Applying", 100, out); - p.onProgress(10); - p.onProgress(40); - p.onProgress(50); // total 100 → full - p.done(); - expect(out.writes.at(-2)).toContain("█".repeat(16)); - }); - - test("clamps the bar at full even if bytes exceed the total", () => { - const out = fakeOut(true); - const p = makeByteProgress("Applying", 100, out); - p.onProgress(5000); - p.done(); - const last = out.writes.at(-2); + test("accumulates bytes across calls and clamps the bar at full", () => { + const msgs: string[] = []; + let now = 0; + const p = makeByteProgress( + "Applying", + 100, + (m) => msgs.push(m), + () => now + ); + p.onProgress(50); + now = 500; + p.onProgress(9000); // way over total → clamp to 100% + const last = msgs.at(-1) ?? ""; + expect(last).toContain("100%"); expect(last).toContain("█".repeat(16)); expect(last).not.toContain("░"); }); - test("overwrites the previous frame's tail when a redraw is shorter", () => { - // Indeterminate counter: a large byte count renders a long line, then a - // hypothetically shorter one would leave stale chars without padding. - // We can't easily shrink formatBytes mid-run, so assert the padding logic - // directly: after a long frame then a short one, the short frame is padded - // to the long frame's width so no stale tail remains. - const out = fakeOut(true); - const p = makeByteProgress("D", null, out); - p.onProgress(1024 * 1024 * 100); // "D 100 MB" — long - const longFrame = out.writes.at(-1) ?? ""; - p.onProgress(-(1024 * 1024 * 100 - 5)); // net 5 bytes → "D 5 B" — shorter - const shortFrame = out.writes.at(-1) ?? ""; - // The short frame (minus the leading \r) must be at least as wide as the - // long frame's content, i.e. padded to erase the tail. - expect(shortFrame.length).toBeGreaterThanOrEqual(longFrame.length); - expect(shortFrame).toContain("5 B"); + test("throttles updates so a fast byte stream doesn't spam the spinner", () => { + const set = vi.fn(); + const now = 1000; + const p = makeByteProgress("Applying", 1000, set, () => now); + // Many calls within the same throttle window → at most one emit. + for (let i = 0; i < 50; i++) { + p.onProgress(10); + } + expect(set.mock.calls.length).toBeLessThanOrEqual(1); }); - test("prints the header once (no bar) in plain output", () => { - process.env.SENTRY_PLAIN_OUTPUT = "1"; // force plain - const out = fakeOut(true); - const p = makeByteProgress("Applying 3 patch(es)", 1000, out); - p.onProgress(500); - p.onProgress(500); - p.done(); - expect(out.writes).toEqual(["Applying 3 patch(es)\n"]); + test("done() emits a final, un-throttled message reflecting the total", () => { + const set = vi.fn(); + const now = 0; + const p = makeByteProgress("Applying", 100, set, () => now); + p.onProgress(100); // throttled (now-0 < 100), no emit yet + set.mockClear(); + p.done(); // must emit regardless of throttle + expect(set).toHaveBeenCalledTimes(1); + expect(set.mock.calls[0]?.[0]).toContain("100%"); }); - test("prints the header once (no bar) off a TTY", () => { - const out = fakeOut(false); - const p = makeByteProgress("Applying", 1000, out); - p.onProgress(1000); - p.done(); - expect(out.writes).toEqual(["Applying\n"]); + test("is a no-op when no setMessage is provided (JSON/non-TTY)", () => { + // Nothing to assert beyond: it must not throw and must still track bytes + // so a later done() with a setMessage-less reporter is harmless. + const p = makeByteProgress("Applying", 100); + expect(() => { + p.onProgress(50); + p.done(); + }).not.toThrow(); }); - test("never throws even if the output stream throws (onProgress and done)", () => { - const throwing = { - isTTY: true, - write(): boolean { + test("never throws even if setMessage throws", () => { + const p = makeByteProgress( + "Applying", + 100, + () => { throw new Error("boom"); }, - }; - const p = makeByteProgress("Applying", 100, throwing); + () => 1000 + ); expect(() => { - p.onProgress(50); + p.onProgress(100); p.done(); }).not.toThrow(); });