Skip to content
This repository was archived by the owner on Oct 23, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/commands/cli/upgrade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down
15 changes: 10 additions & 5 deletions src/lib/bspatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -588,7 +588,8 @@ async function transformPatch(
async function applyReaderToFile(
oldReader: OldReader,
patchData: Uint8Array,
destPath: string
destPath: string,
onBytes?: (bytes: number) => void
): Promise<string> {
const writer = createWriteStream(destPath);
const hasher = createHash("sha256");
Expand All @@ -610,6 +611,7 @@ async function applyReaderToFile(
}
writer.write(chunk);
hasher.update(chunk);
onBytes?.(chunk.byteLength);
});
} finally {
await new Promise<void>((resolve, reject) => {
Expand Down Expand Up @@ -642,7 +644,8 @@ async function applyReaderToFile(
*/
async function applyReaderToMemory(
oldReader: OldReader,
patchData: Uint8Array
patchData: Uint8Array,
onBytes?: (bytes: number) => void
): Promise<Uint8Array> {
// 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.
Expand All @@ -653,6 +656,7 @@ async function applyReaderToMemory(
await transformPatch(oldReader, patchData, (chunk) => {
output.set(chunk, offset);
offset += chunk.byteLength;
onBytes?.(chunk.byteLength);
});

return output;
Expand Down Expand Up @@ -701,7 +705,8 @@ export function applyPatchToMemory(
export async function applyPatchChainInMemory(
oldPath: string,
patches: Uint8Array[],
destPath: string
destPath: string,
onBytes?: (bytes: number) => void
): Promise<string> {
if (patches.length === 0) {
throw new Error("Cannot apply an empty patch chain");
Expand All @@ -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);
}
Expand All @@ -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();
}
Expand Down
79 changes: 64 additions & 15 deletions src/lib/delta-upgrade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -40,6 +40,7 @@ import {
} from "./ghcr.js";
import { logger } from "./logger.js";
import { loadCachedChain, savePatchesToCache } from "./patch-cache.js";
import { makeByteProgress, type SetMessage } from "./progress.js";
import { withTracing, withTracingSpan } from "./telemetry.js";

/** Scoped logger for delta upgrade operations */
Expand Down Expand Up @@ -835,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<DeltaResult | null> {
if (!canAttemptDelta(targetVersion)) {
return Promise.resolve(null);
Expand All @@ -865,13 +868,15 @@ export function attemptDeltaUpgrade(
targetVersion,
oldBinaryPath,
destPath,
offline
offline,
setMessage
)
: await resolveStableDelta(
targetVersion,
oldBinaryPath,
destPath,
offline
offline,
setMessage
);

if (result) {
Expand Down Expand Up @@ -977,13 +982,41 @@ async function tryLoadCachedChain(
async function applyChainAndReturn(
chain: PatchChain,
oldBinaryPath: string,
destPath: string
destPath: string,
setMessage?: SetMessage
): Promise<DeltaResult> {
const sha256 = await withTracing(
"apply-patch-chain",
"upgrade.delta.apply",
() => applyPatchChain(chain, oldBinaryPath, destPath)
// 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 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. 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) {
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.
totalBytes = null;
}
const progress = makeByteProgress(
`Applying ${chain.patches.length} patch(es)`,
totalBytes,
setMessage
);
Comment thread
sentry[bot] marked this conversation as resolved.
Resolved

let sha256: string;
try {
sha256 = await withTracing("apply-patch-chain", "upgrade.delta.apply", () =>
applyPatchChain(chain, oldBinaryPath, destPath, progress.onProgress)
);
} finally {
progress.done();
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

return {
sha256,
patchBytes: chain.totalSize,
Expand All @@ -1002,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;
};

/**
Expand All @@ -1021,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);
Expand All @@ -1029,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
Expand All @@ -1051,7 +1092,7 @@ async function resolveAndApplyDelta(
return null;
}

return await applyChainAndReturn(chain, oldBinaryPath, destPath);
return await applyChainAndReturn(chain, oldBinaryPath, destPath, setMessage);
}

/**
Expand All @@ -1062,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<DeltaResult | null> {
return resolveAndApplyDelta({
targetVersion,
Expand All @@ -1078,6 +1121,7 @@ export function resolveStableDelta(
),
channel: "stable",
offline,
setMessage,
});
}

Expand All @@ -1089,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<DeltaResult | null> {
return resolveAndApplyDelta({
targetVersion,
Expand All @@ -1102,6 +1148,7 @@ export function resolveNightlyDelta(
resolveFromNetwork: () => resolveNightlyChainWithContext(targetVersion),
channel: "nightly",
offline,
setMessage,
});
}

Expand Down Expand Up @@ -1178,7 +1225,8 @@ async function resolveNightlyChainWithContext(
export function applyPatchChain(
chain: PatchChain,
oldBinaryPath: string,
destPath: string
destPath: string,
onBytes?: (bytes: number) => void
): Promise<string> {
return withTracingSpan(
"apply-patches",
Expand All @@ -1197,7 +1245,8 @@ export function applyPatchChain(
const sha256 = await applyPatchChainInMemory(
oldBinaryPath,
chain.patches.map((p) => p.data),
destPath
destPath,
onBytes
);

// Verify the final SHA-256 matches
Expand Down
100 changes: 100 additions & 0 deletions src/lib/progress.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/**
* Byte-driven progress reporting for long-running upgrade phases (patch apply,
* full-binary download).
*
* 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.
*
* 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";

/** 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;
/** 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)));
return "█".repeat(filled) + "░".repeat(width - filled);
}

/**
* Create a byte-progress reporter that feeds a spinner `setMessage` callback.
*
* @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 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,
setMessage?: SetMessage,
nowMs: () => number = Date.now
): ByteProgress {
let written = 0;
let lastEmit = 0;

const format = (): string => {
if (totalBytes === null || totalBytes <= 0) {
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)} (${pct}%)`
);
};

const emit = (): void => {
// Cosmetic only — a formatting or callback failure must never propagate.
try {
setMessage?.(format());
} 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 };
}
Loading
Loading