diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 2660620f7..c8c4e0f29 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 ) + )} @@ -559,12 +219,13 @@ const TUIChat: React.FC = ({ {/* Free trial status and Continue CLI info - always show */} diff --git a/src/ui/components/BottomStatusBar.tsx b/src/ui/components/BottomStatusBar.tsx new file mode 100644 index 000000000..c46bd2059 --- /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..458524305 --- /dev/null +++ b/src/ui/types/selectorTypes.ts @@ -0,0 +1,17 @@ +/** + * Type definitions for selectors - compatible with existing hook interfaces + */ + +import type { SelectorOption } from "../Selector.js"; + +export interface ConfigOption extends SelectorOption { + type: "local" | "assistant" | "create"; + slug?: string; +} + +export interface ModelOption { + id: string; + name: string; + index: number; + provider: string; +}