Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

Improve CLI menu navigation behavior

M Shehzen9e63101910d0
diff --git a/src/channels/cli.ts b/src/channels/cli.ts
index c453cdde..e5cbb93a 100644
--- a/src/channels/cli.ts
+++ b/src/channels/cli.ts
@@ -6,13 +6,19 @@ import type { ChannelMessage } from '../types/channel.js';
import { BaseChannel } from './base.js';
import { logger } from '../utils/logger.js';
import { renderMarkdown } from '../utils/markdown.js';
-import { selectWithArrowKeys, type ArrowSelectOption } from '../utils/arrow-select.js';
+import {
+ ArrowSelectCancelledError,
+ selectWithArrowKeys,
+ type ArrowSelectOption,
+} from '../utils/arrow-select.js';
export class CLIChannel extends BaseChannel {
readonly type = 'cli' as const;
private rl: readline.Interface | null = null;
private agentName: string;
private menuDepth = 0;
+ private menuAbortController: AbortController | null = null;
+ private outputInProgress = 0;
constructor(agentName: string = 'Mercury') {
super();
@@ -63,6 +69,8 @@ export class CLIChannel extends BaseChannel {
}
async send(content: string, _targetId?: string, elapsedMs?: number): Promise<void> {
+ this.closeActiveMenu();
+ this.beginOutput();
const timeStr = elapsedMs != null ? chalk.dim(` (${(elapsedMs / 1000).toFixed(1)}s)`) : '';
const rendered = renderMarkdown(content);
console.log('');
@@ -73,15 +81,16 @@ export class CLIChannel extends BaseChannel {
.join('\n');
console.log(indented);
console.log('');
- if (this.menuDepth === 0) {
- this.showPrompt();
- }
+ this.endOutput();
}
async sendFile(filePath: string, _targetId?: string): Promise<void> {
+ this.closeActiveMenu();
+ this.beginOutput();
const resolved = path.resolve(filePath);
if (!fs.existsSync(resolved)) {
console.log(chalk.red(` File not found: ${filePath}`));
+ this.endOutput();
return;
}
const stat = fs.statSync(resolved);
@@ -95,12 +104,12 @@ export class CLIChannel extends BaseChannel {
console.log(chalk.dim(` path: ${resolved}`));
console.log(chalk.dim(` size: ${sizeStr}`));
console.log('');
- if (this.menuDepth === 0) {
- this.showPrompt();
- }
+ this.endOutput();
}
async stream(content: AsyncIterable<string>, _targetId?: string): Promise<string> {
+ this.closeActiveMenu();
+ this.beginOutput();
console.log('');
process.stdout.write(chalk.cyan(` ${this.agentName}: `));
let full = '';
@@ -109,9 +118,7 @@ export class CLIChannel extends BaseChannel {
full += chunk;
}
console.log('\n');
- if (this.menuDepth === 0) {
- this.showPrompt();
- }
+ this.endOutput();
return full;
}
@@ -126,21 +133,51 @@ export class CLIChannel extends BaseChannel {
}
}
- async withMenu<T>(runner: (select: (title: string, options: ArrowSelectOption[]) => Promise<string>) => Promise<T>): Promise<T> {
+ async withMenu<T>(runner: (select: (title: string, options: ArrowSelectOption[]) => Promise<string>) => Promise<T>): Promise<T | undefined> {
this.menuDepth += 1;
+ this.menuAbortController = new AbortController();
this.suspendPrompt();
try {
- return await runner((title, options) => selectWithArrowKeys(title, options));
+ return await runner((title, options) => selectWithArrowKeys(title, options, {
+ signal: this.menuAbortController?.signal,
+ }));
+ } catch (error) {
+ if (error instanceof ArrowSelectCancelledError) {
+ return undefined;
+ }
+ throw error;
} finally {
this.menuDepth = Math.max(0, this.menuDepth - 1);
+ if (this.menuDepth === 0) {
+ this.menuAbortController = null;
+ }
if (this.menuDepth === 0) {
this.resumePrompt();
- this.showPrompt();
+ if (this.outputInProgress === 0) {
+ this.showPrompt();
+ }
}
}
}
+ private closeActiveMenu(): void {
+ if (!this.menuAbortController?.signal.aborted) {
+ this.menuAbortController?.abort();
+ }
+ }
+
+ private beginOutput(): void {
+ this.outputInProgress += 1;
+ }
+
+ private endOutput(): void {
+ this.outputInProgress = Math.max(0, this.outputInProgress - 1);
+ if (this.menuDepth === 0 && this.outputInProgress === 0) {
+ this.showPrompt();
+ }
+ }
+
private suspendPrompt(): void {
if (!this.rl) return;
process.stdout.write('\n');
diff --git a/src/utils/arrow-select.ts b/src/utils/arrow-select.ts
index b55a5304..5498cbda 100644
--- a/src/utils/arrow-select.ts
+++ b/src/utils/arrow-select.ts
@@ -6,9 +6,23 @@ export interface ArrowSelectOption {
label: string;
}
+export interface ArrowSelectConfig {
+ helperText?: string;
+ maxVisibleOptions?: number;
+ signal?: AbortSignal;
+}
+
+export class ArrowSelectCancelledError extends Error {
+ constructor(message: string = 'Arrow select cancelled') {
+ super(message);
+ this.name = 'ArrowSelectCancelledError';
+ }
+}
+
export async function selectWithArrowKeys(
title: string,
options: ArrowSelectOption[],
+ config: ArrowSelectConfig = {},
): Promise<string> {
if (!process.stdin.isTTY || !process.stdout.isTTY || options.length === 0) {
return options[0]?.value ?? '';
@@ -19,39 +33,84 @@ export async function selectWithArrowKeys(
const stdin = process.stdin;
const stdout = process.stdout;
const canUseRawMode = typeof stdin.setRawMode === 'function';
+ const helperText = config.helperText || 'Use the arrow keys, then press Enter.';
+ const maxVisibleOptions = Math.max(
+ 1,
+ Math.min(
+ options.length,
+ config.maxVisibleOptions ?? Math.max(5, (stdout.rows || 12) - 7),
+ ),
+ );
let activeIndex = 0;
let renderedLineCount = 0;
+ let windowStart = 0;
- const render = () => {
+ const topIndicator = (hasHiddenAbove: boolean) => (
+ hasHiddenAbove ? chalk.dim(' ↑ more') : ' '
+ );
+ const bottomIndicator = (hasHiddenBelow: boolean) => (
+ hasHiddenBelow ? chalk.dim(' ↓ more') : ' '
+ );
+
+ const writeLines = (lines: string[]) => {
if (renderedLineCount > 0) {
- readline.moveCursor(stdout, 0, -renderedLineCount);
- readline.clearScreenDown(stdout);
+ readline.moveCursor(stdout, 0, -(renderedLineCount - 1));
+ }
+
+ for (let index = 0; index < lines.length; index += 1) {
+ readline.cursorTo(stdout, 0);
+ readline.clearLine(stdout, 0);
+ stdout.write(lines[index]);
+ if (index < lines.length - 1) {
+ stdout.write('\n');
+ }
+ }
+ };
+
+ const render = () => {
+ if (activeIndex < windowStart) {
+ windowStart = activeIndex;
+ } else if (activeIndex >= windowStart + maxVisibleOptions) {
+ windowStart = activeIndex - maxVisibleOptions + 1;
}
+ const visibleOptions = options.slice(windowStart, windowStart + maxVisibleOptions);
+ const hasHiddenAbove = windowStart > 0;
+ const hasHiddenBelow = windowStart + maxVisibleOptions < options.length;
const lines = [
chalk.bold.white(` ${title}`),
- chalk.dim(' Use the arrow keys, then press Enter.'),
+ chalk.dim(` ${helperText}`),
'',
- ...options.map((option, index) => {
- const marker = index === activeIndex ? chalk.cyan('>') : ' ';
- const text = index === activeIndex ? chalk.white(option.label) : chalk.dim(option.label);
+ topIndicator(hasHiddenAbove),
+ ...visibleOptions.map((option, visibleIndex) => {
+ const index = windowStart + visibleIndex;
+ const isActive = index === activeIndex;
+ const marker = isActive ? chalk.cyanBright('●') : chalk.dim('·');
+ const text = isActive ? chalk.cyanBright(option.label) : chalk.dim(option.label);
return ` ${marker} ${text}`;
}),
+ bottomIndicator(hasHiddenBelow),
'',
];
- stdout.write(lines.join('\n'));
+ writeLines(lines);
renderedLineCount = lines.length;
};
- return await new Promise<string>((resolve) => {
+ return await new Promise<string>((resolve, reject) => {
const cleanup = () => {
stdin.off('keypress', onKeypress);
+ config.signal?.removeEventListener('abort', onAbort);
if (canUseRawMode) {
stdin.setRawMode(false);
}
};
+ const onAbort = () => {
+ cleanup();
+ reject(new ArrowSelectCancelledError());
+ };
+
const onKeypress = (_input: string, key: readline.Key) => {
if (key.ctrl && key.name === 'c') {
cleanup();
@@ -84,6 +143,13 @@ export async function selectWithArrowKeys(
}
stdin.resume();
stdin.on('keypress', onKeypress);
+ config.signal?.addEventListener('abort', onAbort, { once: true });
+
+ if (config.signal?.aborted) {
+ onAbort();
+ return;
+ }
+
render();
});
}