Add cn ls command with TUI session selector and JSON output

This commit is contained in:
Nate 2025-08-18 09:10:57 -07:00
parent 04d8608a64
commit 40a0eb6b2a
8 changed files with 585 additions and 0 deletions

View file

@ -29,6 +29,12 @@ The CLI automatically saves your chat history for each terminal session. You can
```bash
# Resume the last session in this terminal
cn --resume
# List recent sessions and choose one to resume
cn ls
# List sessions in JSON format (for scripting)
cn ls --json
```
## Command Line Options
@ -37,3 +43,18 @@ cn --resume
- `--config <path>`: Specify agent configuration path
- `--resume`: Resume the last session for this terminal
- `<prompt>`: Optional prompt to start with
## Commands
- `cn`: Start an interactive chat session
- `cn ls`: List recent sessions with TUI selector to choose one to resume
- `cn login`: Authenticate with Continue
- `cn logout`: Sign out of current session
- `cn remote`: Launch a remote instance
- `cn serve`: Start HTTP server mode
### Session Listing (`cn ls`)
Shows recent sessions, limited by screen height to ensure it fits on your terminal.
- `--json`: Output in JSON format for scripting (always shows 10 sessions)

View file

@ -1,5 +1,13 @@
import { type AssistantConfig } from "@continuedev/sdk";
// Export command functions
export { chat } from "./chat.js";
export { login } from "./login.js";
export { logout } from "./logout.js";
export { remote } from "./remote.js";
export { serve } from "./serve.js";
export { listSessionsCommand } from "./ls.js";
export interface SlashCommand {
name: string;
description: string;

129
src/commands/ls.test.ts Normal file
View file

@ -0,0 +1,129 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as sessionModule from "../session.js";
import { listSessionsCommand } from "./ls.js";
// Mock the session module
vi.mock("../session.js", () => ({
listSessions: vi.fn(),
loadSessionById: vi.fn(),
}));
// Mock the TUI components
vi.mock("../ui/SessionSelector.js", () => ({
SessionSelector: () => null,
}));
// Mock ink
vi.mock("ink", () => ({
render: vi.fn(() => ({ unmount: vi.fn() })),
}));
// Mock react
vi.mock("react", () => ({
createElement: vi.fn(),
}));
// Mock the chat command
vi.mock("./chat.js", () => ({
chat: vi.fn(),
}));
describe("listSessionsCommand", () => {
const mockListSessions = vi.mocked(sessionModule.listSessions);
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.restoreAllMocks();
});
it("should output JSON format when format is json", async () => {
const mockSessions = [
{
id: "session-1",
path: "/path/to/session1.json",
timestamp: new Date("2023-01-01T10:00:00Z"),
messageCount: 5,
firstUserMessage: "Hello world",
},
{
id: "session-2",
path: "/path/to/session2.json",
timestamp: new Date("2023-01-01T09:00:00Z"),
messageCount: 3,
firstUserMessage: "Test message",
},
];
mockListSessions.mockReturnValue(mockSessions);
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
await listSessionsCommand({ format: "json" });
expect(consoleSpy).toHaveBeenCalledWith(
JSON.stringify({
sessions: [
{
id: "session-1",
timestamp: "2023-01-01T10:00:00.000Z",
messageCount: 5,
firstUserMessage: "Hello world",
},
{
id: "session-2",
timestamp: "2023-01-01T09:00:00.000Z",
messageCount: 3,
firstUserMessage: "Test message",
},
],
}, null, 2)
);
consoleSpy.mockRestore();
});
it("should use limit of 10 for JSON and 20 for TUI", async () => {
mockListSessions.mockReturnValue([]);
// JSON mode should fetch 10
await listSessionsCommand({ format: "json" });
expect(mockListSessions).toHaveBeenCalledWith(10);
// TUI mode should fetch 20 (so UI can choose how many to display)
await listSessionsCommand({});
expect(mockListSessions).toHaveBeenCalledWith(20);
});
it("should handle empty sessions gracefully in JSON mode", async () => {
mockListSessions.mockReturnValue([]);
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
await listSessionsCommand({ format: "json" });
expect(consoleSpy).toHaveBeenCalledWith(
JSON.stringify({ sessions: [] }, null, 2)
);
consoleSpy.mockRestore();
});
it("should handle empty sessions gracefully in TUI mode", async () => {
mockListSessions.mockReturnValue([]);
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
await listSessionsCommand({});
expect(consoleSpy).toHaveBeenCalledWith(
"No previous sessions found. Start a new conversation with: cn"
);
consoleSpy.mockRestore();
});
});

95
src/commands/ls.ts Normal file
View file

@ -0,0 +1,95 @@
import { render } from "ink";
import React from "react";
import { loadSessionById, listSessions } from "../session.js";
import { SessionSelector } from "../ui/SessionSelector.js";
import { logger } from "../util/logger.js";
import { chat } from "./chat.js";
interface ListSessionsOptions {
format?: "json";
}
/**
* Set a specific session ID for the current process
* This allows us to load a selected session as if it were the current session
*/
function setSessionId(sessionId: string): void {
// Use the same environment variable that getSessionId() checks
process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace('continue-cli-', '');
}
/**
* List recent chat sessions and allow selection
*/
export async function listSessionsCommand(options: ListSessionsOptions = {}): Promise<void> {
// Fetch more sessions than we might display so the UI can choose based on screen height
// But still limit for JSON output to keep it reasonable
const sessions = listSessions(options.format === "json" ? 10 : 20);
// Handle JSON format output
if (options.format === "json") {
console.log(JSON.stringify({
sessions: sessions.map(session => ({
id: session.id,
timestamp: session.timestamp.toISOString(),
messageCount: session.messageCount,
firstUserMessage: session.firstUserMessage,
})),
}, null, 2));
return;
}
// Handle empty sessions case
if (sessions.length === 0) {
console.log("No previous sessions found. Start a new conversation with: cn");
return;
}
// Start TUI selector
return new Promise<void>((resolve, reject) => {
const handleSelect = async (sessionId: string) => {
try {
app.unmount();
// Verify the session exists before trying to load it
const sessionHistory = loadSessionById(sessionId);
if (!sessionHistory) {
console.error(`Session ${sessionId} could not be loaded.`);
resolve();
return;
}
logger.info(`Loading session: ${sessionId}`);
// Set the session ID so that when chat() runs, it will load this session
setSessionId(sessionId);
// Start chat with resume flag to load the selected session
await chat(undefined, {
resume: true,
headless: false
});
resolve();
} catch (error) {
logger.error("Error loading session:", error);
reject(error);
}
};
const handleExit = () => {
app.unmount();
resolve();
};
const app = render(
React.createElement(SessionSelector, {
sessions,
onSelect: handleSelect,
onExit: handleExit,
})
);
});
}

View file

@ -5,6 +5,7 @@ import { Command } from "commander";
import { chat } from "./commands/chat.js";
import { login } from "./commands/login.js";
import { logout } from "./commands/logout.js";
import { listSessionsCommand } from "./commands/ls.js";
import { remoteTest } from "./commands/remote-test.js";
import { remote } from "./commands/remote.js";
import { serve } from "./commands/serve.js";
@ -148,6 +149,17 @@ program
await logout();
});
// List sessions subcommand
program
.command("ls")
.description("List recent chat sessions and select one to resume")
.option("--json", "Output in JSON format")
.action(async (options) => {
await listSessionsCommand({
format: options.json ? "json" : undefined
});
});
// Remote subcommand
program
.command("remote [prompt]")

View file

@ -243,3 +243,107 @@ export function hasSession(): boolean {
const sessionFilePath = getSessionFilePath();
return fs.existsSync(sessionFilePath);
}
/**
* Session metadata for listing sessions
*/
export interface SessionMetadata {
id: string; // Session ID from filename
path: string; // Full file path
timestamp: Date; // Last modified or session timestamp
messageCount: number; // Total messages in session
firstUserMessage?: string; // Preview of first user input
}
/**
* Get metadata from a session file
*/
function getSessionMetadata(filePath: string): SessionMetadata | null {
try {
const fileName = path.basename(filePath, '.json');
const stats = fs.statSync(filePath);
const sessionData = JSON.parse(fs.readFileSync(filePath, "utf8"));
const chatHistory = sessionData.chatHistory || [];
const messageCount = chatHistory.length;
// Find the first user message
let firstUserMessage: string | undefined;
for (let i = 0; i < chatHistory.length; i++) {
if (chatHistory[i].role === 'user') {
firstUserMessage = chatHistory[i].content;
break;
}
}
// Use session timestamp if available, otherwise file modification time
const timestamp = sessionData.timestamp
? new Date(sessionData.timestamp)
: stats.mtime;
return {
id: fileName,
path: filePath,
timestamp,
messageCount,
firstUserMessage,
};
} catch (error) {
logger.error(`Error reading session file ${filePath}:`, error);
return null;
}
}
/**
* List all available sessions with metadata
*/
export function listSessions(limit: number = 10): SessionMetadata[] {
try {
const sessionDir = getSessionDir();
if (!fs.existsSync(sessionDir)) {
return [];
}
const files = fs.readdirSync(sessionDir)
.filter(file => file.endsWith('.json'))
.map(file => path.join(sessionDir, file));
const sessions: SessionMetadata[] = [];
for (const filePath of files) {
const metadata = getSessionMetadata(filePath);
if (metadata) {
sessions.push(metadata);
}
}
// Sort by timestamp (most recent first) and limit results
return sessions
.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())
.slice(0, limit);
} catch (error) {
logger.error("Error listing sessions:", error);
return [];
}
}
/**
* Load chat history from a specific session file
*/
export function loadSessionById(sessionId: string): ChatCompletionMessageParam[] | null {
try {
const sessionDir = getSessionDir();
const sessionFilePath = path.join(sessionDir, `${sessionId}.json`);
if (!fs.existsSync(sessionFilePath)) {
return null;
}
const sessionData = JSON.parse(fs.readFileSync(sessionFilePath, "utf8"));
return sessionData.chatHistory || null;
} catch (error) {
logger.error("Error loading session by ID:", error);
return null;
}
}

View file

@ -0,0 +1,96 @@
import { render } from "ink-testing-library";
import React from "react";
import { describe, expect, it, vi } from "vitest";
import { SessionMetadata } from "../session.js";
import { SessionSelector } from "./SessionSelector.js";
describe("SessionSelector", () => {
const mockSessions: SessionMetadata[] = [
{
id: "session-1",
path: "/path/1.json",
timestamp: new Date("2023-01-01T10:00:00Z"),
messageCount: 5,
firstUserMessage: "Hello world",
},
{
id: "session-2",
path: "/path/2.json",
timestamp: new Date("2023-01-01T09:00:00Z"),
messageCount: 3,
firstUserMessage: "Test message",
},
];
it("should render sessions with first user message", () => {
const onSelect = vi.fn();
const onExit = vi.fn();
const { lastFrame } = render(
<SessionSelector
sessions={mockSessions}
onSelect={onSelect}
onExit={onExit}
/>
);
expect(lastFrame()).toContain("Hello world");
expect(lastFrame()).toContain("Test message");
expect(lastFrame()).toContain("Recent Sessions");
});
it("should handle empty sessions", () => {
const onSelect = vi.fn();
const onExit = vi.fn();
const { lastFrame } = render(
<SessionSelector
sessions={[]}
onSelect={onSelect}
onExit={onExit}
/>
);
expect(lastFrame()).toContain("No previous sessions found");
});
it("should limit sessions based on terminal height", () => {
// Mock a small terminal height
const originalRows = process.stdout.rows;
process.stdout.rows = 10; // Small height
// Create many sessions
const manySessions = Array.from({ length: 20 }, (_, i) => ({
id: `session-${i}`,
path: `/path/${i}.json`,
timestamp: new Date(`2023-01-01T${10 + i}:00:00Z`),
messageCount: 5,
firstUserMessage: `Message ${i}`,
}));
const onSelect = vi.fn();
const onExit = vi.fn();
const { lastFrame } = render(
<SessionSelector
sessions={manySessions}
onSelect={onSelect}
onExit={onExit}
/>
);
const output = lastFrame();
// Should show truncation message when limited
expect(output).toContain("Showing");
expect(output).toContain("of 20 sessions");
// Should not show all 20 sessions
expect(output).not.toContain("Message 10");
// Restore original rows
process.stdout.rows = originalRows;
});
});

120
src/ui/SessionSelector.tsx Normal file
View file

@ -0,0 +1,120 @@
import { Box, Text, useInput } from "ink";
import React, { useMemo, useState } from "react";
import { SessionMetadata } from "../session.js";
interface SessionSelectorProps {
sessions: SessionMetadata[];
onSelect: (sessionId: string) => void;
onExit: () => void;
}
function formatTimestamp(date: Date): string {
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
if (diffDays === 0) {
return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
} else if (diffDays === 1) {
return "yesterday";
} else if (diffDays < 7) {
return `${diffDays} days ago`;
} else {
return date.toLocaleDateString();
}
}
function formatMessage(message: string | undefined): string {
if (!message) return "(no messages)";
return message.split("\n")[0];
}
function getTerminalHeight(): number {
// Default to reasonable fallback if we can't detect
return process.stdout.rows || 25;
}
export function SessionSelector({
sessions,
onSelect,
onExit,
}: SessionSelectorProps) {
const [selectedIndex, setSelectedIndex] = useState(0);
// Calculate how many sessions we can display based on terminal height
const displaySessions = useMemo(() => {
const terminalHeight = getTerminalHeight();
// Reserve 5 lines for header and instructions, each session takes 3 lines (2 content + 1 spacer)
const availableHeight = Math.max(1, terminalHeight - 5);
const maxDisplayableSessions = Math.floor(availableHeight / 3);
return sessions.slice(0, maxDisplayableSessions);
}, [sessions]);
useInput((input, key) => {
if (key.upArrow || input === "k") {
setSelectedIndex((prev) =>
prev > 0 ? prev - 1 : displaySessions.length - 1,
);
} else if (key.downArrow || input === "j") {
setSelectedIndex((prev) =>
prev < displaySessions.length - 1 ? prev + 1 : 0,
);
} else if (key.return) {
if (displaySessions[selectedIndex]) {
onSelect(displaySessions[selectedIndex].id);
}
} else if (key.escape || (key.ctrl && input === "c")) {
onExit();
}
});
if (sessions.length === 0) {
return (
<Box flexDirection="column" padding={1}>
<Text color="yellow">No previous sessions found.</Text>
<Text color="gray">Start a new conversation with: cn</Text>
<Text color="gray">Press ESC to exit</Text>
</Box>
);
}
return (
<Box flexDirection="column" padding={1}>
<Text color="blue" bold>
Recent Sessions
</Text>
<Text color="gray">
Use ↑↓ arrows to navigate, Enter to select, ESC to exit
</Text>
<Text> </Text>
{displaySessions.map((session, index) => {
const isSelected = index === selectedIndex;
const indicator = isSelected ? "► " : " ";
const color = isSelected ? "cyan" : "white";
return (
<Box key={`session-${session.id}`} flexDirection="column">
<Box paddingRight={3}>
<Text color={color} wrap="truncate-end">
{indicator}
{formatMessage(session.firstUserMessage)}
</Text>
</Box>
<Box marginLeft={2}>
<Text color="gray">
{formatTimestamp(session.timestamp)} - {session.messageCount}{" "}
messages
</Text>
</Box>
{index < displaySessions.length - 1 && (
<Text key={`spacer-${index}`}> </Text>
)}
</Box>
);
})}
</Box>
);
}