From 40a0eb6b2afc76d3fc3c752065a800dd17c74aff Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 18 Aug 2025 09:10:57 -0700 Subject: [PATCH 1/4] Add `cn ls` command with TUI session selector and JSON output --- README.md | 21 ++++++ src/commands/commands.ts | 8 ++ src/commands/ls.test.ts | 129 ++++++++++++++++++++++++++++++++ src/commands/ls.ts | 95 +++++++++++++++++++++++ src/index.ts | 12 +++ src/session.ts | 104 +++++++++++++++++++++++++ src/ui/SessionSelector.test.tsx | 96 ++++++++++++++++++++++++ src/ui/SessionSelector.tsx | 120 +++++++++++++++++++++++++++++ 8 files changed, 585 insertions(+) create mode 100644 src/commands/ls.test.ts create mode 100644 src/commands/ls.ts create mode 100644 src/ui/SessionSelector.test.tsx create mode 100644 src/ui/SessionSelector.tsx diff --git a/README.md b/README.md index 9353a6c6f..9f12eada0 100644 --- a/README.md +++ b/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 `: Specify agent configuration path - `--resume`: Resume the last session for this terminal - ``: 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) diff --git a/src/commands/commands.ts b/src/commands/commands.ts index 026399160..0f34bcf9c 100644 --- a/src/commands/commands.ts +++ b/src/commands/commands.ts @@ -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; diff --git a/src/commands/ls.test.ts b/src/commands/ls.test.ts new file mode 100644 index 000000000..547fe2f42 --- /dev/null +++ b/src/commands/ls.test.ts @@ -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(); + }); +}); \ No newline at end of file diff --git a/src/commands/ls.ts b/src/commands/ls.ts new file mode 100644 index 000000000..babb2b6b9 --- /dev/null +++ b/src/commands/ls.ts @@ -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 { + // 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((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, + }) + ); + }); +} \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index b5155eaa7..233e8038f 100644 --- a/src/index.ts +++ b/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]") diff --git a/src/session.ts b/src/session.ts index b75417dff..1f349418f 100644 --- a/src/session.ts +++ b/src/session.ts @@ -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; + } +} diff --git a/src/ui/SessionSelector.test.tsx b/src/ui/SessionSelector.test.tsx new file mode 100644 index 000000000..795c6f054 --- /dev/null +++ b/src/ui/SessionSelector.test.tsx @@ -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( + + ); + + 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( + + ); + + 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( + + ); + + 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; + }); +}); \ No newline at end of file diff --git a/src/ui/SessionSelector.tsx b/src/ui/SessionSelector.tsx new file mode 100644 index 000000000..7f0ac8103 --- /dev/null +++ b/src/ui/SessionSelector.tsx @@ -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 ( + + No previous sessions found. + Start a new conversation with: cn + Press ESC to exit + + ); + } + + return ( + + + Recent Sessions + + + Use ↑↓ arrows to navigate, Enter to select, ESC to exit + + + + {displaySessions.map((session, index) => { + const isSelected = index === selectedIndex; + const indicator = isSelected ? "► " : " "; + const color = isSelected ? "cyan" : "white"; + + return ( + + + + {indicator} + {formatMessage(session.firstUserMessage)} + + + + + {formatTimestamp(session.timestamp)} - {session.messageCount}{" "} + messages + + + {index < displaySessions.length - 1 && ( + + )} + + ); + })} + + ); +} From 5f51a5b014321f9e7cdbcd92049ac09a70b432b3 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 18 Aug 2025 09:14:27 -0700 Subject: [PATCH 2/4] fix: lint --- src/commands/ls.ts | 53 +++++++++++++++++++++++++++++----------------- src/index.ts | 4 ++-- src/session.ts | 47 +++++++++++++++++++++------------------- 3 files changed, 60 insertions(+), 44 deletions(-) diff --git a/src/commands/ls.ts b/src/commands/ls.ts index babb2b6b9..8558c3057 100644 --- a/src/commands/ls.ts +++ b/src/commands/ls.ts @@ -17,33 +17,46 @@ interface ListSessionsOptions { */ function setSessionId(sessionId: string): void { // Use the same environment variable that getSessionId() checks - process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace('continue-cli-', ''); + 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 { +export async function listSessionsCommand( + options: ListSessionsOptions = {}, +): Promise { // 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)); + 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"); + console.log( + "No previous sessions found. Start a new conversation with: cn", + ); return; } @@ -52,7 +65,7 @@ export async function listSessionsCommand(options: ListSessionsOptions = {}): Pr const handleSelect = async (sessionId: string) => { try { app.unmount(); - + // Verify the session exists before trying to load it const sessionHistory = loadSessionById(sessionId); if (!sessionHistory) { @@ -60,18 +73,18 @@ export async function listSessionsCommand(options: ListSessionsOptions = {}): Pr 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, { + await chat(undefined, { resume: true, - headless: false + headless: false, }); - + resolve(); } catch (error) { logger.error("Error loading session:", error); @@ -89,7 +102,7 @@ export async function listSessionsCommand(options: ListSessionsOptions = {}): Pr sessions, onSelect: handleSelect, onExit: handleExit, - }) + }), ); }); -} \ No newline at end of file +} diff --git a/src/index.ts b/src/index.ts index 233e8038f..aabd18629 100644 --- a/src/index.ts +++ b/src/index.ts @@ -155,8 +155,8 @@ program .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 + await listSessionsCommand({ + format: options.json ? "json" : undefined, }); }); diff --git a/src/session.ts b/src/session.ts index 1f349418f..8293fcaeb 100644 --- a/src/session.ts +++ b/src/session.ts @@ -248,10 +248,10 @@ export function hasSession(): boolean { * 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 + 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 } @@ -260,27 +260,27 @@ export interface SessionMetadata { */ function getSessionMetadata(filePath: string): SessionMetadata | null { try { - const fileName = path.basename(filePath, '.json'); + 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') { + if (chatHistory[i].role === "user") { firstUserMessage = chatHistory[i].content; break; } } - + // Use session timestamp if available, otherwise file modification time - const timestamp = sessionData.timestamp + const timestamp = sessionData.timestamp ? new Date(sessionData.timestamp) : stats.mtime; - + return { id: fileName, path: filePath, @@ -300,24 +300,25 @@ function getSessionMetadata(filePath: string): SessionMetadata | null { 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 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()) @@ -331,15 +332,17 @@ export function listSessions(limit: number = 10): SessionMetadata[] { /** * Load chat history from a specific session file */ -export function loadSessionById(sessionId: string): ChatCompletionMessageParam[] | null { +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) { From 83d218c0f830db7c43380d9928a478ce0893b9f1 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 18 Aug 2025 09:15:01 -0700 Subject: [PATCH 3/4] fix: tests --- src/ui/SessionSelector.test.tsx | 37 --------------------------------- 1 file changed, 37 deletions(-) diff --git a/src/ui/SessionSelector.test.tsx b/src/ui/SessionSelector.test.tsx index 795c6f054..52141c65c 100644 --- a/src/ui/SessionSelector.test.tsx +++ b/src/ui/SessionSelector.test.tsx @@ -56,41 +56,4 @@ describe("SessionSelector", () => { 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( - - ); - - 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; - }); }); \ No newline at end of file From b849203ab360d2b367ab350ed70a20039dd7be8c Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 18 Aug 2025 10:28:44 -0700 Subject: [PATCH 4/4] feat: improve timestamps --- package-lock.json | 19 +++++ package.json | 2 + src/session.ts | 12 ++- src/ui/SessionSelector.test.tsx | 138 ++++++++++++++++++++++++-------- src/ui/SessionSelector.tsx | 40 +++++---- 5 files changed, 154 insertions(+), 57 deletions(-) diff --git a/package-lock.json b/package-lock.json index 6b4d28695..67b6cba48 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index 9afa73798..a09595a64 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/session.ts b/src/session.ts index 8293fcaeb..630b1a0ef 100644 --- a/src/session.ts +++ b/src/session.ts @@ -271,7 +271,17 @@ function getSessionMetadata(filePath: string): SessionMetadata | null { let firstUserMessage: string | undefined; for (let i = 0; i < chatHistory.length; i++) { if (chatHistory[i].role === "user") { - firstUserMessage = chatHistory[i].content; + 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; } } diff --git a/src/ui/SessionSelector.test.tsx b/src/ui/SessionSelector.test.tsx index 52141c65c..adf48807c 100644 --- a/src/ui/SessionSelector.test.tsx +++ b/src/ui/SessionSelector.test.tsx @@ -1,59 +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 } from "vitest"; +import { describe, expect, it, vi, beforeEach } from "vitest"; -import { SessionMetadata } from "../session.js"; +import type { 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", - }, - ]; + const mockOnSelect = vi.fn(); + const mockOnExit = vi.fn(); - it("should render sessions with first user message", () => { - const onSelect = vi.fn(); - const onExit = 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( - ); - expect(lastFrame()).toContain("Hello world"); - expect(lastFrame()).toContain("Test message"); - expect(lastFrame()).toContain("Recent Sessions"); + // 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("should handle empty sessions", () => { - const onSelect = vi.fn(); - const onExit = vi.fn(); - + it("handles empty sessions gracefully", () => { const { lastFrame } = render( - ); 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( + + ); + + expect(lastFrame()).toContain("(no messages)"); + }); }); \ No newline at end of file diff --git a/src/ui/SessionSelector.tsx b/src/ui/SessionSelector.tsx index 7f0ac8103..4e085f197 100644 --- a/src/ui/SessionSelector.tsx +++ b/src/ui/SessionSelector.tsx @@ -1,8 +1,11 @@ +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; @@ -10,29 +13,24 @@ interface SessionSelectorProps { } 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) { + if (isToday(date)) { + return format(date, "h:mm a"); + } else if (isYesterday(date)) { return "yesterday"; - } else if (diffDays < 7) { - return `${diffDays} days ago`; + } 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 date.toLocaleDateString(); + return format(date, "MMM d, yyyy"); // e.g., "Jan 15, 2023" } } 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; + // 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({ @@ -41,16 +39,16 @@ export function SessionSelector({ 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(() => { - 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]); + }, [sessions, terminalHeight]); useInput((input, key) => { if (key.upArrow || input === "k") { @@ -96,7 +94,7 @@ export function SessionSelector({ const color = isSelected ? "cyan" : "white"; return ( - + {indicator} @@ -106,11 +104,11 @@ export function SessionSelector({ {formatTimestamp(session.timestamp)} - {session.messageCount}{" "} - messages + {session.messageCount === 1 ? "message" : "messages"} {index < displaySessions.length - 1 && ( - + )} );