Skip to content
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: 6 additions & 0 deletions .changeset/feat-undo-command.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@moonshot-ai/agent-core": minor
"@moonshot-ai/kimi-code": minor
Comment thread
kermanx marked this conversation as resolved.
---

Add `/undo` slash command to withdraw the last prompt from conversation history, and keep replay records in sync when a prompt is undone.
5 changes: 5 additions & 0 deletions apps/kimi-code/src/tui/commands/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import {
handleInitCommand,
handleTitleCommand,
} from './session';
import { handleUndoCommand } from './undo';

// ---------------------------------------------------------------------------
// Re-exports — keep existing consumers working
Expand Down Expand Up @@ -78,6 +79,7 @@ export {
handleInitCommand,
handleTitleCommand,
} from './session';
export { handleUndoCommand } from './undo';

// ---------------------------------------------------------------------------
// Host interface
Expand Down Expand Up @@ -279,6 +281,9 @@ async function handleBuiltInSlashCommand(
case 'logout':
await handleLogoutCommand(host);
return;
case 'undo':
await handleUndoCommand(host, args);
return;
default:
host.showError(`Unknown slash command: /${String(name)}`);
return;
Expand Down
1 change: 1 addition & 0 deletions apps/kimi-code/src/tui/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export {
handleInitCommand,
handleTitleCommand,
} from './session';
export { handleUndoCommand } from './undo';
export {
promptApiKey,
promptCatalogProviderSelection,
Expand Down
7 changes: 7 additions & 0 deletions apps/kimi-code/src/tui/commands/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,13 @@ export const BUILTIN_SLASH_COMMANDS = [
priority: 60,
availability: 'always',
},
{
name: 'undo',
aliases: [],
description: 'Withdraw the last prompt from the transcript',
priority: 80,
availability: 'idle-only',
},
{
name: 'editor',
aliases: [],
Expand Down
188 changes: 188 additions & 0 deletions apps/kimi-code/src/tui/commands/undo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import type { Component } from '@earendil-works/pi-tui';

import { WelcomeComponent } from '../components/chrome/welcome';
import { AgentGroupComponent } from '../components/messages/agent-group';
import { AssistantMessageComponent } from '../components/messages/assistant-message';
import { BackgroundAgentStatusComponent } from '../components/messages/background-agent-status';
import { CronMessageComponent } from '../components/messages/cron-message';
import { ReadGroupComponent } from '../components/messages/read-group';
import { SkillActivationComponent } from '../components/messages/skill-activation';
import { ThinkingComponent } from '../components/messages/thinking';
import { ToolCallComponent } from '../components/messages/tool-call';
import { UserMessageComponent } from '../components/messages/user-message';
import { NO_ACTIVE_SESSION_MESSAGE } from '../constant/kimi-tui';
import type { TranscriptEntry } from '../types';
import { formatErrorMessage } from '../utils/event-payload';
import { getTranscriptComponentEntry } from '../utils/transcript-component-metadata';
import type { SlashCommandHost } from './dispatch';

// ---------------------------------------------------------------------------
// Undo command
// ---------------------------------------------------------------------------

export async function handleUndoCommand(
host: SlashCommandHost,
args: string = '',
): Promise<void> {
if (host.state.appState.streamingPhase !== 'idle') {
host.showError('Cannot undo while streaming — press Esc or Ctrl-C first.');
return;
}

const count = parseUndoCount(args);
if (count === undefined) {
host.showError('Usage: /undo [count], where count is a positive integer.');
return;
}

const session = host.session;
if (session === undefined) {
host.showError(NO_ACTIVE_SESSION_MESSAGE);
return;
}

const entries = host.state.transcriptEntries;
const lastUserIndex = findUndoAnchorEntryIndex(entries, count);
if (lastUserIndex === undefined) {
host.showError('Nothing to undo.');
return;
}

try {
await session.undoHistory(count);
} catch (error) {
const message = formatErrorMessage(error);
host.showError(`Failed to undo: ${message}`);
return;
}

const children = host.state.transcriptContainer.children;
const lastUserComponentIndex = findUndoAnchorComponentIndex(children, count);
if (lastUserComponentIndex !== undefined) {
removeUndoContextComponents(children, lastUserComponentIndex);
host.state.transcriptContainer.invalidate();
}

const preservedEntries = entries.slice(lastUserIndex).filter(
(entry) => !isUndoContextEntry(entry),
);
entries.splice(lastUserIndex, entries.length - lastUserIndex, ...preservedEntries);

if (entries.length === 0) {
renderWelcome(host);
}

host.state.ui.requestRender();
}

function parseUndoCount(args: string): number | undefined {
const value = args.trim();
if (value.length === 0) return 1;
if (!/^[1-9]\d*$/.test(value)) return undefined;
const count = Number(value);
return Number.isSafeInteger(count) ? count : undefined;
}

function isUndoAnchorEntry(entry: TranscriptEntry): boolean {
return (
entry.kind === 'user' ||
(entry.kind === 'skill_activation' && entry.skillTrigger === 'user-slash')
);
}

function findUndoAnchorEntryIndex(
entries: readonly TranscriptEntry[],
count: number,
): number | undefined {
let found = 0;
for (let i = entries.length - 1; i >= 0; i--) {
const entry = entries[i];
if (entry !== undefined && isUndoAnchorEntry(entry)) {
found++;
if (found === count) return i;
}
}
return undefined;
}

function isUndoContextEntry(entry: TranscriptEntry): boolean {
switch (entry.kind) {
case 'user':
case 'assistant':
case 'tool_call':
case 'thinking':
case 'skill_activation':
case 'cron':
return true;
case 'status':
Comment thread
kermanx marked this conversation as resolved.
return entry.turnId !== undefined;
case 'welcome':
return false;
}
}

function findUndoAnchorComponentIndex(
children: readonly Component[],
count: number,
): number | undefined {
let found = 0;
for (let i = children.length - 1; i >= 0; i--) {
const child = children[i];
if (child !== undefined && isUndoAnchorComponent(child)) {
found++;
if (found === count) return i;
}
}
return undefined;
}

function removeUndoContextComponents(
children: Component[],
startIndex: number,
): void {
for (let i = children.length - 1; i >= startIndex; i--) {
const child = children[i];
if (child !== undefined && isUndoContextComponent(child)) {
children.splice(i, 1);
}
}
}

function isUndoAnchorComponent(child: Component): boolean {
return (
child instanceof UserMessageComponent ||
(child instanceof SkillActivationComponent && child.trigger === 'user-slash')
);
}

function isUndoContextComponent(child: Component): boolean {
const entry = getTranscriptComponentEntry(child);
if (entry !== undefined) {
return isUndoContextEntry(entry);
}

return (
child instanceof UserMessageComponent ||
child instanceof AssistantMessageComponent ||
child instanceof ThinkingComponent ||
child instanceof ToolCallComponent ||
child instanceof AgentGroupComponent ||
child instanceof ReadGroupComponent ||
child instanceof SkillActivationComponent ||
child instanceof BackgroundAgentStatusComponent ||
Comment thread
kermanx marked this conversation as resolved.
child instanceof CronMessageComponent
);
}

function renderWelcome(host: SlashCommandHost): void {
if (
host.state.transcriptContainer.children.some(
(child) => child instanceof WelcomeComponent,
)
) {
return;
}
host.state.transcriptContainer.addChild(
new WelcomeComponent(host.state.appState, host.state.theme.colors),
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,17 @@ import { Container, Text, Spacer } from '@earendil-works/pi-tui';
import chalk from 'chalk';

import type { ColorPalette } from '#/tui/theme/colors';
import type { SkillActivationTrigger } from '#/tui/types';

const ARGS_PREVIEW_MAX = 200;

export class SkillActivationComponent extends Container {
constructor(name: string, args: string | undefined, colors: ColorPalette) {
constructor(
name: string,
args: string | undefined,
colors: ColorPalette,
readonly trigger?: SkillActivationTrigger,
) {
super();
this.addChild(new Spacer(1));
const head =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,7 @@ export class SessionEventHandler {
skillActivationId: event.activationId,
skillName: event.skillName,
skillArgs: event.skillArgs,
skillTrigger: event.trigger,
});
}

Expand Down
1 change: 1 addition & 0 deletions apps/kimi-code/src/tui/controllers/session-replay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,7 @@ export class SessionReplayRenderer {
skillActivationId: skill.activationId,
skillName: skill.skillName,
skillArgs: skill.skillArgs,
skillTrigger: skill.trigger,
});
}

Expand Down
11 changes: 11 additions & 0 deletions apps/kimi-code/src/tui/kimi-tui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ import { installTerminalFocusTracking } from './utils/terminal-focus';
import { notifyTerminalOnce } from './utils/terminal-notification';
import { installTerminalThemeTracking } from './utils/terminal-theme';
import { detectTmuxKeyboardWarning } from './utils/tmux-keyboard';
import { markTranscriptComponent } from './utils/transcript-component-metadata';
import { nextTranscriptId } from './utils/transcript-id';

export type { TUIState } from './tui-state';
Expand Down Expand Up @@ -1177,6 +1178,7 @@ export class KimiTUI {
entry.skillName ?? entry.content,
entry.skillArgs,
this.state.theme.colors,
entry.skillTrigger,
);
case 'cron':
return new CronMessageComponent(
Expand Down Expand Up @@ -1241,6 +1243,7 @@ export class KimiTUI {
this.state.transcriptEntries.push(entry);
const component = this.createTranscriptComponent(entry);
if (component) {
markTranscriptComponent(component, entry);
this.state.transcriptContainer.addChild(component);
this.state.ui.requestRender();
}
Expand All @@ -1267,12 +1270,20 @@ export class KimiTUI {
this.appendTranscriptEntry({
id: nextTranscriptId(),
kind: 'status',
turnId: request.turnId === undefined ? undefined : String(request.turnId),
renderMode: 'notice',
content: parts.join(''),
});
}

private renderWelcome(): void {
if (
this.state.transcriptContainer.children.some(
(child) => child instanceof WelcomeComponent,
)
) {
return;
}
const welcome = new WelcomeComponent(this.state.appState, this.state.theme.colors);
this.state.transcriptContainer.addChild(welcome);
}
Expand Down
3 changes: 3 additions & 0 deletions apps/kimi-code/src/tui/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ export type TranscriptEntryKind =
| 'skill_activation'
| 'cron';

export type SkillActivationTrigger = 'user-slash' | 'model-tool' | 'nested-skill';

export interface TranscriptEntry {
id: string;
kind: TranscriptEntryKind;
Expand All @@ -130,6 +132,7 @@ export interface TranscriptEntry {
skillActivationId?: string;
skillName?: string;
skillArgs?: string;
skillTrigger?: SkillActivationTrigger;
}

export type LivePaneMode =
Expand Down
3 changes: 3 additions & 0 deletions apps/kimi-code/src/tui/utils/message-replay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type {
import type {
AppState,
BackgroundAgentMetadata,
SkillActivationTrigger,
ToolCallBlockData,
TranscriptEntry,
} from '#/tui/types';
Expand Down Expand Up @@ -38,6 +39,7 @@ export interface SkillActivationProjection {
readonly activationId: string;
readonly skillName: string;
readonly skillArgs?: string;
readonly trigger: SkillActivationTrigger;
}

export interface ReplayBackgroundProjection {
Expand Down Expand Up @@ -203,6 +205,7 @@ export function skillActivationFromOrigin(
activationId: origin.activationId,
skillName: origin.skillName,
skillArgs: origin.skillArgs,
trigger: origin.trigger,
};
}

Expand Down
15 changes: 15 additions & 0 deletions apps/kimi-code/src/tui/utils/transcript-component-metadata.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { Component } from '@earendil-works/pi-tui';

import type { TranscriptEntry } from '../types';

const componentEntries = new WeakMap<Component, TranscriptEntry>();

export function markTranscriptComponent(component: Component, entry: TranscriptEntry): void {
componentEntries.set(component, entry);
}

export function getTranscriptComponentEntry(
component: Component,
): TranscriptEntry | undefined {
return componentEntries.get(component);
}
1 change: 1 addition & 0 deletions apps/kimi-code/test/tui/commands/registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ describe('built-in slash command registry', () => {
'status',
'theme',
'title',
'undo',
'usage',
'version',
'yolo',
Expand Down
Loading
Loading