From 7d1bb9885fff1e2ca7ff53aa6fdb5f621ebddf09 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 13 Aug 2025 15:19:07 -0700 Subject: [PATCH 01/15] chore: remove jest --- .../continue-sdk-cli-and-hub-context.yaml | 2 +- .npmignore | 2 +- .vscode/launch.json | 10 +-- AGENTS.md | 6 +- eslint.config.js | 1 - jest.config.mjs | 78 ------------------- jest.resolver.cjs | 53 ------------- jest.resolver.js | 31 -------- jest.setup.ts | 42 ---------- spec/testing-strategies.md | 14 ++-- src/slashCommands.modes.test.ts | 2 +- src/test-helpers/ui-test-context.ts | 3 - src/tools/runTerminalCommand.test.ts | 8 +- src/ui/TUIChat.test.tsx | 2 +- src/ui/__tests__/TUIChat.dualModeHelper.tsx | 2 +- src/ui/__tests__/TUIChat.setup.ts | 2 +- src/ui/__tests__/TUIChat.testHelper.ts | 2 +- src/ui/__tests__/mockRemoteServer.ts | 2 +- 18 files changed, 26 insertions(+), 236 deletions(-) delete mode 100644 jest.config.mjs delete mode 100644 jest.resolver.cjs delete mode 100644 jest.resolver.js delete mode 100644 jest.setup.ts diff --git a/.continue/rules/continue-sdk-cli-and-hub-context.yaml b/.continue/rules/continue-sdk-cli-and-hub-context.yaml index 3041db0be..a71e68275 100644 --- a/.continue/rules/continue-sdk-cli-and-hub-context.yaml +++ b/.continue/rules/continue-sdk-cli-and-hub-context.yaml @@ -29,7 +29,7 @@ rules: - readline-sync: Provides synchronous CLI user interactions - - Jest: Used for testing framework + - Vitest: Used for testing framework All code should follow established patterns for a Node.js CLI tool diff --git a/.npmignore b/.npmignore index bdce176fe..e65f2a02b 100644 --- a/.npmignore +++ b/.npmignore @@ -5,7 +5,7 @@ test .continue .releaserc.json AGENTS.md -jest.config.mjs +vitest.config.ts tsconfig.json tsconfig.build.json TESTING_STRATEGY.md diff --git a/.vscode/launch.json b/.vscode/launch.json index 884a92f91..07d82ce2a 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -24,16 +24,14 @@ ], "preLaunchTask": "watch-logs" }, - - { + { "name": "Debug Tests", "type": "node", "request": "launch", - "program": "${workspaceFolder}/node_modules/.bin/jest", - "args": ["--runInBand", "--no-cache"], + "program": "${workspaceFolder}/node_modules/.bin/vitest", + "args": ["--run", "--no-cache"], "env": { - "NODE_ENV": "test", - "NODE_OPTIONS": "--experimental-vm-modules" + "NODE_ENV": "test" }, "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", diff --git a/AGENTS.md b/AGENTS.md index 577362695..bfe1f0d39 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,7 +5,7 @@ This file provides guidance to AI coding agents when working with code in this r ## Development Commands - **Build**: `npm run build` - Compiles TypeScript to JavaScript in dist/ -- **Test**: `npm test` - Runs Jest tests with ESM support +- **Test**: `npm test` - Runs Vitest tests with ESM support - **Type Check**: `npm run lint` - Runs TypeScript compiler without emitting files for type checking - **Format**: `npm run format` - Runs Prettier with --write flag to check + fix formatting - **Start**: `npm start` - Runs the built CLI from dist/index.js @@ -54,8 +54,8 @@ This is a CLI tool for Continue Dev that provides an interactive AI-assisted dev ### Testing Setup -- Uses Jest with TypeScript and ESM support -- Configuration in `jest.config.mjs` +- Uses Vitest with TypeScript and ESM support +- Configuration in `vitest.config.ts` - Tests should be written with `.test.ts` extension - No existing test files found - tests should be added when writing new functionality - Run tests using `npm run test path/or/pattern` diff --git a/eslint.config.js b/eslint.config.js index 1481e9d99..f632d8e68 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -178,7 +178,6 @@ export default [ "coverage/**", "*.d.ts", "src/__mocks__/**", - "jest.setup.ts", "vitest.config.ts", "*.config.js", "*.config.ts", diff --git a/jest.config.mjs b/jest.config.mjs deleted file mode 100644 index 4fe2dc338..000000000 --- a/jest.config.mjs +++ /dev/null @@ -1,78 +0,0 @@ -import path from "path"; -import { fileURLToPath } from "url"; - -export default { - transform: { - "\\.[jt]sx?$": ["ts-jest", { useESM: true }], - }, - - moduleNameMapper: { - "^(\\.{1,2}/.+)\\.js$": "$1", - "^highlight\\.js/lib/languages/(.+)$": - "/src/ui/__mocks__/highlightLanguage.js", - "^lowlight$": "/src/ui/__mocks__/lowlight.js", - "^ink-testing-library$": - "/node_modules/ink-testing-library/build/index.js", - "^./SyntaxHighlighter\\.js$": - "/src/ui/__mocks__/SyntaxHighlighter.ts", - "^./FreeTrialStatus\\.js$": - "/src/ui/__mocks__/FreeTrialStatus.tsx", - }, - extensionsToTreatAsEsm: [".ts", ".tsx"], - preset: "ts-jest/presets/default-esm", - testTimeout: 10000, - testEnvironment: "node", - testPathIgnorePatterns: ["/dist/"], - modulePathIgnorePatterns: ["/dist/"], - transformIgnorePatterns: ["node_modules/(?!(highlight.js|lowlight)/)"], - setupFilesAfterEnv: ["/jest.setup.ts"], - globals: { - __dirname: path.dirname(fileURLToPath(import.meta.url)), - __filename: path.resolve(fileURLToPath(import.meta.url)), - }, - resolver: "/jest.resolver.cjs", - // Force E2E tests to run sequentially to avoid console override conflicts - projects: [ - { - displayName: "e2e", - testMatch: ["/src/e2e/**/*.test.ts"], - maxWorkers: 1, - transform: { - "\\.[jt]sx?$": ["ts-jest", { useESM: true }], - }, - moduleNameMapper: { - "^(\\.{1,2}/.+)\\.js$": "$1", - }, - extensionsToTreatAsEsm: [".ts", ".tsx"], - preset: "ts-jest/presets/default-esm", - testEnvironment: "node", - setupFilesAfterEnv: ["/jest.setup.ts"], - resolver: "/jest.resolver.cjs", - }, - { - displayName: "unit", - testMatch: ["/src/**/*.test.{ts,tsx}"], - testPathIgnorePatterns: ["/src/e2e/"], - transform: { - "\\.[jt]sx?$": ["ts-jest", { useESM: true }], - }, - moduleNameMapper: { - "^(\\.{1,2}/.+)\\.js$": "$1", - "^highlight\\.js/lib/languages/(.+)$": - "/src/ui/__mocks__/highlightLanguage.js", - "^lowlight$": "/src/ui/__mocks__/lowlight.js", - "^ink-testing-library$": - "/node_modules/ink-testing-library/build/index.js", - "^./SyntaxHighlighter\\.js$": - "/src/ui/__mocks__/SyntaxHighlighter.ts", - "^./FreeTrialStatus\\.js$": - "/src/ui/__mocks__/FreeTrialStatus.tsx", - }, - extensionsToTreatAsEsm: [".ts", ".tsx"], - preset: "ts-jest/presets/default-esm", - testEnvironment: "node", - setupFilesAfterEnv: ["/jest.setup.ts"], - resolver: "/jest.resolver.cjs", - }, - ], -}; diff --git a/jest.resolver.cjs b/jest.resolver.cjs deleted file mode 100644 index ac9db7768..000000000 --- a/jest.resolver.cjs +++ /dev/null @@ -1,53 +0,0 @@ -// Custom resolver for Jest to handle .js extensions in ESM project -const path = require("path"); -const fs = require("fs"); - -module.exports = (request, options) => { - // Call the default resolver - const defaultResolver = options.defaultResolver; - - // First try the default resolver - try { - return defaultResolver(request, options); - } catch (e) { - // Only continue if module not found - if (!e.message || !e.message.includes("Cannot find module")) { - throw e; - } - } - - // Handle relative imports - if (request.startsWith(".")) { - const basePath = options.basedir; - const fullPath = path.resolve(basePath, request); - - // Try various extensions - const extensions = ["", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"]; - - for (const ext of extensions) { - const testPath = fullPath + ext; - try { - if (fs.existsSync(testPath)) { - return defaultResolver(testPath, options); - } - } catch (e) { - // Continue to next extension - } - } - - // Also try adding /index with various extensions - for (const ext of extensions) { - const testPath = path.join(fullPath, "index" + ext); - try { - if (fs.existsSync(testPath)) { - return defaultResolver(testPath, options); - } - } catch (e) { - // Continue to next extension - } - } - } - - // If still not found, throw original error - throw new Error(`Cannot find module '${request}'`); -}; diff --git a/jest.resolver.js b/jest.resolver.js deleted file mode 100644 index 1e053f75d..000000000 --- a/jest.resolver.js +++ /dev/null @@ -1,31 +0,0 @@ -module.exports = (path, options) => { - // Call the default resolver - const resolver = options.defaultResolver; - - try { - // Try to resolve the path as-is first - return resolver(path, options); - } catch (error) { - // If the path ends with .js and resolution fails, try without the extension - if (path.endsWith(".js")) { - const pathWithoutJs = path.slice(0, -3); - try { - return resolver(pathWithoutJs, options); - } catch { - // If that also fails, try with .ts extension - try { - return resolver(pathWithoutJs + ".ts", options); - } catch { - // If that also fails, try with .tsx extension - try { - return resolver(pathWithoutJs + ".tsx", options); - } catch { - // If all attempts fail, throw the original error - throw error; - } - } - } - } - throw error; - } -}; diff --git a/jest.setup.ts b/jest.setup.ts deleted file mode 100644 index 64ae4e9ad..000000000 --- a/jest.setup.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { jest } from "@jest/globals"; -import { resetConsoleOverrides } from "./src/util/consoleOverride.js"; - -// Disable telemetry for tests -process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0"; - -// Mock the 'open' package to prevent browser opening during tests -jest.mock("open", () => jest.fn().mockResolvedValue(undefined)); - -// Mock common modules that cause issues -jest.mock("./src/logging.js"); -jest.mock("./src/util/logger.js"); -jest.mock("./src/hooks/useService.js"); -jest.mock("./src/auth/workos.js"); -jest.mock("./src/commands/commands.js"); -jest.mock("./src/services/index.js"); -jest.mock("./src/services/ServiceContainerContext.js"); -jest.mock("./src/config.js"); -jest.mock("./src/configLoader.js"); -jest.mock("./src/args.js"); -jest.mock("./src/services/ServiceContainer.js"); -jest.mock("./src/permissions/permissionsYamlLoader.js"); -jest.mock("./src/permissions/precedenceResolver.js"); - -// Set up global afterEach hook to clear all timers and reset console -afterEach(() => { - // Clear jest timers only if they're available - if (typeof jest !== "undefined" && jest.clearAllTimers) { - try { - jest.clearAllTimers(); - } catch (e) { - // Ignore errors when clearing timers - } - } - - // Reset console overrides to ensure clean state for each test - try { - resetConsoleOverrides(); - } catch (e) { - // Ignore errors when resetting console - } -}); diff --git a/spec/testing-strategies.md b/spec/testing-strategies.md index 39f7ab16f..b0a390e5e 100644 --- a/spec/testing-strategies.md +++ b/spec/testing-strategies.md @@ -15,7 +15,7 @@ This document provides an overview of the different testing strategies used in t - Testing business logic components - Testing error handling and edge cases -**Framework**: Jest with TypeScript support +**Framework**: Vitest with TypeScript support **Examples**: @@ -54,7 +54,7 @@ This document provides an overview of the different testing strategies used in t - Testing component state changes - Testing message display and formatting -**Framework**: Jest + Ink Testing Library + React Testing utilities +**Framework**: Vitest + Ink Testing Library + React Testing utilities **Examples**: @@ -112,7 +112,7 @@ This document provides an overview of the different testing strategies used in t ## Configuration -**Jest Configuration**: [`jest.config.mjs`](../jest.config.mjs) +**Vitest Configuration**: [`vitest.config.ts`](../vitest.config.ts) - TypeScript support with ES modules - React/Ink component testing setup @@ -125,14 +125,14 @@ This document provides an overview of the different testing strategies used in t # Run all tests with linting npm test -# Run tests in watch mode (Jest only) -npx jest --watch +# Run tests in watch mode +npx vitest --watch # Run specific test file -npx jest src/util/formatError.test.ts +npx vitest src/util/formatError.test.ts # Run tests with coverage -npx jest --coverage +npx vitest --coverage ``` ## Best Practices diff --git a/src/slashCommands.modes.test.ts b/src/slashCommands.modes.test.ts index c791ef1da..c6f227f4c 100644 --- a/src/slashCommands.modes.test.ts +++ b/src/slashCommands.modes.test.ts @@ -1,5 +1,5 @@ // Mode-related slash commands have been removed per user request -// This test file is no longer needed but needs a dummy test for Jest +// This test file is no longer needed but needs a dummy test for Vitest import { describe, it, expect } from 'vitest'; diff --git a/src/test-helpers/ui-test-context.ts b/src/test-helpers/ui-test-context.ts index 092f16098..8b979d13d 100644 --- a/src/test-helpers/ui-test-context.ts +++ b/src/test-helpers/ui-test-context.ts @@ -78,9 +78,6 @@ export function createUITestContext( setMaxListeners: vi.fn(), }; - // Note: Jest mocks need to be hoisted, so they can't be called inside functions - // The actual mocking should be done at the top of test files - const cleanup = () => { vi.clearAllMocks(); }; diff --git a/src/tools/runTerminalCommand.test.ts b/src/tools/runTerminalCommand.test.ts index 7b037c802..30a0d8557 100644 --- a/src/tools/runTerminalCommand.test.ts +++ b/src/tools/runTerminalCommand.test.ts @@ -78,7 +78,7 @@ describe("runTerminalCommandTool", () => { expect(elapsed).toBeLessThan(TEST_TIMEOUT_MS + 200); // Allow 200ms margin expect(elapsed).toBeGreaterThan(TEST_TIMEOUT_MS - 100); // Allow 100ms margin expect(result).toContain(`[Command timed out after ${TEST_TIMEOUT_MS / 1000} seconds of no output]`); - }, TEST_TIMEOUT_MS + 2000); // Set Jest timeout with buffer + }, TEST_TIMEOUT_MS + 2000); // Set test timeout with buffer it("should not timeout commands that continuously produce output", async () => { // Create a command that produces output at intervals shorter than timeout @@ -95,7 +95,7 @@ describe("runTerminalCommandTool", () => { expect(result).toContain("output 1"); expect(result).toContain(`output ${iterations}`); expect(result).not.toContain("[Command timed out"); - }, TEST_TIMEOUT_MS * 3); // Set Jest timeout with buffer + }, TEST_TIMEOUT_MS * 3); // Set test timeout with buffer it("should reset timeout when command produces stderr output", async () => { // Create a command that produces stderr output periodically @@ -112,7 +112,7 @@ describe("runTerminalCommandTool", () => { expect(result).toContain("done"); expect(result).toContain("Stderr: error 1"); expect(result).not.toContain("[Command timed out"); - }, TEST_TIMEOUT_MS * 3); // Set Jest timeout with buffer + }, TEST_TIMEOUT_MS * 3); // Set test timeout with buffer it("should include partial output when timing out", async () => { // Create a command that produces some output then stops @@ -123,7 +123,7 @@ describe("runTerminalCommandTool", () => { expect(result).toContain("initial output"); expect(result).toContain(`[Command timed out after ${TEST_TIMEOUT_MS / 1000} seconds of no output]`); - }, TEST_TIMEOUT_MS + 2000); // Set Jest timeout with buffer + }, TEST_TIMEOUT_MS + 2000); // Set test timeout with buffer }); describe("output handling", () => { diff --git a/src/ui/TUIChat.test.tsx b/src/ui/TUIChat.test.tsx index a30b2f3dc..ba4ca2b3b 100644 --- a/src/ui/TUIChat.test.tsx +++ b/src/ui/TUIChat.test.tsx @@ -5,7 +5,7 @@ import "./__tests__/TUIChat.input.test.js"; import "./__tests__/TUIChat.fileSearch.test.js"; import "./__tests__/TUIChat.slashCommands.test.js"; -// Add a dummy test to satisfy Jest +// Add a dummy test to satisfy Vitest describe("TUIChat Test Suite", () => { it("should import all test modules", () => { expect(true).toBe(true); diff --git a/src/ui/__tests__/TUIChat.dualModeHelper.tsx b/src/ui/__tests__/TUIChat.dualModeHelper.tsx index 3b5021ab0..a62b235e8 100644 --- a/src/ui/__tests__/TUIChat.dualModeHelper.tsx +++ b/src/ui/__tests__/TUIChat.dualModeHelper.tsx @@ -6,7 +6,7 @@ import { AppRoot } from "../AppRoot.js"; export type TestMode = "local" | "remote"; -// Dummy test to satisfy Jest +// Dummy test to satisfy Vitest describe("TUIChat dual mode helper", () => { it("exports helper functions", () => { expect(testBothModes).toBeDefined(); diff --git a/src/ui/__tests__/TUIChat.setup.ts b/src/ui/__tests__/TUIChat.setup.ts index 6ac658ad3..dcb9678a0 100644 --- a/src/ui/__tests__/TUIChat.setup.ts +++ b/src/ui/__tests__/TUIChat.setup.ts @@ -54,7 +54,7 @@ export const createProps = (overrides: any = {}) => ({ ...overrides, }); -// Add a dummy test to satisfy Jest requirement +// Add a dummy test to satisfy Vitest requirement describe("TUIChat setup", () => { test("setup should export required functions", () => { expect(createProps).toBeDefined(); diff --git a/src/ui/__tests__/TUIChat.testHelper.ts b/src/ui/__tests__/TUIChat.testHelper.ts index 2c2cc1e3b..8a0fd9289 100644 --- a/src/ui/__tests__/TUIChat.testHelper.ts +++ b/src/ui/__tests__/TUIChat.testHelper.ts @@ -54,7 +54,7 @@ export function runTest( modes.forEach((testMode) => { describe(`[${testMode.toUpperCase()} MODE]`, () => { it(name, async () => { - // Import mocks from Jest setup + // Import mocks from Vitest setup const { useServices, useService } = await import( "../../hooks/useService.js" ); diff --git a/src/ui/__tests__/mockRemoteServer.ts b/src/ui/__tests__/mockRemoteServer.ts index 3831b75eb..fef90966c 100644 --- a/src/ui/__tests__/mockRemoteServer.ts +++ b/src/ui/__tests__/mockRemoteServer.ts @@ -159,7 +159,7 @@ export class MockRemoteServer { } } -// Add a dummy test to satisfy Jest requirement +// Add a dummy test to satisfy Vitest requirement describe("MockRemoteServer", () => { test("should be defined", () => { expect(MockRemoteServer).toBeDefined(); From 9f44602f65cf786d9d81e531a2295d94c2ee9093 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 18 Aug 2025 08:34:09 -0700 Subject: [PATCH 02/15] =?UTF-8?q?feat:=20add=20context=20percentage=20disp?= =?UTF-8?q?lay=20to=20status=20bar=20=20=F0=9F=A4=96=20Generated=20with=20?= =?UTF-8?q?[Claude=20Code](https://claude.ai/code)=20=20Co-Authored-By:=20?= =?UTF-8?q?Claude=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ui/TUIChat.tsx | 391 ++---------------- src/ui/components/BottomStatusBar.tsx | 70 ++++ .../components/ContextPercentageDisplay.tsx | 22 + src/ui/components/ScreenContent.tsx | 158 +++++++ src/ui/hooks/useContextPercentage.ts | 41 ++ src/ui/hooks/useTUIChatHooks.ts | 148 +++++++ src/ui/types/selectorTypes.ts | 15 + 7 files changed, 480 insertions(+), 365 deletions(-) create mode 100644 src/ui/components/BottomStatusBar.tsx create mode 100644 src/ui/components/ContextPercentageDisplay.tsx create mode 100644 src/ui/components/ScreenContent.tsx create mode 100644 src/ui/hooks/useContextPercentage.ts create mode 100644 src/ui/hooks/useTUIChatHooks.ts create mode 100644 src/ui/types/selectorTypes.ts diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 2660620f7..9c037d111 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -1,9 +1,7 @@ import { Box, Text } from "ink"; -import React, { useCallback, useEffect, useMemo, useState } from "react"; +import React, { useEffect, useMemo } from "react"; import { useServices } from "../hooks/useService.js"; -import type { PermissionMode } from "../permissions/types.js"; -import { modeService } from "../services/ModeService.js"; import { ApiClientServiceState, AuthServiceState, @@ -11,174 +9,24 @@ import { MCPServiceState, ModelServiceState, } from "../services/types.js"; -import { getGitRemoteUrl, isGitRepo } from "../util/git.js"; -import { ModeIndicator } from "./components/ModeIndicator.js"; +import { BottomStatusBar } from "./components/BottomStatusBar.js"; +import { ScreenContent } from "./components/ScreenContent.js"; import { StaticChatContent } from "./components/StaticChatContent.js"; -import { ToolPermissionSelector } from "./components/ToolPermissionSelector.js"; -import { ConfigSelector } from "./ConfigSelector.js"; -import { - useNavigation, - type NavigationScreen, -} from "./context/NavigationContext.js"; +import { useNavigation } from "./context/NavigationContext.js"; import { startFileIndexing } from "./FileSearchUI.js"; -import { FreeTrialStatus } from "./FreeTrialStatus.js"; -import { FreeTrialTransitionUI } from "./FreeTrialTransitionUI.js"; import { useChat } from "./hooks/useChat.js"; -import { useConfigSelector } from "./hooks/useConfigSelector.js"; +import { useContextPercentage } from "./hooks/useContextPercentage.js"; import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; -import { useModelSelector } from "./hooks/useModelSelector.js"; -import { useOrganizationSelector } from "./hooks/useOrganizationSelector.js"; +import { + getRepoUrlText, + useCurrentMode, + useIntroMessage, + useLoginHandlers, + useSelectors, +} from "./hooks/useTUIChatHooks.js"; import { LoadingAnimation } from "./LoadingAnimation.js"; -import { MCPSelector } from "./MCPSelector.js"; -import { ModelSelector } from "./ModelSelector.js"; -import { OrganizationSelector } from "./OrganizationSelector.js"; -import type { SelectorOption } from "./Selector.js"; import { Timer } from "./Timer.js"; -import { UpdateNotification } from "./UpdateNotification.js"; -import { UserInput } from "./UserInput.js"; - -// Type definitions for selectors -interface ConfigOption extends SelectorOption { - type: "local" | "assistant" | "create"; - slug?: string; -} - -interface ModelOption extends SelectorOption { - index: number; - provider: string; -} - -// Helper function to get repo URL text -function getRepoUrlText(remoteUrl?: string): string { - let url = remoteUrl ?? ""; - if (!url) { - const isGit = isGitRepo(); - if (isGit) { - const gitUrl = getGitRemoteUrl(); - if (gitUrl) { - url = gitUrl; - } - } - } - if (!url) { - url = process.cwd(); - } - - url = url.replace(/\.git$/, ""); - url = url.replace(/^(https|http):\/\/.*?\//, ""); - return url; -} - -// Custom hook for intro message -function useIntroMessage( - isRemoteMode: boolean, - services: any, - allServicesReady: boolean, -) { - const [showIntroMessage, setShowIntroMessage] = useState(false); - - useEffect(() => { - const shouldShow = - !isRemoteMode && - allServicesReady && - !!services.config?.config && - !!services.model?.model && - !!services.mcp?.mcpService; - - setShowIntroMessage(shouldShow); - }, [ - isRemoteMode, - allServicesReady, - services.config?.config, - services.model?.model, - services.mcp?.mcpService, - ]); - - return [showIntroMessage, setShowIntroMessage] as const; -} - -// Custom hook for login handling -function useLoginHandlers( - navigateTo: any, - navState: any, - closeCurrentScreen: () => void, -) { - const handleLoginPrompt = useCallback( - (promptText: string): Promise => { - return new Promise((resolve) => { - navigateTo("login", { text: promptText, resolve }); - }); - }, - [navigateTo], - ); - - const handleLoginTokenSubmit = useCallback( - (token: string) => { - if (navState.screenData?.resolve) { - navState.screenData.resolve(token); - closeCurrentScreen(); - } - }, - [navState.screenData, closeCurrentScreen], - ); - - return { handleLoginPrompt, handleLoginTokenSubmit }; -} - -// Custom hook for mode tracking -function useCurrentMode() { - const [currentMode, setCurrentMode] = useState( - modeService.getCurrentMode(), - ); - - useEffect(() => { - const handleModeChange = (newMode: PermissionMode) => { - setCurrentMode(newMode); - }; - - modeService.on("modeChanged", handleModeChange); - return () => { - modeService.off("modeChanged", handleModeChange); - }; - }, []); - - return currentMode; -} - -// Custom hook to combine all selector logic -function useSelectors( - configPath: string | undefined, - setMessages: React.Dispatch>, - resetChatHistory: () => void, -) { - const { handleOrganizationSelect } = useOrganizationSelector({ - onMessage: (message) => { - setMessages((prev) => [...prev, message]); - }, - onChatReset: resetChatHistory, - }); - - const { handleConfigSelect } = useConfigSelector({ - configPath, - onMessage: (message) => { - setMessages((prev) => [...prev, message]); - }, - onChatReset: resetChatHistory, - }); - - const { handleModelSelect } = useModelSelector({ - onMessage: (message) => { - setMessages((prev) => [...prev, message]); - }, - }); - - return { - handleOrganizationSelect, - handleConfigSelect, - handleModelSelect, - }; -} interface TUIChatProps { // Remote mode props @@ -191,205 +39,6 @@ interface TUIChatProps { additionalRules?: string[]; } -// Bottom status bar component -interface BottomStatusBarProps { - currentMode: PermissionMode; - repoURlText: string; - isRemoteMode: boolean; - services: any; - navState: any; - navigateTo: (screen: NavigationScreen, data?: any) => void; - closeCurrentScreen: () => void; -} - -const BottomStatusBar: React.FC = ({ - currentMode, - repoURlText, - isRemoteMode, - services, - navState, - navigateTo, - closeCurrentScreen, -}) => ( - - - {currentMode === "normal" && ( - <> - - {repoURlText} - - - - )} - - - - {!isRemoteMode && services.model?.model && ( - { - if (shouldShow && navState.currentScreen === "chat") { - navigateTo("free-trial"); - } else if (!shouldShow && navState.currentScreen === "free-trial") { - closeCurrentScreen(); - } - }} - /> - )} - - - - - -); - -// Component to handle all screen-specific rendering -interface ScreenContentProps { - isScreenActive: (screen: NavigationScreen) => boolean; - navState: any; - services: any; - handleLoginTokenSubmit: (token: string) => void; - handleOrganizationSelect: ( - organizationId: string | null, - organizationName: string, - ) => Promise; - handleConfigSelect: (config: ConfigOption) => Promise; - handleModelSelect: (model: ModelOption) => Promise; - handleReload: () => Promise; - closeCurrentScreen: () => void; - activePermissionRequest: any; - handleToolPermissionResponse: ( - requestId: string, - approved: boolean, - createPolicy?: boolean, - stopStream?: boolean, - ) => void; - handleUserMessage: (message: string) => void; - isWaitingForResponse: boolean; - inputMode: boolean; - handleInterrupt: () => void; - handleFileAttached: (filePath: string, content: string) => void; - isInputDisabled: boolean; - isRemoteMode: boolean; -} - -const ScreenContent: React.FC = ({ - isScreenActive, - navState, - services, - handleLoginTokenSubmit, - handleOrganizationSelect, - handleConfigSelect, - handleModelSelect, - handleReload, - closeCurrentScreen, - activePermissionRequest, - handleToolPermissionResponse, - handleUserMessage, - isWaitingForResponse, - inputMode, - handleInterrupt, - handleFileAttached, - isInputDisabled, - isRemoteMode, -}) => { - // Login prompt - if (isScreenActive("login") && navState.screenData) { - return ( - - - Login Required - - {navState.screenData.text} - - - ); - } - - // Organization selector - if (isScreenActive("organization")) { - return ( - - ); - } - - // Config selector - if (isScreenActive("config")) { - return ( - - ); - } - - if (isScreenActive("mcp")) { - return ; - } - - // Model selector - if (isScreenActive("model")) { - return ( - - ); - } - - // Free trial transition UI - if (isScreenActive("free-trial")) { - return ; - } - - // Chat screen with input area - if (isScreenActive("chat")) { - if (activePermissionRequest) { - return ( - - ); - } - return ( - - ); - } - - return null; -}; - const TUIChat: React.FC = ({ remoteUrl, configPath, @@ -458,6 +107,7 @@ const TUIChat: React.FC = ({ const { messages, setMessages, + chatHistory, isWaitingForResponse, responseStartTime, inputMode, @@ -485,6 +135,12 @@ const TUIChat: React.FC = ({ remoteUrl, }); + // Calculate context percentage + const contextData = useContextPercentage({ + chatHistory, + model: services.model?.model || undefined, + }); + const { renderMessage } = useMessageRenderer(); const { handleOrganizationSelect, handleConfigSelect, handleModelSelect } = @@ -528,9 +184,13 @@ const TUIChat: React.FC = ({ {isWaitingForResponse && responseStartTime && ( - ( + + ( + - • esc to interrupt ) + + • esc to interrupt ) + )} @@ -565,6 +225,7 @@ const TUIChat: React.FC = ({ navState={navState} navigateTo={navigateTo} closeCurrentScreen={closeCurrentScreen} + contextPercentage={contextData?.percentage} /> diff --git a/src/ui/components/BottomStatusBar.tsx b/src/ui/components/BottomStatusBar.tsx new file mode 100644 index 000000000..8d75c65a1 --- /dev/null +++ b/src/ui/components/BottomStatusBar.tsx @@ -0,0 +1,70 @@ +import { Box, Text } from "ink"; +import React from "react"; + +import type { PermissionMode } from "../../permissions/types.js"; +import type { NavigationScreen } from "../context/NavigationContext.js"; +import { FreeTrialStatus } from "../FreeTrialStatus.js"; +import { UpdateNotification } from "../UpdateNotification.js"; + +import { ContextPercentageDisplay } from "./ContextPercentageDisplay.js"; +import { ModeIndicator } from "./ModeIndicator.js"; + +interface BottomStatusBarProps { + currentMode: PermissionMode; + repoURlText: string; + isRemoteMode: boolean; + services: any; + navState: any; + navigateTo: (screen: NavigationScreen, data?: any) => void; + closeCurrentScreen: () => void; + contextPercentage?: number; +} + +export const BottomStatusBar: React.FC = ({ + currentMode, + repoURlText, + isRemoteMode, + services, + navState, + navigateTo, + closeCurrentScreen, + contextPercentage, +}) => ( + + + {currentMode === "normal" && ( + + + {repoURlText} + + + + )} + + {contextPercentage !== undefined && contextPercentage > 75 && ( + + • + + + )} + + + {!isRemoteMode && services.model?.model && ( + { + if (shouldShow && navState.currentScreen === "chat") { + navigateTo("free-trial"); + } else if (!shouldShow && navState.currentScreen === "free-trial") { + closeCurrentScreen(); + } + }} + /> + )} + + + + + +); diff --git a/src/ui/components/ContextPercentageDisplay.tsx b/src/ui/components/ContextPercentageDisplay.tsx new file mode 100644 index 000000000..c1e53a6a0 --- /dev/null +++ b/src/ui/components/ContextPercentageDisplay.tsx @@ -0,0 +1,22 @@ +import { Text } from "ink"; +import React from "react"; + +interface ContextPercentageDisplayProps { + percentage: number; +} + +/** + * Component to display the current context usage percentage + * Shows the percentage in gray color for consistency with other status indicators + * Only displays when percentage exceeds 75% threshold + */ +export const ContextPercentageDisplay: React.FC< + ContextPercentageDisplayProps +> = ({ percentage }) => { + // Only show if percentage is greater than 75% + if (percentage <= 75) { + return null; + } + + return Context: {percentage}%; +}; diff --git a/src/ui/components/ScreenContent.tsx b/src/ui/components/ScreenContent.tsx new file mode 100644 index 000000000..8e0e8c779 --- /dev/null +++ b/src/ui/components/ScreenContent.tsx @@ -0,0 +1,158 @@ +import { Box, Text } from "ink"; +import React from "react"; + +import { ConfigSelector } from "../ConfigSelector.js"; +import type { NavigationScreen } from "../context/NavigationContext.js"; +import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js"; +import { MCPSelector } from "../MCPSelector.js"; +import { ModelSelector } from "../ModelSelector.js"; +import { OrganizationSelector } from "../OrganizationSelector.js"; +import type { ConfigOption, ModelOption } from "../types/selectorTypes.js"; +import { UserInput } from "../UserInput.js"; + +import { ToolPermissionSelector } from "./ToolPermissionSelector.js"; + +interface ScreenContentProps { + isScreenActive: (screen: NavigationScreen) => boolean; + navState: any; + services: any; + handleLoginTokenSubmit: (token: string) => void; + handleOrganizationSelect: ( + organizationId: string | null, + organizationName: string, + ) => Promise; + handleConfigSelect: (config: ConfigOption) => Promise; + handleModelSelect: (model: ModelOption) => Promise; + handleReload: () => Promise; + closeCurrentScreen: () => void; + activePermissionRequest: any; + handleToolPermissionResponse: ( + requestId: string, + approved: boolean, + createPolicy?: boolean, + stopStream?: boolean, + ) => void; + handleUserMessage: (message: string) => void; + isWaitingForResponse: boolean; + inputMode: boolean; + handleInterrupt: () => void; + handleFileAttached: (filePath: string, content: string) => void; + isInputDisabled: boolean; + isRemoteMode: boolean; +} + +export const ScreenContent: React.FC = ({ + isScreenActive, + navState, + services, + handleLoginTokenSubmit, + handleOrganizationSelect, + handleConfigSelect, + handleModelSelect, + handleReload, + closeCurrentScreen, + activePermissionRequest, + handleToolPermissionResponse, + handleUserMessage, + isWaitingForResponse, + inputMode, + handleInterrupt, + handleFileAttached, + isInputDisabled, + isRemoteMode, +}) => { + // Login prompt + if (isScreenActive("login") && navState.screenData) { + return ( + + + Login Required + + {navState.screenData.text} + + + ); + } + + // Organization selector + if (isScreenActive("organization")) { + return ( + + ); + } + + // Config selector + if (isScreenActive("config")) { + return ( + + ); + } + + if (isScreenActive("mcp")) { + return ; + } + + // Model selector + if (isScreenActive("model")) { + return ( + + ); + } + + // Free trial transition UI + if (isScreenActive("free-trial")) { + return ; + } + + // Chat screen with input area + if (isScreenActive("chat")) { + if (activePermissionRequest) { + return ( + + ); + } + return ( + + ); + } + + return null; +}; diff --git a/src/ui/hooks/useContextPercentage.ts b/src/ui/hooks/useContextPercentage.ts new file mode 100644 index 000000000..7172591fd --- /dev/null +++ b/src/ui/hooks/useContextPercentage.ts @@ -0,0 +1,41 @@ +import { ModelConfig } from "@continuedev/config-yaml"; +import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import { useMemo } from "react"; + +import { + calculateContextUsagePercentage, + countChatHistoryTokens, +} from "../../util/tokenizer.js"; + +interface UseContextPercentageProps { + chatHistory: ChatCompletionMessageParam[]; + model?: ModelConfig; +} + +/** + * Hook to calculate the current context usage percentage + * This uses the same logic as the compaction trigger to show users + * how close they are to the context limit + */ +export function useContextPercentage({ + chatHistory, + model, +}: UseContextPercentageProps) { + const contextData = useMemo(() => { + // Return null if no model is available + if (!model) { + return null; + } + + // Calculate token count and percentage + const tokenCount = countChatHistoryTokens(chatHistory); + const percentage = calculateContextUsagePercentage(tokenCount, model); + + return { + tokenCount, + percentage, + }; + }, [chatHistory, model]); + + return contextData; +} diff --git a/src/ui/hooks/useTUIChatHooks.ts b/src/ui/hooks/useTUIChatHooks.ts new file mode 100644 index 000000000..762c9d481 --- /dev/null +++ b/src/ui/hooks/useTUIChatHooks.ts @@ -0,0 +1,148 @@ +import { useCallback, useEffect, useState } from "react"; + +import type { PermissionMode } from "../../permissions/types.js"; +import { modeService } from "../../services/ModeService.js"; +import { getGitRemoteUrl, isGitRepo } from "../../util/git.js"; +import type { ConfigOption, ModelOption } from "../types/selectorTypes.js"; + +import { useConfigSelector } from "./useConfigSelector.js"; +import { useModelSelector } from "./useModelSelector.js"; +import { useOrganizationSelector } from "./useOrganizationSelector.js"; + +// Helper function to get repo URL text +export function getRepoUrlText(remoteUrl?: string): string { + let url = remoteUrl ?? ""; + if (!url) { + const isGit = isGitRepo(); + if (isGit) { + const gitUrl = getGitRemoteUrl(); + if (gitUrl) { + url = gitUrl; + } + } + } + if (!url) { + url = process.cwd(); + } + + url = url.replace(/\.git$/, ""); + url = url.replace(/^(https|http):\/\/.*?\//, ""); + return url; +} + +// Custom hook for intro message +export function useIntroMessage( + isRemoteMode: boolean, + services: any, + allServicesReady: boolean, +) { + const [showIntroMessage, setShowIntroMessage] = useState(false); + + useEffect(() => { + const shouldShow = + !isRemoteMode && + allServicesReady && + !!services.config?.config && + !!services.model?.model && + !!services.mcp?.mcpService; + + setShowIntroMessage(shouldShow); + }, [ + isRemoteMode, + allServicesReady, + services.config?.config, + services.model?.model, + services.mcp?.mcpService, + ]); + + return [showIntroMessage, setShowIntroMessage] as const; +} + +// Custom hook for login handling +export function useLoginHandlers( + navigateTo: any, + navState: any, + closeCurrentScreen: () => void, +) { + const handleLoginPrompt = useCallback( + (promptText: string): Promise => { + return new Promise((resolve) => { + navigateTo("login", { text: promptText, resolve }); + }); + }, + [navigateTo], + ); + + const handleLoginTokenSubmit = useCallback( + (token: string) => { + if (navState.screenData?.resolve) { + navState.screenData.resolve(token); + closeCurrentScreen(); + } + }, + [navState.screenData, closeCurrentScreen], + ); + + return { handleLoginPrompt, handleLoginTokenSubmit }; +} + +// Custom hook for mode tracking +export function useCurrentMode() { + const [currentMode, setCurrentMode] = useState( + modeService.getCurrentMode(), + ); + + useEffect(() => { + const handleModeChange = (newMode: PermissionMode) => { + setCurrentMode(newMode); + }; + + modeService.on("modeChanged", handleModeChange); + return () => { + modeService.off("modeChanged", handleModeChange); + }; + }, []); + + return currentMode; +} + +// Custom hook to combine all selector logic +export function useSelectors( + configPath: string | undefined, + setMessages: React.Dispatch>, + resetChatHistory: () => void, +): { + handleOrganizationSelect: ( + organizationId: string | null, + organizationName: string, + ) => Promise; + handleConfigSelect: (config: ConfigOption) => Promise; + handleModelSelect: (model: ModelOption) => Promise; +} { + const { handleOrganizationSelect } = useOrganizationSelector({ + onMessage: (message) => { + setMessages((prev) => [...prev, message]); + }, + onChatReset: resetChatHistory, + }); + + const { handleConfigSelect } = useConfigSelector({ + configPath, + onMessage: (message) => { + setMessages((prev) => [...prev, message]); + }, + onChatReset: resetChatHistory, + }); + + const { handleModelSelect } = useModelSelector({ + onMessage: (message) => { + setMessages((prev) => [...prev, message]); + }, + }); + + return { + handleOrganizationSelect, + handleConfigSelect, + handleModelSelect, + }; +} diff --git a/src/ui/types/selectorTypes.ts b/src/ui/types/selectorTypes.ts new file mode 100644 index 000000000..c6d23809a --- /dev/null +++ b/src/ui/types/selectorTypes.ts @@ -0,0 +1,15 @@ +// Type definitions for selectors - compatible with existing hook interfaces + +export interface ConfigOption { + id: string; + name: string; + type: "local" | "assistant" | "create"; + slug?: string; +} + +export interface ModelOption { + id: string; + name: string; + index: number; + provider: string; +} From d1ddd5edae0d5d2148180af38be6950ffd29a9ae Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 18 Aug 2025 08:45:13 -0700 Subject: [PATCH 03/15] feat: review bot --- .../workflows/continue-detailed-review.yaml | 25 +++++++++++++++++++ .../workflows/continue-general-review.yaml | 25 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 .github/workflows/continue-detailed-review.yaml create mode 100644 .github/workflows/continue-general-review.yaml diff --git a/.github/workflows/continue-detailed-review.yaml b/.github/workflows/continue-detailed-review.yaml new file mode 100644 index 000000000..a3e96e2df --- /dev/null +++ b/.github/workflows/continue-detailed-review.yaml @@ -0,0 +1,25 @@ +name: Continue Detailed Review + +on: + pull_request: + types: [opened, ready_for_review] + issue_comment: + types: [created] + +permissions: + contents: read + pull-requests: write + issues: write + +jobs: + detailed-code-review: + name: Continue Detailed Review + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Run Detailed PR Review + uses: continuedev/continue/actions/detailed-review@5361d5e33b880add1d3d050eeadd01971434fb75 + with: + continue-api-key: ${{ secrets.CONTINUE_API_KEY }} + continue-org: continuedev + continue-config: continuedev/review-bot \ No newline at end of file diff --git a/.github/workflows/continue-general-review.yaml b/.github/workflows/continue-general-review.yaml new file mode 100644 index 000000000..d69efa163 --- /dev/null +++ b/.github/workflows/continue-general-review.yaml @@ -0,0 +1,25 @@ +name: Continue General Review + +on: + pull_request: + types: [opened, ready_for_review] + issue_comment: + types: [created] + +permissions: + contents: read + pull-requests: write + issues: write + +jobs: + general-code-review: + name: Continue General Review + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Run Continue PR Review Action + uses: continuedev/continue/actions/general-review@5361d5e33b880add1d3d050eeadd01971434fb75 + with: + continue-api-key: ${{ secrets.CONTINUE_API_KEY }} + continue-org: "continuedev" + continue-config: "continuedev/review-bot" \ No newline at end of file From b643f63a5fdb256bd6fa641e4c5f3e5dcbc50b3b Mon Sep 17 00:00:00 2001 From: Continue Agent Date: Mon, 18 Aug 2025 15:51:13 +0000 Subject: [PATCH 04/15] fix: improve JSDoc comment formatting in selectorTypes.ts Addresses @sestinj code review feedback on PR #227 line 3 --- src/ui/types/selectorTypes.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/ui/types/selectorTypes.ts b/src/ui/types/selectorTypes.ts index c6d23809a..2773486de 100644 --- a/src/ui/types/selectorTypes.ts +++ b/src/ui/types/selectorTypes.ts @@ -1,4 +1,6 @@ -// Type definitions for selectors - compatible with existing hook interfaces +/** + * Type definitions for selectors - compatible with existing hook interfaces + */ export interface ConfigOption { id: string; From f5484c4dbe33f7bf01748d60a645270535e21075 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 18 Aug 2025 08:58:10 -0700 Subject: [PATCH 05/15] address feedback --- src/ui/components/BottomStatusBar.tsx | 6 +++--- src/ui/types/selectorTypes.ts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/ui/components/BottomStatusBar.tsx b/src/ui/components/BottomStatusBar.tsx index 8d75c65a1..c46bd2059 100644 --- a/src/ui/components/BottomStatusBar.tsx +++ b/src/ui/components/BottomStatusBar.tsx @@ -11,7 +11,7 @@ import { ModeIndicator } from "./ModeIndicator.js"; interface BottomStatusBarProps { currentMode: PermissionMode; - repoURlText: string; + repoURLText: string; isRemoteMode: boolean; services: any; navState: any; @@ -22,7 +22,7 @@ interface BottomStatusBarProps { export const BottomStatusBar: React.FC = ({ currentMode, - repoURlText, + repoURLText, isRemoteMode, services, navState, @@ -35,7 +35,7 @@ export const BottomStatusBar: React.FC = ({ {currentMode === "normal" && ( - {repoURlText} + {repoURLText} diff --git a/src/ui/types/selectorTypes.ts b/src/ui/types/selectorTypes.ts index c6d23809a..899e9ab6f 100644 --- a/src/ui/types/selectorTypes.ts +++ b/src/ui/types/selectorTypes.ts @@ -1,8 +1,8 @@ // Type definitions for selectors - compatible with existing hook interfaces -export interface ConfigOption { - id: string; - name: string; +import type { SelectorOption } from "../Selector.js"; + +export interface ConfigOption extends SelectorOption { type: "local" | "assistant" | "create"; slug?: string; } From 40a0eb6b2afc76d3fc3c752065a800dd17c74aff Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 18 Aug 2025 09:10:57 -0700 Subject: [PATCH 06/15] 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 ba132ce9b626e52c28d1245c255f38c02fcb5af8 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 18 Aug 2025 09:14:01 -0700 Subject: [PATCH 07/15] fix --- src/ui/TUIChat.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 9c037d111..c8c4e0f29 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -219,7 +219,7 @@ const TUIChat: React.FC = ({ {/* Free trial status and Continue CLI info - always show */} Date: Mon, 18 Aug 2025 09:14:27 -0700 Subject: [PATCH 08/15] 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 09/15] 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 10/15] 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 && ( - + )} ); From 8811d960f50d4fc7ce9e4b68d6e7310222b695f1 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 18 Aug 2025 10:33:12 -0700 Subject: [PATCH 11/15] chore: remove duplicate bot --- .github/workflows/continue-review.yaml | 250 ------------------------- 1 file changed, 250 deletions(-) delete mode 100644 .github/workflows/continue-review.yaml diff --git a/.github/workflows/continue-review.yaml b/.github/workflows/continue-review.yaml deleted file mode 100644 index a6cf72b93..000000000 --- a/.github/workflows/continue-review.yaml +++ /dev/null @@ -1,250 +0,0 @@ -name: Continue CLI Code Review - -on: - workflow_call: - inputs: - assistant: - description: "Assistant configuration to use" - required: false - default: "nate/default-assistant" - type: string - prompt: - description: "Custom prompt to use instead of the default PR review" - required: false - type: string - secrets: - CONTINUE_API_KEY: - required: true - workflow_dispatch: - inputs: - assistant: - description: "Assistant configuration to use" - required: false - default: "nate/default-assistant" - type: string - prompt: - description: "Custom prompt to use instead of the default PR review" - required: false - type: string - -permissions: - contents: read - pull-requests: write - issues: write - -jobs: - code-review: - name: AI Code Review - runs-on: ubuntu-latest - - steps: - - name: Checkout Repository - uses: actions/checkout@v4 - with: - fetch-depth: 0 # Fetch full history for better context - - - name: Setup Node.js - uses: actions/setup-node@v4 - with: - node-version: 20 - - - name: Install Continue CLI - run: npm install -g @continuedev/cli - - - name: Build PR diff prompt - if: github.event_name == 'pull_request' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request') - run: | - # Get PR number - different methods depending on trigger - if [ "${{ github.event_name }}" = "pull_request" ]; then - PR_NUMBER="${{ github.event.number }}" - else - # For workflow_call triggered by PR, we need to get it from context - PR_NUMBER=$(jq -r '.pull_request.number' "$GITHUB_EVENT_PATH" 2>/dev/null || echo "") - fi - - if [ -n "$PR_NUMBER" ] && [ "$PR_NUMBER" != "null" ]; then - # Get PR diff using GitHub CLI - gh pr diff $PR_NUMBER > pr_diff.txt - - # Create comprehensive prompt - cat > review_prompt.txt << 'EOF' - You are conducting a code review for a pull request. Below is the git diff showing all the changes: - - EOF - - echo "--- PR DIFF START ---" >> review_prompt.txt - cat pr_diff.txt >> review_prompt.txt - echo "--- PR DIFF END ---" >> review_prompt.txt - - cat >> review_prompt.txt << 'EOF' - - Please analyze these changes and provide a comprehensive code review. Consider: - - 1. **Code Quality**: Are there any bugs, performance issues, or code smells? - 2. **Best Practices**: Does the code follow established patterns and conventions? - 3. **Security**: Are there any potential security vulnerabilities? - 4. **Testing**: Are appropriate tests included or updated? - 5. **Documentation**: Is documentation adequate for the changes? - 6. **Architecture**: Do the changes fit well with the existing codebase structure? - - You can use the available tools to explore the codebase and understand context better. - - Format your response as a markdown code review with the following structure: - - ## Code Review Summary - - ### Issues Found - - [List any problems with severity levels] - - ### Suggestions - - [List improvement recommendations] - - ### Overall Assessment - [Provide overall recommendation: APPROVE, REQUEST_CHANGES, or COMMENT] - - Only call the 'exit' tool if you find critical security vulnerabilities or bugs that would break production. - EOF - else - echo "Could not determine PR number, using generic prompt" - cat > review_prompt.txt << 'EOF' - Please review the recent changes to this codebase and provide feedback on code quality, potential issues, and suggestions for improvement. - - Format your response as a markdown code review. - EOF - fi - env: - GH_TOKEN: ${{ github.token }} - - - name: Build custom prompt - if: inputs.prompt != '' - env: - GITHUB_TOKEN: ${{ github.token }} - run: | - # Get PR number for custom prompts too - if [ "${{ github.event_name }}" = "pull_request" ]; then - PR_NUMBER="${{ github.event.number }}" - else - # For workflow_call triggered by PR, we need to get it from context - PR_NUMBER=$(jq -r '.pull_request.number' "$GITHUB_EVENT_PATH" 2>/dev/null || echo "") - fi - - if [ -n "$PR_NUMBER" ] && [ "$PR_NUMBER" != "null" ]; then - # Get PR diff using GitHub CLI - gh pr diff $PR_NUMBER > pr_diff.txt - - # Create custom prompt with diff included - echo "${{ inputs.prompt }}" > review_prompt.txt - echo "" >> review_prompt.txt - echo "Below is the git diff showing all the changes:" >> review_prompt.txt - echo "" >> review_prompt.txt - echo "--- PR DIFF START ---" >> review_prompt.txt - cat pr_diff.txt >> review_prompt.txt - echo "--- PR DIFF END ---" >> review_prompt.txt - else - echo "${{ inputs.prompt }}" > review_prompt.txt - fi - - - name: Build default prompt for non-PR triggers - if: inputs.prompt == '' && github.event_name != 'pull_request' && (github.event_name != 'workflow_run' || github.event.workflow_run.event != 'pull_request') - run: | - cat > review_prompt.txt << 'EOF' - Please review the recent changes to this codebase and provide feedback on code quality, potential issues, and suggestions for improvement. You do not need to acknowledge what was done well. - - Format your response as a markdown code review with each comment having only a short description about the problem and suggested solution, each being separated by "\n\n---\n\n". - - EOF - - - name: Run Continue CLI Review - run: | - echo "Running Continue CLI with prompt:" - echo "==================================" - cat review_prompt.txt - echo "==================================" - echo "" - - # Run the CLI with the generated prompt and pipe output to code_review.md - cat review_prompt.txt | cn --auto --config "${{ inputs.assistant }}" -p > code_review.md - env: - CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} - - - name: Upload Review Results - uses: actions/upload-artifact@v4 - if: always() - with: - name: code-review-results - path: | - code_review.md - review_prompt.txt - pr_diff.txt - retention-days: 30 - - - name: Comment PR with Review - if: always() && (github.event_name == 'pull_request' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request')) - uses: actions/github-script@v7 - with: - script: | - const fs = require('fs'); - - try { - let reviewContent = ''; - - if (fs.existsSync('code_review.md') && fs.statSync('code_review.md').size > 0) { - reviewContent = fs.readFileSync('code_review.md', 'utf8'); - } else { - reviewContent = '⚠️ AI review completed but no review output was generated. Check the action logs for details.'; - } - - // Get PR number - let prNumber; - if (context.payload.pull_request) { - prNumber = context.payload.pull_request.number; - } else if (context.payload.workflow_run && context.payload.workflow_run.pull_requests && context.payload.workflow_run.pull_requests.length > 0) { - prNumber = context.payload.workflow_run.pull_requests[0].number; - } - - if (!prNumber) { - console.log('Could not determine PR number for commenting'); - return; - } - - // Unique identifier for our bot comments - const botSignature = ''; - const newComment = `${botSignature}\n${reviewContent}`; - - // Get all comments on the PR - const { data: comments } = await github.rest.issues.listComments({ per_page: 100, - issue_number: prNumber, - owner: context.repo.owner, - repo: context.repo.repo, - }); - - // Find existing Continue CLI review comment - const existingComment = comments.find(comment => - comment.body.includes(botSignature) - ); - - if (existingComment) { - // Update existing comment - await github.rest.issues.updateComment({ - comment_id: existingComment.id, - owner: context.repo.owner, - repo: context.repo.repo, - body: newComment - }); - console.log(`Successfully updated existing comment #${existingComment.id} on PR #${prNumber}`); - } else { - // Create new comment - await github.rest.issues.createComment({ - issue_number: prNumber, - owner: context.repo.owner, - repo: context.repo.repo, - body: newComment - }); - console.log(`Successfully created new comment on PR #${prNumber}`); - } - } catch (error) { - console.log('Failed to post/update comment:', error.message); - console.log('Error details:', error); - } - env: - GITHUB_TOKEN: ${{ github.token }} From 44981be66d663c2865dbfe0588f4d2ab76d7c868 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 18 Aug 2025 10:33:39 -0700 Subject: [PATCH 12/15] fix: formatting --- .github/workflows/continue-detailed-review.yaml | 2 +- .github/workflows/continue-general-review.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/continue-detailed-review.yaml b/.github/workflows/continue-detailed-review.yaml index a3e96e2df..595981e57 100644 --- a/.github/workflows/continue-detailed-review.yaml +++ b/.github/workflows/continue-detailed-review.yaml @@ -22,4 +22,4 @@ jobs: with: continue-api-key: ${{ secrets.CONTINUE_API_KEY }} continue-org: continuedev - continue-config: continuedev/review-bot \ No newline at end of file + continue-config: continuedev/review-bot diff --git a/.github/workflows/continue-general-review.yaml b/.github/workflows/continue-general-review.yaml index d69efa163..4fa060dd8 100644 --- a/.github/workflows/continue-general-review.yaml +++ b/.github/workflows/continue-general-review.yaml @@ -22,4 +22,4 @@ jobs: with: continue-api-key: ${{ secrets.CONTINUE_API_KEY }} continue-org: "continuedev" - continue-config: "continuedev/review-bot" \ No newline at end of file + continue-config: "continuedev/review-bot" From c0280e461db3f06b554e14a9c27011fa4365adb2 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 18 Aug 2025 10:34:52 -0700 Subject: [PATCH 13/15] Move session storage from .continue-cli/sessions to .continue/cli-sessions --- src/e2e/resume-flag.test.ts | 4 ++-- src/session.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/e2e/resume-flag.test.ts b/src/e2e/resume-flag.test.ts index 87e105b06..ccbdfecb2 100644 --- a/src/e2e/resume-flag.test.ts +++ b/src/e2e/resume-flag.test.ts @@ -44,7 +44,7 @@ describe("E2E: Resume Flag", () => { expect(firstResult.stdout).toContain("Hello! Nice to meet you."); // Verify that a session file was created - const sessionDir = path.join(context.testDir, ".continue-cli", "sessions"); + const sessionDir = path.join(context.testDir, ".continue", "cli-sessions"); const sessionFiles = await fs.readdir(sessionDir); expect(sessionFiles).toHaveLength(1); @@ -131,7 +131,7 @@ describe("E2E: Resume Flag", () => { expect(firstResult.stdout).toContain("First response"); // Verify the first session was saved correctly - const sessionDir = path.join(context.testDir, ".continue-cli", "sessions"); + const sessionDir = path.join(context.testDir, ".continue", "cli-sessions"); let sessionFiles = await fs.readdir(sessionDir); expect(sessionFiles).toHaveLength(1); diff --git a/src/session.ts b/src/session.ts index b75417dff..18f9b5c52 100644 --- a/src/session.ts +++ b/src/session.ts @@ -156,7 +156,7 @@ function getSessionId(): string { function getSessionDir(): string { // For tests, use the test directory if we're in test mode if (process.env.CONTINUE_CLI_TEST && process.env.HOME) { - const sessionDir = path.join(process.env.HOME, ".continue-cli", "sessions"); + const sessionDir = path.join(process.env.HOME, ".continue", "cli-sessions"); // Create directory if it doesn't exist if (!fs.existsSync(sessionDir)) { @@ -167,7 +167,7 @@ function getSessionDir(): string { } const homeDir = os.homedir(); - const sessionDir = path.join(homeDir, ".continue-cli", "sessions"); + const sessionDir = path.join(homeDir, ".continue", "cli-sessions"); // Create directory if it doesn't exist if (!fs.existsSync(sessionDir)) { From 4f1af0ae77afac0c15f186a7193c0bc2341f3390 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 18 Aug 2025 10:39:10 -0700 Subject: [PATCH 14/15] chore: remove redundant step --- .github/workflows/pr_checks.yml | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/.github/workflows/pr_checks.yml b/.github/workflows/pr_checks.yml index 3f8922952..be6f84ec4 100644 --- a/.github/workflows/pr_checks.yml +++ b/.github/workflows/pr_checks.yml @@ -86,18 +86,6 @@ jobs: shell: bash run: npm test -- --exclude='**/*.e2e.*' --exclude='**/e2e/**' - review: - uses: ./.github/workflows/continue-review.yaml - secrets: - CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} - with: - prompt: | - Please review the below changes for any mistakes. You can look around the codebase to investigate if needed. Look for: - - React changes causing too many re-renders - - Functions that are too long - - Other potentially subtle bugs - Keep your response concise and give a bullet pointed list of the findings, including suggested fixes for any problems you find. - # GitHub does not have a way of requiring that all checks pass (you must manually select each job) # This action at least lets us manage the list of required tests via source control # so that creators of new jobs can add them to this list From 21acbb5c324612033ae179f23d1514e120a51218 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 18 Aug 2025 14:31:29 -0700 Subject: [PATCH 15/15] Add responsive ASCII art display based on terminal width --- src/asciiArt.test.ts | 71 ++++++++++++++++++++++++++++++++++++++++++++ src/asciiArt.ts | 18 +++++++++++ src/commands/chat.ts | 4 +-- 3 files changed, 91 insertions(+), 2 deletions(-) create mode 100644 src/asciiArt.test.ts diff --git a/src/asciiArt.test.ts b/src/asciiArt.test.ts new file mode 100644 index 000000000..ba59c2afc --- /dev/null +++ b/src/asciiArt.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it, beforeEach, afterEach } from "vitest"; + +import { getDisplayableAsciiArt, CONTINUE_ASCII_ART } from "./asciiArt.js"; + +describe("asciiArt", () => { + let originalColumns: number | undefined; + + beforeEach(() => { + originalColumns = process.stdout.columns; + }); + + afterEach(() => { + if (originalColumns === undefined) { + delete (process.stdout as any).columns; + } else { + process.stdout.columns = originalColumns; + } + }); + + describe("getDisplayableAsciiArt", () => { + it("should return full ASCII art when terminal is wide enough", () => { + // Set process.stdout.columns to simulate wide terminal + process.stdout.columns = 80; + + const result = getDisplayableAsciiArt(); + + expect(result).toBe(CONTINUE_ASCII_ART); + }); + + it("should return simple text version when terminal is too narrow", () => { + // Set process.stdout.columns to simulate narrow terminal + process.stdout.columns = 60; + + const result = getDisplayableAsciiArt(); + + expect(result).toContain("CONTINUE"); + expect(result).toContain("v0.0.0-dev"); + expect(result).not.toBe(CONTINUE_ASCII_ART); + // Should be much shorter than the full ASCII art + expect(result.length).toBeLessThan(CONTINUE_ASCII_ART.length / 2); + }); + + it("should return simple text version when terminal is below threshold", () => { + // Test the edge case at exactly 74 columns (below our threshold of 75) + process.stdout.columns = 74; + + const result = getDisplayableAsciiArt(); + + expect(result).toContain("CONTINUE"); + expect(result).not.toBe(CONTINUE_ASCII_ART); + }); + + it("should return full ASCII art when terminal is exactly at threshold", () => { + // Test the edge case at exactly 75 columns (our threshold) + process.stdout.columns = 75; + + const result = getDisplayableAsciiArt(); + + expect(result).toBe(CONTINUE_ASCII_ART); + }); + + it("should default to full ASCII art when columns is undefined", () => { + // Set process.stdout.columns to undefined (should default to 80) + delete (process.stdout as any).columns; + + const result = getDisplayableAsciiArt(); + + expect(result).toBe(CONTINUE_ASCII_ART); + }); + }); +}); \ No newline at end of file diff --git a/src/asciiArt.ts b/src/asciiArt.ts index 0afb4c041..39d365388 100644 --- a/src/asciiArt.ts +++ b/src/asciiArt.ts @@ -14,6 +14,24 @@ ${mind.multiline(` ██████╗ ██████╗ ███╗ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝`)} ${d("v" + getVersion())}`; +// Minimum terminal width required to display ASCII art properly +const MIN_WIDTH_FOR_ASCII_ART = 75; + +/** + * Returns the ASCII art only if the terminal is wide enough to display it properly. + * If terminal is too narrow, returns just the version string. + */ +export function getDisplayableAsciiArt(): string { + const terminalWidth = process.stdout.columns || 80; + + if (terminalWidth >= MIN_WIDTH_FOR_ASCII_ART) { + return CONTINUE_ASCII_ART; + } + + // If terminal is too narrow, just show a simple version + return `\n${chalk.bold.blue("CONTINUE")} ${d("v" + getVersion())}\n`; +} + export const CONTINUE_LOGO_ASCII_ART = ` @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@ diff --git a/src/commands/chat.ts b/src/commands/chat.ts index 6cd94ff0a..27775449e 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -3,7 +3,7 @@ import chalk from "chalk"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; import * as readlineSync from "readline-sync"; -import { CONTINUE_ASCII_ART } from "../asciiArt.js"; +import { getDisplayableAsciiArt } from "../asciiArt.js"; import { compactChatHistory, findCompactionIndex, @@ -456,7 +456,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { } // Show ASCII art and version for TUI mode - console.log(CONTINUE_ASCII_ART); + console.log(getDisplayableAsciiArt()); // Start TUI with skipOnboarding since we already handled it await startTUIChat({