Merge branch 'feat/ctrl-n-external-editor' - configurable keybindings (#405)

This commit is contained in:
Mario Zechner 2026-01-03 22:51:12 +01:00
commit f2b89d5ec5
26 changed files with 1258 additions and 1081 deletions

View file

@ -2,6 +2,10 @@
## [Unreleased]
### Added
- Configurable keybindings via `~/.pi/agent/keybindings.json`. All keyboard shortcuts (editor navigation, deletion, app actions like model cycling, etc.) can now be customized. Supports multiple bindings per action. ([#405](https://github.com/badlogic/pi-mono/pull/405) by [@hjanuschka](https://github.com/hjanuschka))
## [0.32.3] - 2026-01-03
### Fixed

View file

@ -24,6 +24,7 @@ Works on Linux, macOS, and Windows (requires bash; see [Windows Setup](#windows-
- [Slash Commands](#slash-commands)
- [Editor Features](#editor-features)
- [Keyboard Shortcuts](#keyboard-shortcuts)
- [Custom Keybindings](#custom-keybindings)
- [Bash Mode](#bash-mode)
- [Image Support](#image-support)
- [Sessions](#sessions)
@ -266,6 +267,61 @@ Both modes are configurable via `/settings`: "one-at-a-time" delivers messages o
| Ctrl+T | Toggle thinking block visibility |
| Ctrl+G | Edit message in external editor (`$VISUAL` or `$EDITOR`) |
### Custom Keybindings
All keyboard shortcuts can be customized via `~/.pi/agent/keybindings.json`. Each action can be bound to one or more keys.
**Key format:** `modifier+key` where modifiers are `ctrl`, `shift`, `alt` and keys are `a-z`, `0-9`, `escape`, `tab`, `enter`, `space`, `backspace`, `delete`, `home`, `end`, `up`, `down`, `left`, `right`.
**Configurable actions:**
| Action | Default | Description |
|--------|---------|-------------|
| `cursorUp` | `up` | Move cursor up |
| `cursorDown` | `down` | Move cursor down |
| `cursorLeft` | `left` | Move cursor left |
| `cursorRight` | `right` | Move cursor right |
| `cursorWordLeft` | `alt+left`, `ctrl+left` | Move cursor word left |
| `cursorWordRight` | `alt+right`, `ctrl+right` | Move cursor word right |
| `cursorLineStart` | `home`, `ctrl+a` | Move to line start |
| `cursorLineEnd` | `end`, `ctrl+e` | Move to line end |
| `deleteCharBackward` | `backspace` | Delete char backward |
| `deleteCharForward` | `delete` | Delete char forward |
| `deleteWordBackward` | `ctrl+w`, `alt+backspace` | Delete word backward |
| `deleteToLineStart` | `ctrl+u` | Delete to line start |
| `deleteToLineEnd` | `ctrl+k` | Delete to line end |
| `newLine` | `shift+enter`, `alt+enter` | Insert new line |
| `submit` | `enter` | Submit input |
| `tab` | `tab` | Tab/autocomplete |
| `interrupt` | `escape` | Interrupt operation |
| `clear` | `ctrl+c` | Clear editor |
| `exit` | `ctrl+d` | Exit (when empty) |
| `suspend` | `ctrl+z` | Suspend process |
| `cycleThinkingLevel` | `shift+tab` | Cycle thinking level |
| `cycleModelForward` | `ctrl+p` | Next model |
| `cycleModelBackward` | `shift+ctrl+p` | Previous model |
| `selectModel` | `ctrl+l` | Open model selector |
| `expandTools` | `ctrl+o` | Expand tool output |
| `toggleThinking` | `ctrl+t` | Toggle thinking |
| `externalEditor` | `ctrl+g` | Open external editor |
| `followUp` | `alt+enter` | Queue follow-up message |
**Example (Emacs-style):**
```json
{
"cursorUp": ["up", "ctrl+p"],
"cursorDown": ["down", "ctrl+n"],
"cursorLeft": ["left", "ctrl+b"],
"cursorRight": ["right", "ctrl+f"],
"cursorWordLeft": ["alt+left", "alt+b"],
"cursorWordRight": ["alt+right", "alt+f"],
"deleteCharForward": ["delete", "ctrl+d"],
"deleteCharBackward": ["backspace", "ctrl+h"],
"newLine": ["shift+enter", "ctrl+j"]
}
```
### Bash Mode
Prefix commands with `!` to execute them and add output to context:

View file

@ -3,7 +3,7 @@
*/
import type { HookAPI } from "@mariozechner/pi-coding-agent";
import { isArrowDown, isArrowLeft, isArrowRight, isArrowUp, isEscape, visibleWidth } from "@mariozechner/pi-tui";
import { matchesKey, visibleWidth } from "@mariozechner/pi-tui";
const GAME_WIDTH = 40;
const GAME_HEIGHT = 15;
@ -150,7 +150,7 @@ class SnakeComponent {
handleInput(data: string): void {
// If paused (resuming), wait for any key
if (this.paused) {
if (isEscape(data) || data === "q" || data === "Q") {
if (matchesKey(data, "escape") || data === "q" || data === "Q") {
// Quit without clearing save
this.dispose();
this.onClose();
@ -163,7 +163,7 @@ class SnakeComponent {
}
// ESC to pause and save
if (isEscape(data)) {
if (matchesKey(data, "escape")) {
this.dispose();
this.onSave(this.state);
this.onClose();
@ -179,13 +179,13 @@ class SnakeComponent {
}
// Arrow keys or WASD
if (isArrowUp(data) || data === "w" || data === "W") {
if (matchesKey(data, "up") || data === "w" || data === "W") {
if (this.state.direction !== "down") this.state.nextDirection = "up";
} else if (isArrowDown(data) || data === "s" || data === "S") {
} else if (matchesKey(data, "down") || data === "s" || data === "S") {
if (this.state.direction !== "up") this.state.nextDirection = "down";
} else if (isArrowRight(data) || data === "d" || data === "D") {
} else if (matchesKey(data, "right") || data === "d" || data === "D") {
if (this.state.direction !== "left") this.state.nextDirection = "right";
} else if (isArrowLeft(data) || data === "a" || data === "A") {
} else if (matchesKey(data, "left") || data === "a" || data === "A") {
if (this.state.direction !== "right") this.state.nextDirection = "left";
}

View file

@ -6,7 +6,7 @@
*/
import type { HookAPI, Theme } from "@mariozechner/pi-coding-agent";
import { isCtrlC, isEscape, truncateToWidth } from "@mariozechner/pi-tui";
import { matchesKey, truncateToWidth } from "@mariozechner/pi-tui";
interface Todo {
id: number;
@ -35,7 +35,7 @@ class TodoListComponent {
}
handleInput(data: string): void {
if (isEscape(data) || isCtrlC(data)) {
if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
this.onClose();
}
}

View file

@ -0,0 +1,199 @@
import {
DEFAULT_EDITOR_KEYBINDINGS,
type EditorAction,
type EditorKeybindingsConfig,
EditorKeybindingsManager,
type KeyId,
matchesKey,
setEditorKeybindings,
} from "@mariozechner/pi-tui";
import { existsSync, readFileSync } from "fs";
import { join } from "path";
import { getAgentDir } from "../config.js";
/**
* Application-level actions (coding agent specific).
*/
export type AppAction =
| "interrupt"
| "clear"
| "exit"
| "suspend"
| "cycleThinkingLevel"
| "cycleModelForward"
| "cycleModelBackward"
| "selectModel"
| "expandTools"
| "toggleThinking"
| "externalEditor"
| "followUp";
/**
* All configurable actions.
*/
export type KeyAction = AppAction | EditorAction;
/**
* Full keybindings configuration (app + editor actions).
*/
export type KeybindingsConfig = {
[K in KeyAction]?: KeyId | KeyId[];
};
/**
* Default application keybindings.
*/
export const DEFAULT_APP_KEYBINDINGS: Record<AppAction, KeyId | KeyId[]> = {
interrupt: "escape",
clear: "ctrl+c",
exit: "ctrl+d",
suspend: "ctrl+z",
cycleThinkingLevel: "shift+tab",
cycleModelForward: "ctrl+p",
cycleModelBackward: "shift+ctrl+p",
selectModel: "ctrl+l",
expandTools: "ctrl+o",
toggleThinking: "ctrl+t",
externalEditor: "ctrl+g",
followUp: "alt+enter",
};
/**
* All default keybindings (app + editor).
*/
export const DEFAULT_KEYBINDINGS: Required<KeybindingsConfig> = {
...DEFAULT_EDITOR_KEYBINDINGS,
...DEFAULT_APP_KEYBINDINGS,
};
// App actions list for type checking
const APP_ACTIONS: AppAction[] = [
"interrupt",
"clear",
"exit",
"suspend",
"cycleThinkingLevel",
"cycleModelForward",
"cycleModelBackward",
"selectModel",
"expandTools",
"toggleThinking",
"externalEditor",
"followUp",
];
function isAppAction(action: string): action is AppAction {
return APP_ACTIONS.includes(action as AppAction);
}
/**
* Manages all keybindings (app + editor).
*/
export class KeybindingsManager {
private config: KeybindingsConfig;
private appActionToKeys: Map<AppAction, KeyId[]>;
private constructor(config: KeybindingsConfig) {
this.config = config;
this.appActionToKeys = new Map();
this.buildMaps();
}
/**
* Create from config file and set up editor keybindings.
*/
static create(agentDir: string = getAgentDir()): KeybindingsManager {
const configPath = join(agentDir, "keybindings.json");
const config = KeybindingsManager.loadFromFile(configPath);
const manager = new KeybindingsManager(config);
// Set up editor keybindings globally
const editorConfig: EditorKeybindingsConfig = {};
for (const [action, keys] of Object.entries(config)) {
if (!isAppAction(action)) {
editorConfig[action as EditorAction] = keys;
}
}
setEditorKeybindings(new EditorKeybindingsManager(editorConfig));
return manager;
}
/**
* Create in-memory.
*/
static inMemory(config: KeybindingsConfig = {}): KeybindingsManager {
return new KeybindingsManager(config);
}
private static loadFromFile(path: string): KeybindingsConfig {
if (!existsSync(path)) return {};
try {
return JSON.parse(readFileSync(path, "utf-8"));
} catch {
return {};
}
}
private buildMaps(): void {
this.appActionToKeys.clear();
// Set defaults for app actions
for (const [action, keys] of Object.entries(DEFAULT_APP_KEYBINDINGS)) {
const keyArray = Array.isArray(keys) ? keys : [keys];
this.appActionToKeys.set(action as AppAction, [...keyArray]);
}
// Override with user config (app actions only)
for (const [action, keys] of Object.entries(this.config)) {
if (keys === undefined || !isAppAction(action)) continue;
const keyArray = Array.isArray(keys) ? keys : [keys];
this.appActionToKeys.set(action, keyArray);
}
}
/**
* Check if input matches an app action.
*/
matches(data: string, action: AppAction): boolean {
const keys = this.appActionToKeys.get(action);
if (!keys) return false;
for (const key of keys) {
if (matchesKey(data, key)) return true;
}
return false;
}
/**
* Get keys bound to an app action.
*/
getKeys(action: AppAction): KeyId[] {
return this.appActionToKeys.get(action) ?? [];
}
/**
* Get display string for an action.
*/
getDisplayString(action: AppAction): string {
const keys = this.getKeys(action);
if (keys.length === 0) return "";
if (keys.length === 1) return keys[0]!;
return keys.join("/");
}
/**
* Get the full effective config.
*/
getEffectiveConfig(): Required<KeybindingsConfig> {
const result = { ...DEFAULT_KEYBINDINGS };
for (const [action, keys] of Object.entries(this.config)) {
if (keys !== undefined) {
(result as KeybindingsConfig)[action as KeyAction] = keys;
}
}
return result;
}
}
// Re-export for convenience
export type { EditorAction, KeyId };

View file

@ -1,113 +1,65 @@
import {
Editor,
isAltEnter,
isCtrlC,
isCtrlD,
isCtrlG,
isCtrlL,
isCtrlO,
isCtrlP,
isCtrlT,
isCtrlZ,
isEscape,
isShiftCtrlP,
isShiftTab,
} from "@mariozechner/pi-tui";
import { Editor, type EditorTheme } from "@mariozechner/pi-tui";
import type { AppAction, KeybindingsManager } from "../../../core/keybindings.js";
/**
* Custom editor that handles Escape and Ctrl+C keys for coding-agent
* Custom editor that handles app-level keybindings for coding-agent.
*/
export class CustomEditor extends Editor {
private keybindings: KeybindingsManager;
private actionHandlers: Map<AppAction, () => void> = new Map();
// Special handlers that can be dynamically replaced
public onEscape?: () => void;
public onCtrlC?: () => void;
public onCtrlD?: () => void;
public onShiftTab?: () => void;
public onCtrlP?: () => void;
public onShiftCtrlP?: () => void;
public onCtrlL?: () => void;
public onCtrlO?: () => void;
public onCtrlT?: () => void;
public onCtrlG?: () => void;
public onCtrlZ?: () => void;
public onAltEnter?: () => void;
constructor(theme: EditorTheme, keybindings: KeybindingsManager) {
super(theme);
this.keybindings = keybindings;
}
/**
* Register a handler for an app action.
*/
onAction(action: AppAction, handler: () => void): void {
this.actionHandlers.set(action, handler);
}
handleInput(data: string): void {
// Intercept Alt+Enter for follow-up messages
if (isAltEnter(data) && this.onAltEnter) {
this.onAltEnter();
return;
}
// Intercept Ctrl+G for external editor
if (isCtrlG(data) && this.onCtrlG) {
this.onCtrlG();
return;
}
// Check app keybindings first
// Intercept Ctrl+Z for suspend
if (isCtrlZ(data) && this.onCtrlZ) {
this.onCtrlZ();
return;
}
// Intercept Ctrl+T for thinking block visibility toggle
if (isCtrlT(data) && this.onCtrlT) {
this.onCtrlT();
return;
}
// Intercept Ctrl+L for model selector
if (isCtrlL(data) && this.onCtrlL) {
this.onCtrlL();
return;
}
// Intercept Ctrl+O for tool output expansion
if (isCtrlO(data) && this.onCtrlO) {
this.onCtrlO();
return;
}
// Intercept Shift+Ctrl+P for backward model cycling (check before Ctrl+P)
if (isShiftCtrlP(data) && this.onShiftCtrlP) {
this.onShiftCtrlP();
return;
}
// Intercept Ctrl+P for model cycling
if (isCtrlP(data) && this.onCtrlP) {
this.onCtrlP();
return;
}
// Intercept Shift+Tab for thinking level cycling
if (isShiftTab(data) && this.onShiftTab) {
this.onShiftTab();
return;
}
// Intercept Escape key - but only if autocomplete is NOT active
// (let parent handle escape for autocomplete cancellation)
if (isEscape(data) && this.onEscape && !this.isShowingAutocomplete()) {
this.onEscape();
return;
}
// Intercept Ctrl+C
if (isCtrlC(data) && this.onCtrlC) {
this.onCtrlC();
return;
}
// Intercept Ctrl+D (only when editor is empty)
if (isCtrlD(data)) {
if (this.getText().length === 0 && this.onCtrlD) {
this.onCtrlD();
// Escape/interrupt - only if autocomplete is NOT active
if (this.keybindings.matches(data, "interrupt")) {
if (!this.isShowingAutocomplete()) {
// Use dynamic onEscape if set, otherwise registered handler
const handler = this.onEscape ?? this.actionHandlers.get("interrupt");
if (handler) {
handler();
return;
}
}
// Always consume Ctrl+D (don't pass to parent)
// Let parent handle escape for autocomplete cancellation
super.handleInput(data);
return;
}
// Pass to parent for normal handling
// Exit (Ctrl+D) - only when editor is empty
if (this.keybindings.matches(data, "exit")) {
if (this.getText().length === 0) {
const handler = this.onCtrlD ?? this.actionHandlers.get("exit");
if (handler) handler();
}
return; // Always consume
}
// Check all other app actions
for (const [action, handler] of this.actionHandlers) {
if (action !== "interrupt" && action !== "exit" && this.keybindings.matches(data, action)) {
handler();
return;
}
}
// Pass to parent for editor handling
super.handleInput(data);
}
}

View file

@ -7,7 +7,7 @@ import { spawnSync } from "node:child_process";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { Container, Editor, isCtrlC, isCtrlG, isEscape, Spacer, Text, type TUI } from "@mariozechner/pi-tui";
import { Container, Editor, getEditorKeybindings, matchesKey, Spacer, Text, type TUI } from "@mariozechner/pi-tui";
import { getEditorTheme, theme } from "../theme/theme.js";
import { DynamicBorder } from "./dynamic-border.js";
@ -67,14 +67,15 @@ export class HookEditorComponent extends Container {
return;
}
const kb = getEditorKeybindings();
// Escape or Ctrl+C to cancel
if (isEscape(keyData) || isCtrlC(keyData)) {
if (kb.matches(keyData, "selectCancel")) {
this.onCancelCallback();
return;
}
// Ctrl+G for external editor
if (isCtrlG(keyData)) {
// Ctrl+G for external editor (keep matchesKey for this app-specific action)
if (matchesKey(keyData, "ctrl+g")) {
this.openExternalEditor();
return;
}

View file

@ -2,7 +2,7 @@
* Simple text input component for hooks.
*/
import { Container, Input, isCtrlC, isEnter, isEscape, Spacer, Text } from "@mariozechner/pi-tui";
import { Container, getEditorKeybindings, Input, Spacer, Text } from "@mariozechner/pi-tui";
import { theme } from "../theme/theme.js";
import { DynamicBorder } from "./dynamic-border.js";
@ -46,14 +46,15 @@ export class HookInputComponent extends Container {
}
handleInput(keyData: string): void {
const kb = getEditorKeybindings();
// Enter
if (isEnter(keyData) || keyData === "\n") {
if (kb.matches(keyData, "selectConfirm") || keyData === "\n") {
this.onSubmitCallback(this.input.getValue());
return;
}
// Escape or Ctrl+C to cancel
if (isEscape(keyData) || isCtrlC(keyData)) {
if (kb.matches(keyData, "selectCancel")) {
this.onCancelCallback();
return;
}

View file

@ -3,7 +3,7 @@
* Displays a list of string options with keyboard navigation.
*/
import { Container, isArrowDown, isArrowUp, isCtrlC, isEnter, isEscape, Spacer, Text } from "@mariozechner/pi-tui";
import { Container, getEditorKeybindings, Spacer, Text } from "@mariozechner/pi-tui";
import { theme } from "../theme/theme.js";
import { DynamicBorder } from "./dynamic-border.js";
@ -66,25 +66,26 @@ export class HookSelectorComponent extends Container {
}
handleInput(keyData: string): void {
const kb = getEditorKeybindings();
// Up arrow or k
if (isArrowUp(keyData) || keyData === "k") {
if (kb.matches(keyData, "selectUp") || keyData === "k") {
this.selectedIndex = Math.max(0, this.selectedIndex - 1);
this.updateList();
}
// Down arrow or j
else if (isArrowDown(keyData) || keyData === "j") {
else if (kb.matches(keyData, "selectDown") || keyData === "j") {
this.selectedIndex = Math.min(this.options.length - 1, this.selectedIndex + 1);
this.updateList();
}
// Enter
else if (isEnter(keyData) || keyData === "\n") {
else if (kb.matches(keyData, "selectConfirm") || keyData === "\n") {
const selected = this.options[this.selectedIndex];
if (selected) {
this.onSelectCallback(selected);
}
}
// Escape or Ctrl+C
else if (isEscape(keyData) || isCtrlC(keyData)) {
else if (kb.matches(keyData, "selectCancel")) {
this.onCancelCallback();
}
}

View file

@ -1,16 +1,5 @@
import { type Model, modelsAreEqual } from "@mariozechner/pi-ai";
import {
Container,
Input,
isArrowDown,
isArrowUp,
isCtrlC,
isEnter,
isEscape,
Spacer,
Text,
type TUI,
} from "@mariozechner/pi-tui";
import { Container, getEditorKeybindings, Input, Spacer, Text, type TUI } from "@mariozechner/pi-tui";
import type { ModelRegistry } from "../../../core/model-registry.js";
import type { SettingsManager } from "../../../core/settings-manager.js";
import { fuzzyFilter } from "../../../utils/fuzzy.js";
@ -216,27 +205,28 @@ export class ModelSelectorComponent extends Container {
}
handleInput(keyData: string): void {
const kb = getEditorKeybindings();
// Up arrow - wrap to bottom when at top
if (isArrowUp(keyData)) {
if (kb.matches(keyData, "selectUp")) {
if (this.filteredModels.length === 0) return;
this.selectedIndex = this.selectedIndex === 0 ? this.filteredModels.length - 1 : this.selectedIndex - 1;
this.updateList();
}
// Down arrow - wrap to top when at bottom
else if (isArrowDown(keyData)) {
else if (kb.matches(keyData, "selectDown")) {
if (this.filteredModels.length === 0) return;
this.selectedIndex = this.selectedIndex === this.filteredModels.length - 1 ? 0 : this.selectedIndex + 1;
this.updateList();
}
// Enter
else if (isEnter(keyData)) {
else if (kb.matches(keyData, "selectConfirm")) {
const selectedModel = this.filteredModels[this.selectedIndex];
if (selectedModel) {
this.handleSelect(selectedModel.model);
}
}
// Escape or Ctrl+C
else if (isEscape(keyData) || isCtrlC(keyData)) {
else if (kb.matches(keyData, "selectCancel")) {
this.onCancelCallback();
}
// Pass everything else to search input

View file

@ -1,14 +1,5 @@
import { getOAuthProviders, type OAuthProviderInfo } from "@mariozechner/pi-ai";
import {
Container,
isArrowDown,
isArrowUp,
isCtrlC,
isEnter,
isEscape,
Spacer,
TruncatedText,
} from "@mariozechner/pi-tui";
import { Container, getEditorKeybindings, Spacer, TruncatedText } from "@mariozechner/pi-tui";
import type { AuthStorage } from "../../../core/auth-storage.js";
import { theme } from "../theme/theme.js";
import { DynamicBorder } from "./dynamic-border.js";
@ -104,25 +95,26 @@ export class OAuthSelectorComponent extends Container {
}
handleInput(keyData: string): void {
const kb = getEditorKeybindings();
// Up arrow
if (isArrowUp(keyData)) {
if (kb.matches(keyData, "selectUp")) {
this.selectedIndex = Math.max(0, this.selectedIndex - 1);
this.updateList();
}
// Down arrow
else if (isArrowDown(keyData)) {
else if (kb.matches(keyData, "selectDown")) {
this.selectedIndex = Math.min(this.allProviders.length - 1, this.selectedIndex + 1);
this.updateList();
}
// Enter
else if (isEnter(keyData)) {
else if (kb.matches(keyData, "selectConfirm")) {
const selectedProvider = this.allProviders[this.selectedIndex];
if (selectedProvider?.available) {
this.onSelectCallback(selectedProvider.id);
}
}
// Escape or Ctrl+C
else if (isEscape(keyData) || isCtrlC(keyData)) {
else if (kb.matches(keyData, "selectCancel")) {
this.onCancelCallback();
}
}

View file

@ -1,12 +1,8 @@
import {
type Component,
Container,
getEditorKeybindings,
Input,
isArrowDown,
isArrowUp,
isCtrlC,
isEnter,
isEscape,
Spacer,
Text,
truncateToWidth,
@ -126,31 +122,28 @@ class SessionList implements Component {
}
handleInput(keyData: string): void {
const kb = getEditorKeybindings();
// Up arrow
if (isArrowUp(keyData)) {
if (kb.matches(keyData, "selectUp")) {
this.selectedIndex = Math.max(0, this.selectedIndex - 1);
}
// Down arrow
else if (isArrowDown(keyData)) {
else if (kb.matches(keyData, "selectDown")) {
this.selectedIndex = Math.min(this.filteredSessions.length - 1, this.selectedIndex + 1);
}
// Enter
else if (isEnter(keyData)) {
else if (kb.matches(keyData, "selectConfirm")) {
const selected = this.filteredSessions[this.selectedIndex];
if (selected && this.onSelect) {
this.onSelect(selected.path);
}
}
// Escape - cancel
else if (isEscape(keyData)) {
else if (kb.matches(keyData, "selectCancel")) {
if (this.onCancel) {
this.onCancel();
}
}
// Ctrl+C - exit
else if (isCtrlC(keyData)) {
this.onExit();
}
// Pass everything else to search input
else {
this.searchInput.handleInput(keyData);

View file

@ -1,17 +1,9 @@
import {
type Component,
Container,
getEditorKeybindings,
Input,
isArrowDown,
isArrowLeft,
isArrowRight,
isArrowUp,
isBackspace,
isCtrlC,
isCtrlO,
isEnter,
isEscape,
isShiftCtrlO,
matchesKey,
Spacer,
Text,
TruncatedText,
@ -664,43 +656,42 @@ class TreeList implements Component {
}
handleInput(keyData: string): void {
if (isArrowUp(keyData)) {
const kb = getEditorKeybindings();
if (kb.matches(keyData, "selectUp")) {
this.selectedIndex = this.selectedIndex === 0 ? this.filteredNodes.length - 1 : this.selectedIndex - 1;
} else if (isArrowDown(keyData)) {
} else if (kb.matches(keyData, "selectDown")) {
this.selectedIndex = this.selectedIndex === this.filteredNodes.length - 1 ? 0 : this.selectedIndex + 1;
} else if (isArrowLeft(keyData)) {
} else if (kb.matches(keyData, "cursorLeft")) {
// Page up
this.selectedIndex = Math.max(0, this.selectedIndex - this.maxVisibleLines);
} else if (isArrowRight(keyData)) {
} else if (kb.matches(keyData, "cursorRight")) {
// Page down
this.selectedIndex = Math.min(this.filteredNodes.length - 1, this.selectedIndex + this.maxVisibleLines);
} else if (isEnter(keyData)) {
} else if (kb.matches(keyData, "selectConfirm")) {
const selected = this.filteredNodes[this.selectedIndex];
if (selected && this.onSelect) {
this.onSelect(selected.node.entry.id);
}
} else if (isEscape(keyData)) {
} else if (kb.matches(keyData, "selectCancel")) {
if (this.searchQuery) {
this.searchQuery = "";
this.applyFilter();
} else {
this.onCancel?.();
}
} else if (isCtrlC(keyData)) {
this.onCancel?.();
} else if (isShiftCtrlO(keyData)) {
} else if (matchesKey(keyData, "shift+ctrl+o")) {
// Cycle filter backwards
const modes: FilterMode[] = ["default", "no-tools", "user-only", "labeled-only", "all"];
const currentIndex = modes.indexOf(this.filterMode);
this.filterMode = modes[(currentIndex - 1 + modes.length) % modes.length];
this.applyFilter();
} else if (isCtrlO(keyData)) {
} else if (matchesKey(keyData, "ctrl+o")) {
// Cycle filter forwards: default → no-tools → user-only → labeled-only → all → default
const modes: FilterMode[] = ["default", "no-tools", "user-only", "labeled-only", "all"];
const currentIndex = modes.indexOf(this.filterMode);
this.filterMode = modes[(currentIndex + 1) % modes.length];
this.applyFilter();
} else if (isBackspace(keyData)) {
} else if (kb.matches(keyData, "deleteCharBackward")) {
if (this.searchQuery.length > 0) {
this.searchQuery = this.searchQuery.slice(0, -1);
this.applyFilter();
@ -768,10 +759,11 @@ class LabelInput implements Component {
}
handleInput(keyData: string): void {
if (isEnter(keyData)) {
const kb = getEditorKeybindings();
if (kb.matches(keyData, "selectConfirm")) {
const value = this.input.getValue().trim();
this.onSubmit?.(this.entryId, value || undefined);
} else if (isEscape(keyData)) {
} else if (kb.matches(keyData, "selectCancel")) {
this.onCancel?.();
} else {
this.input.handleInput(keyData);

View file

@ -1,15 +1,4 @@
import {
type Component,
Container,
isArrowDown,
isArrowUp,
isCtrlC,
isEnter,
isEscape,
Spacer,
Text,
truncateToWidth,
} from "@mariozechner/pi-tui";
import { type Component, Container, getEditorKeybindings, Spacer, Text, truncateToWidth } from "@mariozechner/pi-tui";
import { theme } from "../theme/theme.js";
import { DynamicBorder } from "./dynamic-border.js";
@ -89,29 +78,24 @@ class UserMessageList implements Component {
}
handleInput(keyData: string): void {
const kb = getEditorKeybindings();
// Up arrow - go to previous (older) message, wrap to bottom when at top
if (isArrowUp(keyData)) {
if (kb.matches(keyData, "selectUp")) {
this.selectedIndex = this.selectedIndex === 0 ? this.messages.length - 1 : this.selectedIndex - 1;
}
// Down arrow - go to next (newer) message, wrap to top when at bottom
else if (isArrowDown(keyData)) {
else if (kb.matches(keyData, "selectDown")) {
this.selectedIndex = this.selectedIndex === this.messages.length - 1 ? 0 : this.selectedIndex + 1;
}
// Enter - select message and branch
else if (isEnter(keyData)) {
else if (kb.matches(keyData, "selectConfirm")) {
const selected = this.messages[this.selectedIndex];
if (selected && this.onSelect) {
this.onSelect(selected.id);
}
}
// Escape - cancel
else if (isEscape(keyData)) {
if (this.onCancel) {
this.onCancel();
}
}
// Ctrl+C - cancel
else if (isCtrlC(keyData)) {
else if (kb.matches(keyData, "selectCancel")) {
if (this.onCancel) {
this.onCancel();
}

View file

@ -13,6 +13,7 @@ import {
CombinedAutocompleteProvider,
type Component,
Container,
getEditorKeybindings,
Input,
Loader,
Markdown,
@ -28,6 +29,7 @@ import { APP_NAME, getAuthPath, getDebugLogPath } from "../../config.js";
import type { AgentSession, AgentSessionEvent } from "../../core/agent-session.js";
import type { CustomToolSessionEvent, LoadedCustomTool } from "../../core/custom-tools/index.js";
import type { HookUIContext } from "../../core/hooks/index.js";
import { KeybindingsManager } from "../../core/keybindings.js";
import { createCompactionSummaryMessage } from "../../core/messages.js";
import { type SessionContext, SessionManager } from "../../core/session-manager.js";
import { loadSkills } from "../../core/skills.js";
@ -84,6 +86,7 @@ export class InteractiveMode {
private editor: CustomEditor;
private editorContainer: Container;
private footer: FooterComponent;
private keybindings: KeybindingsManager;
private version: string;
private isInitialized = false;
private onInputCallback?: (text: string) => void;
@ -165,7 +168,8 @@ export class InteractiveMode {
this.chatContainer = new Container();
this.pendingMessagesContainer = new Container();
this.statusContainer = new Container();
this.editor = new CustomEditor(getEditorTheme());
this.keybindings = KeybindingsManager.create();
this.editor = new CustomEditor(getEditorTheme(), this.keybindings);
this.editorContainer = new Container();
this.editorContainer.addChild(this.editor);
this.footer = new FooterComponent(session);
@ -217,43 +221,65 @@ export class InteractiveMode {
async init(): Promise<void> {
if (this.isInitialized) return;
// Add header
// Add header with keybindings from config
const logo = theme.bold(theme.fg("accent", APP_NAME)) + theme.fg("dim", ` v${this.version}`);
// Format keybinding for startup display (lowercase, compact)
const formatStartupKey = (keys: string | string[]): string => {
const keyArray = Array.isArray(keys) ? keys : [keys];
return keyArray.join("/");
};
const kb = this.keybindings;
const interrupt = formatStartupKey(kb.getKeys("interrupt"));
const clear = formatStartupKey(kb.getKeys("clear"));
const exit = formatStartupKey(kb.getKeys("exit"));
const suspend = formatStartupKey(kb.getKeys("suspend"));
const deleteToLineEnd = formatStartupKey(getEditorKeybindings().getKeys("deleteToLineEnd"));
const cycleThinkingLevel = formatStartupKey(kb.getKeys("cycleThinkingLevel"));
const cycleModelForward = formatStartupKey(kb.getKeys("cycleModelForward"));
const cycleModelBackward = formatStartupKey(kb.getKeys("cycleModelBackward"));
const selectModel = formatStartupKey(kb.getKeys("selectModel"));
const expandTools = formatStartupKey(kb.getKeys("expandTools"));
const toggleThinking = formatStartupKey(kb.getKeys("toggleThinking"));
const externalEditor = formatStartupKey(kb.getKeys("externalEditor"));
const followUp = formatStartupKey(kb.getKeys("followUp"));
const instructions =
theme.fg("dim", "esc") +
theme.fg("dim", interrupt) +
theme.fg("muted", " to interrupt") +
"\n" +
theme.fg("dim", "ctrl+c") +
theme.fg("dim", clear) +
theme.fg("muted", " to clear") +
"\n" +
theme.fg("dim", "ctrl+c twice") +
theme.fg("dim", `${clear} twice`) +
theme.fg("muted", " to exit") +
"\n" +
theme.fg("dim", "ctrl+d") +
theme.fg("dim", exit) +
theme.fg("muted", " to exit (empty)") +
"\n" +
theme.fg("dim", "ctrl+z") +
theme.fg("dim", suspend) +
theme.fg("muted", " to suspend") +
"\n" +
theme.fg("dim", "ctrl+k") +
theme.fg("dim", deleteToLineEnd) +
theme.fg("muted", " to delete line") +
"\n" +
theme.fg("dim", "shift+tab") +
theme.fg("dim", cycleThinkingLevel) +
theme.fg("muted", " to cycle thinking") +
"\n" +
theme.fg("dim", "ctrl+p/shift+ctrl+p") +
theme.fg("dim", `${cycleModelForward}/${cycleModelBackward}`) +
theme.fg("muted", " to cycle models") +
"\n" +
theme.fg("dim", "ctrl+l") +
theme.fg("dim", selectModel) +
theme.fg("muted", " to select model") +
"\n" +
theme.fg("dim", "ctrl+o") +
theme.fg("dim", expandTools) +
theme.fg("muted", " to expand tools") +
"\n" +
theme.fg("dim", "ctrl+t") +
theme.fg("dim", toggleThinking) +
theme.fg("muted", " to toggle thinking") +
"\n" +
theme.fg("dim", "ctrl+g") +
theme.fg("dim", externalEditor) +
theme.fg("muted", " for external editor") +
"\n" +
theme.fg("dim", "/") +
@ -262,7 +288,7 @@ export class InteractiveMode {
theme.fg("dim", "!") +
theme.fg("muted", " to run bash") +
"\n" +
theme.fg("dim", "alt+enter") +
theme.fg("dim", followUp) +
theme.fg("muted", " to queue follow-up") +
"\n" +
theme.fg("dim", "drop files") +
@ -770,20 +796,21 @@ export class InteractiveMode {
}
};
this.editor.onCtrlC = () => this.handleCtrlC();
// Register app action handlers
this.editor.onAction("clear", () => this.handleCtrlC());
this.editor.onCtrlD = () => this.handleCtrlD();
this.editor.onCtrlZ = () => this.handleCtrlZ();
this.editor.onShiftTab = () => this.cycleThinkingLevel();
this.editor.onCtrlP = () => this.cycleModel("forward");
this.editor.onShiftCtrlP = () => this.cycleModel("backward");
this.editor.onAction("suspend", () => this.handleCtrlZ());
this.editor.onAction("cycleThinkingLevel", () => this.cycleThinkingLevel());
this.editor.onAction("cycleModelForward", () => this.cycleModel("forward"));
this.editor.onAction("cycleModelBackward", () => this.cycleModel("backward"));
// Global debug handler on TUI (works regardless of focus)
this.ui.onDebug = () => this.handleDebugCommand();
this.editor.onCtrlL = () => this.showModelSelector();
this.editor.onCtrlO = () => this.toggleToolOutputExpansion();
this.editor.onCtrlT = () => this.toggleThinkingBlockVisibility();
this.editor.onCtrlG = () => this.openExternalEditor();
this.editor.onAltEnter = () => this.handleAltEnter();
this.editor.onAction("selectModel", () => this.showModelSelector());
this.editor.onAction("expandTools", () => this.toggleToolOutputExpansion());
this.editor.onAction("toggleThinking", () => this.toggleThinkingBlockVisibility());
this.editor.onAction("externalEditor", () => this.openExternalEditor());
this.editor.onAction("followUp", () => this.handleFollowUp());
this.editor.onChange = (text: string) => {
const wasBashMode = this.isBashMode;
@ -1448,7 +1475,7 @@ export class InteractiveMode {
process.kill(0, "SIGTSTP");
}
private async handleAltEnter(): Promise<void> {
private async handleFollowUp(): Promise<void> {
const text = this.editor.getText().trim();
if (!text) return;
@ -2262,38 +2289,96 @@ export class InteractiveMode {
this.ui.requestRender();
}
/**
* Format keybindings for display (e.g., "ctrl+c" -> "Ctrl+C").
*/
private formatKeyDisplay(keys: string | string[]): string {
const keyArray = Array.isArray(keys) ? keys : [keys];
return keyArray
.map((key) =>
key
.split("+")
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join("+"),
)
.join("/");
}
/**
* Get display string for an app keybinding action.
*/
private getAppKeyDisplay(action: Parameters<KeybindingsManager["getDisplayString"]>[0]): string {
const display = this.keybindings.getDisplayString(action);
return this.formatKeyDisplay(display);
}
/**
* Get display string for an editor keybinding action.
*/
private getEditorKeyDisplay(action: Parameters<ReturnType<typeof getEditorKeybindings>["getKeys"]>[0]): string {
const keys = getEditorKeybindings().getKeys(action);
return this.formatKeyDisplay(keys);
}
private handleHotkeysCommand(): void {
// Navigation keybindings
const cursorWordLeft = this.getEditorKeyDisplay("cursorWordLeft");
const cursorWordRight = this.getEditorKeyDisplay("cursorWordRight");
const cursorLineStart = this.getEditorKeyDisplay("cursorLineStart");
const cursorLineEnd = this.getEditorKeyDisplay("cursorLineEnd");
// Editing keybindings
const submit = this.getEditorKeyDisplay("submit");
const newLine = this.getEditorKeyDisplay("newLine");
const deleteWordBackward = this.getEditorKeyDisplay("deleteWordBackward");
const deleteToLineStart = this.getEditorKeyDisplay("deleteToLineStart");
const deleteToLineEnd = this.getEditorKeyDisplay("deleteToLineEnd");
const tab = this.getEditorKeyDisplay("tab");
// App keybindings
const interrupt = this.getAppKeyDisplay("interrupt");
const clear = this.getAppKeyDisplay("clear");
const exit = this.getAppKeyDisplay("exit");
const suspend = this.getAppKeyDisplay("suspend");
const cycleThinkingLevel = this.getAppKeyDisplay("cycleThinkingLevel");
const cycleModelForward = this.getAppKeyDisplay("cycleModelForward");
const expandTools = this.getAppKeyDisplay("expandTools");
const toggleThinking = this.getAppKeyDisplay("toggleThinking");
const externalEditor = this.getAppKeyDisplay("externalEditor");
const followUp = this.getAppKeyDisplay("followUp");
const hotkeys = `
**Navigation**
| Key | Action |
|-----|--------|
| \`Arrow keys\` | Move cursor / browse history (Up when empty) |
| \`Option+Left/Right\` | Move by word |
| \`Ctrl+A\` / \`Home\` / \`Cmd+Left\` | Start of line |
| \`Ctrl+E\` / \`End\` / \`Cmd+Right\` | End of line |
| \`${cursorWordLeft}\` / \`${cursorWordRight}\` | Move by word |
| \`${cursorLineStart}\` | Start of line |
| \`${cursorLineEnd}\` | End of line |
**Editing**
| Key | Action |
|-----|--------|
| \`Enter\` | Send message |
| \`Shift+Enter\` / \`Alt+Enter\` | New line |
| \`Ctrl+W\` / \`Option+Backspace\` | Delete word backwards |
| \`Ctrl+U\` | Delete to start of line |
| \`Ctrl+K\` | Delete to end of line |
| \`${submit}\` | Send message |
| \`${newLine}\` | New line |
| \`${deleteWordBackward}\` | Delete word backwards |
| \`${deleteToLineStart}\` | Delete to start of line |
| \`${deleteToLineEnd}\` | Delete to end of line |
**Other**
| Key | Action |
|-----|--------|
| \`Tab\` | Path completion / accept autocomplete |
| \`Escape\` | Cancel autocomplete / abort streaming |
| \`Ctrl+C\` | Clear editor (first) / exit (second) |
| \`Ctrl+D\` | Exit (when editor is empty) |
| \`Ctrl+Z\` | Suspend to background |
| \`Shift+Tab\` | Cycle thinking level |
| \`Ctrl+P\` | Cycle models |
| \`Ctrl+O\` | Toggle tool output expansion |
| \`Ctrl+T\` | Toggle thinking block visibility |
| \`Ctrl+G\` | Edit message in external editor |
| \`${tab}\` | Path completion / accept autocomplete |
| \`${interrupt}\` | Cancel autocomplete / abort streaming |
| \`${clear}\` | Clear editor (first) / exit (second) |
| \`${exit}\` | Exit (when editor is empty) |
| \`${suspend}\` | Suspend to background |
| \`${cycleThinkingLevel}\` | Cycle thinking level |
| \`${cycleModelForward}\` | Cycle models |
| \`${expandTools}\` | Toggle tool output expansion |
| \`${toggleThinking}\` | Toggle thinking block visibility |
| \`${externalEditor}\` | Edit message in external editor |
| \`${followUp}\` | Queue follow-up message |
| \`/\` | Slash commands |
| \`!\` | Run bash command |
`;