Merge pull request #230 from continuedev/resume-2
Add `cn ls` command with TUI session selector and JSON output
This commit is contained in:
commit
c680fb7ae6
10 changed files with 661 additions and 0 deletions
21
README.md
21
README.md
|
|
@ -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)
|
||||
|
|
|
|||
19
package-lock.json
generated
19
package-lock.json
generated
|
|
@ -29,6 +29,7 @@
|
|||
"@workos-inc/node": "^7.45.0",
|
||||
"chalk": "^5.4.1",
|
||||
"commander": "^14.0.0",
|
||||
"date-fns": "^4.1.0",
|
||||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.5.0",
|
||||
"express": "^5.1.0",
|
||||
|
|
@ -63,6 +64,7 @@
|
|||
"@semantic-release/github": "^11.0.3",
|
||||
"@semantic-release/npm": "^12.0.2",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@types/date-fns": "^2.5.3",
|
||||
"@types/diff": "^7.0.2",
|
||||
"@types/express": "^5.0.3",
|
||||
"@types/glob": "^8.1.0",
|
||||
|
|
@ -5627,6 +5629,13 @@
|
|||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/date-fns": {
|
||||
"version": "2.5.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/date-fns/-/date-fns-2.5.3.tgz",
|
||||
"integrity": "sha512-4KVPD3g5RjSgZtdOjvI/TDFkLNUHhdoWxmierdQbDeEg17Rov0hbBYtIzNaQA67ORpteOhvR9YEMTb6xeDCang==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/deep-eql": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
|
||||
|
|
@ -8124,6 +8133,16 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/date-fns": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz",
|
||||
"integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/kossnocorp"
|
||||
}
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.4.1",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz",
|
||||
|
|
|
|||
|
|
@ -58,6 +58,7 @@
|
|||
"@workos-inc/node": "^7.45.0",
|
||||
"chalk": "^5.4.1",
|
||||
"commander": "^14.0.0",
|
||||
"date-fns": "^4.1.0",
|
||||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.5.0",
|
||||
"express": "^5.1.0",
|
||||
|
|
@ -89,6 +90,7 @@
|
|||
"@semantic-release/github": "^11.0.3",
|
||||
"@semantic-release/npm": "^12.0.2",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@types/date-fns": "^2.5.3",
|
||||
"@types/diff": "^7.0.2",
|
||||
"@types/express": "^5.0.3",
|
||||
"@types/glob": "^8.1.0",
|
||||
|
|
|
|||
|
|
@ -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
129
src/commands/ls.test.ts
Normal 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();
|
||||
});
|
||||
});
|
||||
108
src/commands/ls.ts
Normal file
108
src/commands/ls.ts
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
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,
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
12
src/index.ts
12
src/index.ts
|
|
@ -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]")
|
||||
|
|
|
|||
117
src/session.ts
117
src/session.ts
|
|
@ -243,3 +243,120 @@ 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") {
|
||||
const content = chatHistory[i].content;
|
||||
// Handle both string and array content types
|
||||
if (typeof content === "string") {
|
||||
firstUserMessage = content;
|
||||
} else if (Array.isArray(content)) {
|
||||
// For array content, find the first text part
|
||||
const textPart = content.find((part) => part.type === "text");
|
||||
firstUserMessage = textPart?.text || "(multimodal message)";
|
||||
} else {
|
||||
firstUserMessage = "(unknown content type)";
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
127
src/ui/SessionSelector.test.tsx
Normal file
127
src/ui/SessionSelector.test.tsx
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
import {
|
||||
subDays,
|
||||
subMonths,
|
||||
subYears,
|
||||
startOfDay,
|
||||
addHours
|
||||
} from "date-fns";
|
||||
import { render } from "ink-testing-library";
|
||||
import React from "react";
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
|
||||
import type { SessionMetadata } from "../session.js";
|
||||
|
||||
import { SessionSelector } from "./SessionSelector.js";
|
||||
|
||||
describe("SessionSelector", () => {
|
||||
const mockOnSelect = vi.fn();
|
||||
const mockOnExit = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("formats timestamps correctly for different time periods", () => {
|
||||
const now = new Date();
|
||||
const today = addHours(startOfDay(now), 14); // 2 PM today
|
||||
const yesterday = subDays(today, 1);
|
||||
const thisWeek = subDays(today, 3); // 3 days ago (this week)
|
||||
const thisYear = subMonths(today, 2); // 2 months ago (this year)
|
||||
const lastYear = subYears(today, 1); // 1 year ago
|
||||
|
||||
const sessions: SessionMetadata[] = [
|
||||
{
|
||||
id: "session-1",
|
||||
path: "/test/session-1.json",
|
||||
timestamp: today,
|
||||
messageCount: 10,
|
||||
firstUserMessage: "Today's session",
|
||||
},
|
||||
{
|
||||
id: "session-2",
|
||||
path: "/test/session-2.json",
|
||||
timestamp: yesterday,
|
||||
messageCount: 5,
|
||||
firstUserMessage: "Yesterday's session",
|
||||
},
|
||||
{
|
||||
id: "session-3",
|
||||
path: "/test/session-3.json",
|
||||
timestamp: thisWeek,
|
||||
messageCount: 8,
|
||||
firstUserMessage: "This week's session",
|
||||
},
|
||||
{
|
||||
id: "session-4",
|
||||
path: "/test/session-4.json",
|
||||
timestamp: thisYear,
|
||||
messageCount: 12,
|
||||
firstUserMessage: "This year's session",
|
||||
},
|
||||
{
|
||||
id: "session-5",
|
||||
path: "/test/session-5.json",
|
||||
timestamp: lastYear,
|
||||
messageCount: 3,
|
||||
firstUserMessage: "Last year's session",
|
||||
},
|
||||
];
|
||||
|
||||
const { lastFrame } = render(
|
||||
<SessionSelector
|
||||
sessions={sessions}
|
||||
onSelect={mockOnSelect}
|
||||
onExit={mockOnExit}
|
||||
/>
|
||||
);
|
||||
|
||||
// Check that the output contains expected date formats
|
||||
expect(lastFrame()).toContain("2:00 PM"); // Today should show time
|
||||
expect(lastFrame()).toContain("yesterday"); // Yesterday should show "yesterday"
|
||||
|
||||
// This week should show day name (we can't predict exact day without knowing when test runs)
|
||||
// but we can check it doesn't contain "ago" which was the old format
|
||||
expect(lastFrame()).not.toContain("days ago");
|
||||
|
||||
// This year should show month/day format like "Oct 18" (no "ago")
|
||||
expect(lastFrame()).toMatch(/[A-Z][a-z]{2} \d{1,2}/); // MMM d format
|
||||
|
||||
// Last year should include the year
|
||||
expect(lastFrame()).toMatch(/[A-Z][a-z]{2} \d{1,2}, \d{4}/); // MMM d, yyyy format
|
||||
});
|
||||
|
||||
it("handles empty sessions gracefully", () => {
|
||||
const { lastFrame } = render(
|
||||
<SessionSelector
|
||||
sessions={[]}
|
||||
onSelect={mockOnSelect}
|
||||
onExit={mockOnExit}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(lastFrame()).toContain("No previous sessions found");
|
||||
expect(lastFrame()).toContain("Start a new conversation with: cn");
|
||||
});
|
||||
|
||||
it("handles sessions without first user message", () => {
|
||||
const sessions: SessionMetadata[] = [
|
||||
{
|
||||
id: "session-1",
|
||||
path: "/test/session-1.json",
|
||||
timestamp: new Date(),
|
||||
messageCount: 0,
|
||||
firstUserMessage: undefined,
|
||||
},
|
||||
];
|
||||
|
||||
const { lastFrame } = render(
|
||||
<SessionSelector
|
||||
sessions={sessions}
|
||||
onSelect={mockOnSelect}
|
||||
onExit={mockOnExit}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(lastFrame()).toContain("(no messages)");
|
||||
});
|
||||
});
|
||||
118
src/ui/SessionSelector.tsx
Normal file
118
src/ui/SessionSelector.tsx
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
import { format, isToday, isYesterday, isThisWeek, isThisYear } from "date-fns";
|
||||
import { Box, Text, useInput } from "ink";
|
||||
import React, { useMemo, useState } from "react";
|
||||
|
||||
import { SessionMetadata } from "../session.js";
|
||||
|
||||
import { useTerminalSize } from "./hooks/useTerminalSize.js";
|
||||
|
||||
interface SessionSelectorProps {
|
||||
sessions: SessionMetadata[];
|
||||
onSelect: (sessionId: string) => void;
|
||||
onExit: () => void;
|
||||
}
|
||||
|
||||
function formatTimestamp(date: Date): string {
|
||||
if (isToday(date)) {
|
||||
return format(date, "h:mm a");
|
||||
} else if (isYesterday(date)) {
|
||||
return "yesterday";
|
||||
} else if (isThisWeek(date)) {
|
||||
return format(date, "EEEE"); // Day name (e.g., "Monday")
|
||||
} else if (isThisYear(date)) {
|
||||
return format(date, "MMM d"); // e.g., "Jan 15"
|
||||
} else {
|
||||
return format(date, "MMM d, yyyy"); // e.g., "Jan 15, 2023"
|
||||
}
|
||||
}
|
||||
|
||||
function formatMessage(message: string | undefined): string {
|
||||
if (!message) return "(no messages)";
|
||||
// Ensure we're working with a string, handle edge cases from persisted data
|
||||
const messageStr = typeof message === "string" ? message : String(message);
|
||||
return messageStr.split("\n")[0];
|
||||
}
|
||||
|
||||
export function SessionSelector({
|
||||
sessions,
|
||||
onSelect,
|
||||
onExit,
|
||||
}: SessionSelectorProps) {
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const { rows: terminalHeight } = useTerminalSize();
|
||||
|
||||
// Calculate how many sessions we can display based on terminal height
|
||||
const displaySessions = useMemo(() => {
|
||||
// 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, terminalHeight]);
|
||||
|
||||
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.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}{" "}
|
||||
{session.messageCount === 1 ? "message" : "messages"}
|
||||
</Text>
|
||||
</Box>
|
||||
{index < displaySessions.length - 1 && (
|
||||
<Text key={`spacer-${session.id}`}> </Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue