Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

fix(cli): stop drawing progress frames when stderr is not a terminal (#359)

KageBinary3c49cc243654
diff --git a/ix-cli/src/cli/__tests__/progress-tty.test.ts b/ix-cli/src/cli/__tests__/progress-tty.test.ts
new file mode 100644
index 00000000..ac1731e6
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/progress-tty.test.ts
@@ -0,0 +1,37 @@
+import { afterEach, describe, expect, it } from "vitest";
+
+import { canRenderProgress } from "../stderr.js";
+
+const original = process.stderr.isTTY;
+
+afterEach(() => {
+ process.stderr.isTTY = original;
+});
+
+// The progress bars in ingest.ts, map.ts and reset.ts all animate by writing
+// `\r` and overwriting the line. That only overwrites on a terminal — into a
+// redirect, a pipe or a CI log every 80 ms frame is kept, so output grew with
+// elapsed time rather than with work done. Each of those three gated on
+// something else entirely (format, --silent, nothing at all), and none of them
+// asked whether anyone was watching.
+describe("canRenderProgress", () => {
+ it("is true on a terminal", () => {
+ process.stderr.isTTY = true;
+ expect(canRenderProgress()).toBe(true);
+ });
+
+ it("is false when stderr is redirected", () => {
+ process.stderr.isTTY = false;
+ expect(canRenderProgress()).toBe(false);
+ });
+
+ it("is false when isTTY is undefined, which is what a pipe actually gives", () => {
+ // Node does not set isTTY to false on a non-tty stream — it leaves the
+ // property off entirely. So a helper written as `isTTY === false`, and a
+ // test that only ever assigned false, would both pass while every real
+ // redirect still animated. That is the case this whole fix is about, so it
+ // is the case the test has to construct.
+ delete (process.stderr as { isTTY?: boolean }).isTTY;
+ expect(canRenderProgress()).toBe(false);
+ });
+});
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index c00b2f49..20047bac 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -19,6 +19,7 @@ import { ensureWorkspaceIdState } from '../bootstrap.js';
import { detectSystem, repoWorkspaceIdFor, lookupPackage, readPackageNames, readPackageDeps } from '../system.js';
import { CLIENT_EXPECTED_SCHEMA_VERSION } from '../backend-status.js';
import { SUPPORTED_EXTENSIONS } from '../supported-extensions.js';
+import { canRenderProgress } from '../stderr.js';
import {
deterministicId,
transformIssue,
@@ -691,7 +692,16 @@ export async function ingestFiles(
let progressTotal = 0;
let progressStart = performance.now();
- const interval = opts.format === 'text' ? setInterval(() => {
+ // canRenderProgress, not just the format: `ix map` redirected to a file or
+ // captured by an agent is still format 'text', and every 80 ms frame is
+ // retained rather than overwritten.
+ //
+ // Kept as two conditions rather than folded into one flag because they gate
+ // different things below. `interval` gates the redrawing writes; the text
+ // format alone still gates the newline-terminated summary, which redirected
+ // output should keep — that is the "final summary" the bar was drowning.
+ const wantsTextProgress = opts.format === 'text';
+ const interval = (wantsTextProgress && canRenderProgress()) ? setInterval(() => {
if (debug && currentWorkLabel) {
const workElapsed = performance.now() - currentWorkStart;
if (workElapsed >= SLOW_WORK_LOG_MS && (lastSlowWorkNotice === 0 || workElapsed - lastSlowWorkNotice >= SLOW_WORK_REPEAT_MS)) {
@@ -1445,6 +1455,13 @@ export async function ingestFiles(
process.stderr.write('\r' + renderProgressLine(progressPhase, progressTotal, progressTotal));
}
process.stderr.write('\r' + ' '.repeat(PROG_LINE_WIDTH) + '\r');
+ }
+ // Outside the interval guard, on the format instead. This line is
+ // newline-terminated output, not a progress frame, and it is the only
+ // timing the user ever sees — leaving it keyed to the bar would have made
+ // silencing the bar silently drop it too, turning a fix for noisy output
+ // into a loss of the summary that output is for.
+ if (wantsTextProgress) {
const elapsedSec = ((performance.now() - start) / 1000).toFixed(1);
process.stderr.write(chalk.dim(` Ingested in ${elapsedSec}s\n`));
}
diff --git a/ix-cli/src/cli/commands/map.ts b/ix-cli/src/cli/commands/map.ts
index 97e31274..e195a01c 100644
--- a/ix-cli/src/cli/commands/map.ts
+++ b/ix-cli/src/cli/commands/map.ts
@@ -11,6 +11,7 @@ import { ingestFiles } from "./ingest.js";
import { detectSystem } from "../system.js";
import { getRemoteRunner, isCloudReady } from "../remote.js";
import { acquireMapLock } from "../single-flight.js";
+import { canRenderProgress } from "../stderr.js";
// Hard wall-clock budget for a single `ix map`. Past this, the shared deadline
// signal aborts every in-flight request and the command exits, so a single
@@ -275,7 +276,10 @@ Examples:
const mapBarWidth = 25;
const mapStart = performance.now();
- const mapInterval = (!machineFormat && !silent) ? setInterval(() => {
+ // Same gate as the ingest bar: --silent and the machine formats were the
+ // only ways to avoid this, and neither is available to something merely
+ // capturing normal output.
+ const mapInterval = (!machineFormat && !silent && canRenderProgress()) ? setInterval(() => {
const elapsed = performance.now() - mapStart;
const pct = 1 - Math.exp(-elapsed / 4000);
const filled = Math.round(pct * mapBarWidth);
diff --git a/ix-cli/src/cli/commands/reset.ts b/ix-cli/src/cli/commands/reset.ts
index b459dfc5..f9c6f285 100644
--- a/ix-cli/src/cli/commands/reset.ts
+++ b/ix-cli/src/cli/commands/reset.ts
@@ -3,6 +3,7 @@ import chalk from "chalk";
import { spawnSync } from "child_process";
import { IxClient } from "../../client/api.js";
import { getEndpoint, clearIngestMtimeCache } from "../config.js";
+import { canRenderProgress } from "../stderr.js";
export function registerResetCommand(program: Command): void {
program
@@ -35,28 +36,36 @@ export function registerResetCommand(program: Command): void {
const label = opts.code ? "Wiping code graph..." : "Wiping graph...";
const spinnerFrames = ["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];
let spinIdx = 0;
- const interval = setInterval(() => {
+ // This spinner ran unconditionally, so a redirected `ix reset` collected a
+ // frame every 80 ms for as long as the wipe took.
+ const spinner = canRenderProgress() ? setInterval(() => {
process.stderr.write(`\r${chalk.cyan(spinnerFrames[spinIdx++ % spinnerFrames.length])} ${chalk.dim(label)}`);
- }, 80);
+ }, 80) : null;
+ // One teardown for all three exits rather than the pair repeated at each.
+ // Clearing an interval that was never started is harmless, but writing the
+ // erase sequence is not: with no spinner to erase it just deposits literal
+ // escape bytes in whatever captured the output.
+ const stopSpinner = () => {
+ if (!spinner) return;
+ clearInterval(spinner);
+ process.stderr.write("\r\x1b[K");
+ };
try {
if (opts.code) {
await client.resetCode();
- clearInterval(interval);
- process.stderr.write("\r\x1b[K");
+ stopSpinner();
// Clear the mtime cache so the next ix map re-ingests all files
clearIngestMtimeCache(process.cwd());
console.log(chalk.green("✓") + " Code graph wiped. Planning artifacts preserved.");
console.log(chalk.dim(" Run `ix map` to rebuild the code graph."));
} else {
await client.reset();
- clearInterval(interval);
- process.stderr.write("\r\x1b[K");
+ stopSpinner();
clearIngestMtimeCache(process.cwd());
console.log(chalk.green("✓") + " Graph wiped.");
}
} catch (err: any) {
- clearInterval(interval);
- process.stderr.write("\r\x1b[K");
+ stopSpinner();
console.error(chalk.red("Error:"), err.message);
process.exitCode = 1;
return;
diff --git a/ix-cli/src/cli/commands/upgrade.ts b/ix-cli/src/cli/commands/upgrade.ts
index 4e9cc53f..f4bb68b0 100644
--- a/ix-cli/src/cli/commands/upgrade.ts
+++ b/ix-cli/src/cli/commands/upgrade.ts
@@ -6,6 +6,7 @@ import { fileURLToPath } from "url";
import { homedir, tmpdir } from "os";
import chalk from "chalk";
import { BACKEND_IMAGE, checkBackendImage, isNonStandardBackend } from "../backend-status.js";
+import { canRenderProgress } from "../stderr.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -716,7 +717,12 @@ function printUpdateNotice(
compassUpdate?: boolean,
backendUpdate?: boolean
): void {
- process.stderr.write("\r" + " ".repeat(80) + "\r");
+ // Erase whatever progress frame is mid-render before printing over it. There
+ // is no such frame when stderr is not a terminal, so this would be 82 bytes
+ // of padding and two carriage returns deposited straight into the captured
+ // output — and this notice fires on ordinary commands, so it leaked into
+ // redirected output that had no progress bar to begin with.
+ if (canRenderProgress()) process.stderr.write("\r" + " ".repeat(80) + "\r");
console.error("");
if (isNewer(latest, current)) {
console.error(chalk.yellow(` Update available: ${current} → ${latest}`));
diff --git a/ix-cli/src/cli/stderr.ts b/ix-cli/src/cli/stderr.ts
index 41899b3b..b050dc55 100644
--- a/ix-cli/src/cli/stderr.ts
+++ b/ix-cli/src/cli/stderr.ts
@@ -9,3 +9,21 @@ export function stderr(message: string): void {
export function stderrDim(message: string): void {
process.stderr.write(chalk.dim(message) + "\n");
}
+
+/**
+ * Whether stderr can render a redrawing progress line.
+ *
+ * A progress bar animates by returning to the start of the line with `\r` and
+ * overwriting what is there. That only overwrites on a terminal. Into a
+ * redirect, a pipe, a CI log or an agent capturing tool output, every frame is
+ * *retained* — so an 80 ms interval turns a sub-second command into dozens of
+ * stacked frames, and a long one into unbounded output that grows with
+ * duration rather than with work done.
+ *
+ * Read at each call rather than cached at module load: the tests drive this by
+ * setting `process.stderr.isTTY`, and a captured constant would answer for
+ * whatever the first import happened to see.
+ */
+export function canRenderProgress(): boolean {
+ return Boolean(process.stderr.isTTY);
+}