Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(cli): harden spinner message clamping

jkomyno41019972e1ee
diff --git a/ts/packages/cli/src/services/terminal-ui.ts b/ts/packages/cli/src/services/terminal-ui.ts
index 063c2f5a2..d200d8ef0 100644
--- a/ts/packages/cli/src/services/terminal-ui.ts
+++ b/ts/packages/cli/src/services/terminal-ui.ts
@@ -201,53 +201,58 @@ type TerminalUIStreams = {
// columns. Below that the frame prefix alone overflows the row and no message
// length can keep it on one line, so the budget degrades to just the ellipsis.
const SPINNER_RENDER_OVERHEAD = 7; // frame + two spaces (3) + animated dots (3) + last-column safety (1)
+const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
-export const clampSpinnerMessage = (output: Writable, message: string): string => {
+export const clampSpinnerMessage = (columns: number, message: string): string => {
const singleLine = message.replace(/\s*\r?\n\s*/g, ' ');
if (singleLine.includes('\u001b')) {
return singleLine; // truncating could split an ANSI escape sequence
}
- const budget = Math.max(getColumns(output) - SPINNER_RENDER_OVERHEAD, 1);
+ const budget = Math.max(columns - SPINNER_RENDER_OVERHEAD, 1);
if (stringWidth(singleLine) <= budget) {
return singleLine;
}
- // Measure in display columns, not UTF-16 code units: clack wraps the rendered
- // frame by width, so a CJK character it counts as two columns would slip past
- // a `.length` budget and wrap anyway. Accumulating whole code points also keeps
- // the cut off a surrogate pair. One column is reserved for the ellipsis.
+ // Measure whole grapheme clusters in display columns. Measuring individual
+ // code points under-counts sequences such as keycap emoji, while slicing by
+ // UTF-16 length can split surrogate pairs or joined emoji. One column is
+ // reserved for the ellipsis.
let clamped = '';
let width = 0;
- for (const char of singleLine) {
- const charWidth = stringWidth(char);
- if (width + charWidth > budget - 1) {
+ for (const { segment } of graphemeSegmenter.segment(singleLine)) {
+ const segmentWidth = stringWidth(segment);
+ if (width + segmentWidth > budget - 1) {
break;
}
- clamped += char;
- width += charWidth;
+ clamped += segment;
+ width += segmentWidth;
}
return `${clamped}…`;
};
+type StartedClackSpinner = {
+ readonly raw: p.SpinnerResult;
+ readonly updateMessage: (message: string) => void;
+};
+
function createClackSpinnerHandle(
- s: p.SpinnerResult,
- defaultMessage: string,
- output: Writable
+ spinner: StartedClackSpinner,
+ defaultMessage: string
): { handle: SpinnerHandle; isStopped: () => boolean } {
let stopped = false;
return {
handle: {
- message: (msg: string) => Effect.sync(() => s.message(clampSpinnerMessage(output, msg))),
+ message: (msg: string) => Effect.sync(() => spinner.updateMessage(msg)),
stop: (msg?: string) =>
Effect.sync(() => {
stopped = true;
- s.stop(msg ?? defaultMessage);
+ spinner.raw.stop(msg ?? defaultMessage);
}),
error: (msg?: string) =>
Effect.sync(() => {
stopped = true;
- s.error(msg ?? defaultMessage);
+ spinner.raw.error(msg ?? defaultMessage);
}),
},
isStopped: () => stopped,
@@ -283,10 +288,18 @@ export const makeTerminalUI = (streams: TerminalUIStreams): TerminalUI => {
};
/** Start a clack spinner on stderr, clamped to a single terminal row. */
- const startSpinner = (message: string): p.SpinnerResult => {
- const s = p.spinner({ output: stderr });
- s.start(clampSpinnerMessage(stderr, message));
- return s;
+ const startSpinner = (message: string): StartedClackSpinner => {
+ // Clack captures this width during construction and continues wrapping
+ // against it. Updates may respect a later narrower terminal, but must never
+ // grow beyond Clack's fixed width.
+ const initialColumns = getColumns(stderr);
+ const raw = p.spinner({ output: stderr });
+ raw.start(clampSpinnerMessage(initialColumns, message));
+ return {
+ raw,
+ updateMessage: msg =>
+ raw.message(clampSpinnerMessage(Math.min(initialColumns, getColumns(stderr)), msg)),
+ };
};
return {
@@ -360,7 +373,7 @@ export const makeTerminalUI = (streams: TerminalUIStreams): TerminalUI => {
return Effect.acquireUseRelease(
Effect.sync(() => startSpinner(message)),
() => effect,
- (s, exit) =>
+ (spinner, exit) =>
Effect.sync(() => {
if (Exit.isSuccess(exit)) {
let successMessage = message;
@@ -370,9 +383,9 @@ export const makeTerminalUI = (streams: TerminalUIStreams): TerminalUI => {
} else if (configuredSuccessMessage !== undefined) {
successMessage = configuredSuccessMessage;
}
- s.stop(successMessage);
+ spinner.raw.stop(successMessage);
} else {
- s.error(options?.errorMessage ?? message);
+ spinner.raw.error(options?.errorMessage ?? message);
}
})
);
@@ -385,9 +398,9 @@ export const makeTerminalUI = (streams: TerminalUIStreams): TerminalUI => {
return Effect.acquireUseRelease(
Effect.sync(() => {
- const s = startSpinner(message);
- const { handle, isStopped } = createClackSpinnerHandle(s, message, stderr);
- return { raw: s, handle, isStopped };
+ const spinner = startSpinner(message);
+ const { handle, isStopped } = createClackSpinnerHandle(spinner, message);
+ return { raw: spinner.raw, handle, isStopped };
}),
({ handle }) => use(handle),
({ raw, isStopped }, exit) =>
diff --git a/ts/packages/cli/test/src/services/terminal-ui.test.ts b/ts/packages/cli/test/src/services/terminal-ui.test.ts
index bedf54074..abfc26780 100644
--- a/ts/packages/cli/test/src/services/terminal-ui.test.ts
+++ b/ts/packages/cli/test/src/services/terminal-ui.test.ts
@@ -173,35 +173,23 @@ describe('TerminalUI', () => {
});
describe('clampSpinnerMessage keeps live spinner messages on one terminal row', () => {
- const streamWithColumns = (columns?: number) =>
- columns === undefined ? makeSink(true) : Object.assign(makeSink(true), { columns });
-
it('leaves a message that fits untouched', () => {
- expect(clampSpinnerMessage(streamWithColumns(80), 'Checking for updates')).toBe(
- 'Checking for updates'
- );
+ expect(clampSpinnerMessage(80, 'Checking for updates')).toBe('Checking for updates');
});
it('truncates a message longer than the row budget with an ellipsis', () => {
- const clamped = clampSpinnerMessage(streamWithColumns(40), 'x'.repeat(100));
+ const clamped = clampSpinnerMessage(40, 'x'.repeat(100));
expect(clamped).toBe(`${'x'.repeat(32)}…`);
expect(clamped).toHaveLength(40 - 7);
});
it('collapses embedded newlines into spaces', () => {
- expect(clampSpinnerMessage(streamWithColumns(80), 'line one\nline two')).toBe(
- 'line one line two'
- );
+ expect(clampSpinnerMessage(80, 'line one\nline two')).toBe('line one line two');
});
it('never slices a message containing ANSI escape sequences', () => {
const colored = `\u001b[32m${'x'.repeat(100)}\u001b[0m`;
- expect(clampSpinnerMessage(streamWithColumns(40), colored)).toBe(colored);
- });
-
- it('falls back to 80 columns when the stream reports no width', () => {
- const clamped = clampSpinnerMessage(streamWithColumns(undefined), 'x'.repeat(100));
- expect(clamped).toHaveLength(80 - 7);
+ expect(clampSpinnerMessage(40, colored)).toBe(colored);
});
it('measures display columns, not UTF-16 code units', () => {
@@ -212,13 +200,23 @@ describe('TerminalUI', () => {
expect(message).toHaveLength(20);
expect(stringWidth(message)).toBe(40);
- const clamped = clampSpinnerMessage(streamWithColumns(40), message);
+ const clamped = clampSpinnerMessage(40, message);
expect(clamped.endsWith('…')).toBe(true);
expect(stringWidth(clamped)).toBeLessThanOrEqual(40 - 7);
});
+ it('measures and truncates whole grapheme clusters', () => {
+ const keycap = '1\uFE0F\u20E3';
+ expect(stringWidth(keycap)).toBe(2);
+ expect([...keycap].reduce((width, char) => width + stringWidth(char), 0)).toBe(1);
+
+ const clamped = clampSpinnerMessage(20, keycap.repeat(20));
+ expect(clamped).toMatch(/^(?:1\uFE0F\u20E3)*…$/u);
+ expect(stringWidth(clamped)).toBeLessThanOrEqual(20 - 7);
+ });
+
it('never cuts a surrogate pair in half', () => {
- const clamped = clampSpinnerMessage(streamWithColumns(20), '\u{1f600}'.repeat(40));
+ const clamped = clampSpinnerMessage(20, '\u{1f600}'.repeat(40));
expect(clamped).not.toMatch(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/);
expect(stringWidth(clamped)).toBeLessThanOrEqual(20 - 7);
});
@@ -226,12 +224,12 @@ describe('TerminalUI', () => {
it('degrades to the ellipsis on terminals narrower than the frame overhead', () => {
// Below SPINNER_RENDER_OVERHEAD + 1 columns no message length fits, so the
// budget bottoms out at one column rather than jumping back up to eight.
- expect(clampSpinnerMessage(streamWithColumns(4), 'x'.repeat(100))).toBe('…');
+ expect(clampSpinnerMessage(4, 'x'.repeat(100))).toBe('…');
});
it('keeps the rendered frame within the row at the exact budget boundary', () => {
const columns = 20;
- const clamped = clampSpinnerMessage(streamWithColumns(columns), 'x'.repeat(100));
+ const clamped = clampSpinnerMessage(columns, 'x'.repeat(100));
// frame (1) + two spaces (2) + message + three animated dots (3).
expect(1 + 2 + stringWidth(clamped) + 3).toBeLessThanOrEqual(columns);
});
@@ -311,6 +309,56 @@ describe('TerminalUI', () => {
)
);
+ it.live('does not grow updates beyond the width Clack captured at construction', () =>
+ withFakeTimers(
+ Effect.gen(function* () {
+ const { ui, stderr } = narrowUi(20);
+
+ yield* ui.useMakeSpinner('Checking for updates...', spinner =>
+ Effect.gen(function* () {
+ stderr.columns = 80;
+ yield* spinner.message(LONG_UPGRADE_MESSAGE);
+ yield* Effect.sync(() => vi.advanceTimersByTime(TICKS_PAST_THREE_DOTS));
+ yield* spinner.stop('Upgrade completed!');
+ })
+ );
+
+ const frames = clampedFrames(stderr);
+ expect(frames.length).toBeGreaterThan(0);
+ expect(frames[0]).toContain('New version');
+ for (const frame of frames) {
+ expect(frame).not.toContain('\n');
+ expect(stringWidth(frame)).toBeLessThanOrEqual(20);
+ }
+ })
+ )
+ );
+
+ it.live('respects a terminal that narrows after spinner construction', () =>
+ withFakeTimers(
+ Effect.gen(function* () {
+ const { ui, stderr } = narrowUi(80);
+
+ yield* ui.useMakeSpinner('Checking for updates...', spinner =>
+ Effect.gen(function* () {
+ stderr.columns = 20;
+ yield* spinner.message(LONG_UPGRADE_MESSAGE);
+ yield* Effect.sync(() => vi.advanceTimersByTime(TICKS_PAST_THREE_DOTS));
+ yield* spinner.stop('Upgrade completed!');
+ })
+ );
+
+ const frames = clampedFrames(stderr);
+ expect(frames.length).toBeGreaterThan(0);
+ expect(frames[0]).toContain('New version');
+ for (const frame of frames) {
+ expect(frame).not.toContain('\n');
+ expect(stringWidth(frame)).toBeLessThanOrEqual(20);
+ }
+ })
+ )
+ );
+
it.live('clamps the withSpinner start message too', () =>
withFakeTimers(
Effect.gen(function* () {