diff --git a/extensions/cli/src/__mocks__/services/index.ts b/extensions/cli/src/__mocks__/services/index.ts index 7ea28d99b..16091f0a9 100644 --- a/extensions/cli/src/__mocks__/services/index.ts +++ b/extensions/cli/src/__mocks__/services/index.ts @@ -17,4 +17,9 @@ export const SERVICE_NAMES = { CONFIG: "config", MODEL: "model", MCP: "mcp", + TOOL_PERMISSIONS: "toolPermissions", + FILE_INDEX: "fileIndex", + RESOURCE_MONITORING: "resourceMonitoring", + SYSTEM_MESSAGE: "systemMessage", + CHAT_HISTORY: "chatHistory", }; diff --git a/extensions/cli/src/commands/commands.ts b/extensions/cli/src/commands/commands.ts index 419241100..5e0c7f7bd 100644 --- a/extensions/cli/src/commands/commands.ts +++ b/extensions/cli/src/commands/commands.ts @@ -40,6 +40,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [ description: "Sign out of your current session", category: "system", }, + { + name: "update", + description: "Update the Continue CLI", + category: "system", + }, { name: "whoami", description: "Check who you're currently logged in as", diff --git a/extensions/cli/src/services/UpdateService.ts b/extensions/cli/src/services/UpdateService.ts new file mode 100644 index 000000000..71e99ea57 --- /dev/null +++ b/extensions/cli/src/services/UpdateService.ts @@ -0,0 +1,223 @@ +import { exec, spawn } from "child_process"; +import { logger } from "src/util/logger.js"; +import { promisify } from "util"; +import { compareVersions, getLatestVersion, getVersion } from "../version.js"; +import { serviceContainer } from "./ServiceContainer.js"; +import { UpdateServiceState, UpdateStatus } from "./types.js"; + +const execAsync = promisify(exec); + +/** + * Service for checking and performing CLI updates + */ +export class UpdateService { + private state: UpdateServiceState; + private serviceName = "update"; // Used for emitting events via serviceContainer + + constructor() { + this.state = { + autoUpdate: true, // TODO make configurable + status: UpdateStatus.IDLE, + message: "", + error: null, + isUpdateAvailable: false, + latestVersion: null, + currentVersion: getVersion(), + }; + } + + /** + * Initialize the update service + */ + async initialize(headless?: boolean) { + // Don't automatically check in tests/headless + if (!headless && process.env.NODE_ENV !== "test") { + await this.checkAndAutoUpdate(); + } + + return this.state; + } + + getState(): UpdateServiceState { + return this.state; + } + + private async checkAndAutoUpdate() { + await this.checkForUpdates(); + + if (this.state.currentVersion === "0.0.0-dev") { + return; // Uncomment to test update behavior + } + + // If update is available, automatically update + if ( + this.state.isUpdateAvailable && + this.state.autoUpdate && + this.state.status !== "updating" + ) { + if (process.env.CONTINUE_CLI_AUTO_UPDATED) { + logger.debug("Already auto updated, preventing sequential auto-update"); + } else { + await this.performUpdate(true); + } + } + } + + private async checkForUpdates() { + try { + this.updateState({ + status: UpdateStatus.CHECKING, + message: "Checking for updates", + }); + + const latestVersion = await getLatestVersion(); + + if (!latestVersion) { + this.updateState({ + status: UpdateStatus.IDLE, + message: "Continue CLI", + isUpdateAvailable: false, + }); + return this.state; + } + + const comparison = compareVersions( + this.state.currentVersion, + latestVersion, + ); + const isUpdateAvailable = comparison === "older"; + + this.updateState({ + status: UpdateStatus.IDLE, + message: isUpdateAvailable + ? `Update available: v${latestVersion}` + : `Continue CLI v${this.state.currentVersion}`, + isUpdateAvailable, + latestVersion, + }); + } catch (error: any) { + logger.error("Error checking for updates:", error); + this.updateState({ + status: UpdateStatus.ERROR, + message: `Continue CLI v${this.state.currentVersion}`, + error, + }); + } + } + + async performUpdate(isAutoUpdate?: boolean) { + if (this.state.status === "updating") { + return; + } + + try { + this.updateState({ + status: UpdateStatus.UPDATING, + message: `Updating to v${this.state.latestVersion}`, + }); + + // Install the update + const { stdout, stderr } = await execAsync("npm i -g @continuedev/cli"); + logger.debug("Update output:", { stdout, stderr }); + + if (stderr) { + const errLines = stderr.split("\n"); + for (const line of errLines) { + const lower = line.toLowerCase().trim(); + if ( + !line || + lower.includes("debugger") || + lower.includes("npm warn") + ) { + continue; + } + throw new Error(stderr); + } + } + + if (isAutoUpdate) { + this.updateState({ + status: UpdateStatus.UPDATED, + message: `Updated to v${this.state.latestVersion}`, + isUpdateAvailable: false, + }); + this.restartCLI(); + } else { + this.updateState({ + status: UpdateStatus.UPDATED, + message: `Restart for v${this.state.latestVersion}`, + isUpdateAvailable: false, + }); + } + } catch (error: any) { + logger.error("Error updating CLI:", error); + this.updateState({ + status: UpdateStatus.ERROR, + message: isAutoUpdate ? "Auto-update failed" : "Update failed", + error, + }); + setTimeout(() => { + this.updateState({ + status: UpdateStatus.IDLE, + message: `/update to v${this.state.latestVersion}`, + }); + }, 4000); + } + } + + private restartCLI(): void { + try { + const entryPoint = process.argv[1]; + const cliArgs = process.argv.slice(2); + const nodeExecutable = process.execPath; + + logger.debug( + `Preparing for CLI restart with: ${nodeExecutable} ${entryPoint} ${cliArgs.join( + " ", + )}`, + ); + + // Halt/clean up parent cn process + try { + // Remove all input listeners + global.clearTimeout = () => {}; + global.clearInterval = () => {}; + process.stdin.removeAllListeners(); + process.stdin.pause(); + // console.clear(); // Don't want to clear things that were in console before cn started + } catch (e) { + logger.debug("Error cleaning up terminal:", e); + } + + // Spawn a new detached cn process + const child = spawn(nodeExecutable, [entryPoint, ...cliArgs], { + detached: true, + stdio: "inherit", + env: { + ...process.env, + CONTINUE_CLI_AUTO_UPDATED: "true", + }, + }); + child.on("exit", (code) => { + process.exit(code); + }); + + // Unref child so parent can exit + // I could not find a way to avoid a bug where next process has input glitches without leaving parent in place + // So commenting this out is intentional for now + // child.unref(); + // process.exit(0); + } catch (error) { + logger.error("Failed to restart CLI:", error); + } + } + + private updateState(partialState: Partial): void { + this.state = { + ...this.state, + ...partialState, + }; + + serviceContainer.set(this.serviceName, this.state); + } +} diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index ae53965ab..068f53542 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -21,6 +21,7 @@ import { ServiceInitOptions, ServiceInitResult, } from "./types.js"; +import { UpdateService } from "./UpdateService.js"; // Service instances const authService = new AuthService(); @@ -31,6 +32,7 @@ const mcpService = new MCPService(); const fileIndexService = new FileIndexService(); const resourceMonitoringService = new ResourceMonitoringService(); const chatHistoryService = new ChatHistoryService(); +const updateService = new UpdateService(); /** * Initialize all services and register them with the service container @@ -132,6 +134,12 @@ export async function initializeServices( [], // No dependencies ); + serviceContainer.register( + SERVICE_NAMES.UPDATE, + () => updateService.initialize(), + [], // No dependencies + ); + serviceContainer.register( SERVICE_NAMES.API_CLIENT, async () => { @@ -283,17 +291,9 @@ export function reloadService(serviceName: string) { * Check if all core services are ready */ export function areServicesReady(): boolean { - return [ - SERVICE_NAMES.TOOL_PERMISSIONS, - SERVICE_NAMES.AUTH, - SERVICE_NAMES.API_CLIENT, - SERVICE_NAMES.CONFIG, - SERVICE_NAMES.MODEL, - SERVICE_NAMES.MCP, - SERVICE_NAMES.FILE_INDEX, - SERVICE_NAMES.RESOURCE_MONITORING, - SERVICE_NAMES.CHAT_HISTORY, - ].every((name) => serviceContainer.isReady(name)); + return Object.values(SERVICE_NAMES).every((name) => + serviceContainer.isReady(name), + ); } /** @@ -317,6 +317,7 @@ export const services = { resourceMonitoring: resourceMonitoringService, systemMessage: systemMessageService, chatHistory: chatHistoryService, + updateService: updateService, } as const; // Export the service container for advanced usage diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index 18fb2cbae..6f80965b6 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -81,6 +81,24 @@ export interface MCPServiceState { prompts: MCPPrompt[]; } +export enum UpdateStatus { + IDLE = "idle", + CHECKING = "checking", + UPDATING = "updating", + UPDATED = "updated", + ERROR = "error", +} + +export interface UpdateServiceState { + autoUpdate: boolean; + status: UpdateStatus; + message: string; + error?: Error | null; + isUpdateAvailable: boolean; + latestVersion: string | null; + currentVersion: string; +} + export interface ApiClientServiceState { apiClient: DefaultApiInterface | null; } @@ -92,8 +110,8 @@ export interface ToolPermissionServiceState { originalPolicies?: ToolPermissions; } -export type { FileIndexServiceState } from "./FileIndexService.js"; export type { ChatHistoryState } from "./ChatHistoryService.js"; +export type { FileIndexServiceState } from "./FileIndexService.js"; /** * Service names as constants to prevent typos @@ -109,6 +127,7 @@ export const SERVICE_NAMES = { RESOURCE_MONITORING: "resourceMonitoring", SYSTEM_MESSAGE: "systemMessage", CHAT_HISTORY: "chatHistory", + UPDATE: "update", } as const; /** diff --git a/extensions/cli/src/slashCommands.ts b/extensions/cli/src/slashCommands.ts index b5dc3d9aa..8f2079e89 100644 --- a/extensions/cli/src/slashCommands.ts +++ b/extensions/cli/src/slashCommands.ts @@ -259,22 +259,16 @@ const commandHandlers: Record = { return { openSessionSelector: true }; }, fork: handleFork, + update: () => { + posthogService.capture("useSlashCommand", { name: "update" }); + return { openUpdateSelector: true }; + }, }; export async function handleSlashCommands( input: string, assistant: AssistantConfig, -): Promise<{ - output?: string; - exit?: boolean; - newInput?: string; - clear?: boolean; - openConfigSelector?: boolean; - openModelSelector?: boolean; - openMCPSelector?: boolean; - openSessionSelector?: boolean; - compact?: boolean; -} | null> { +): Promise { // Only trigger slash commands if slash is the very first character if (!input.startsWith("/") || !input.trim().startsWith("/")) { return null; diff --git a/extensions/cli/src/ui/LoadingText.tsx b/extensions/cli/src/ui/LoadingText.tsx new file mode 100644 index 000000000..9d19cc5c4 --- /dev/null +++ b/extensions/cli/src/ui/LoadingText.tsx @@ -0,0 +1,33 @@ +import { Text } from "ink"; +import React, { useEffect, useState } from "react"; + +interface LoadingTextProps { + text: string; + color?: string; + interval?: number; +} + +export const LoadingText: React.FC = ({ + text, + color = "gray", + interval = 300, +}) => { + const [dotsCount, setDotsCount] = useState(1); + + useEffect(() => { + const timer = setInterval(() => { + setDotsCount((current) => (current % 3) + 1); + }, interval); + + return () => clearInterval(timer); + }, [interval]); + + const dots = ".".repeat(dotsCount); + + return ( + + {text} + {dots} + + ); +}; diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 9625e9917..c9b1ed079 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -208,6 +208,7 @@ const TUIChat: React.FC = ({ onShowConfigSelector: () => navigateTo("config"), onShowModelSelector: () => navigateTo("model"), onShowMCPSelector: () => navigateTo("mcp"), + onShowUpdateSelector: () => navigateTo("update"), onShowSessionSelector: () => navigateTo("session"), onLoginPrompt: handleLoginPrompt, onReload: handleReload, diff --git a/extensions/cli/src/ui/UpdateSelector.tsx b/extensions/cli/src/ui/UpdateSelector.tsx new file mode 100644 index 000000000..813c50b61 --- /dev/null +++ b/extensions/cli/src/ui/UpdateSelector.tsx @@ -0,0 +1,84 @@ +import React, { useMemo, useState } from "react"; + +import { useService } from "../hooks/useService.js"; +import { services } from "../services/index.js"; +import { SERVICE_NAMES } from "../services/types.js"; + +import { Selector, SelectorOption } from "./Selector.js"; + +import type { UpdateServiceState } from "../services/types.js"; + +interface UpdateSelectorProps { + onCancel: () => void; +} + +interface UpdateOption extends SelectorOption { + action: "run" | "back"; +} + +export const UpdateSelector: React.FC = ({ onCancel }) => { + const [selectedIndex, setSelectedIndex] = useState(0); + const updateServiceState = useService( + SERVICE_NAMES.UPDATE, + ); + + const updateState = updateServiceState.value; + + const isWorking = + updateServiceState.state === "loading" || + updateState?.status === "checking" || + updateState?.status === "updating"; + + const error: string | null = useMemo(() => { + if (updateServiceState.state === "error") { + return updateServiceState.error?.message || "Update service error"; + } + if (updateState?.status === "error") { + return updateState.message || "Update failed"; + } + return null; + }, [updateServiceState.state, updateServiceState.error, updateState]); + + const loadingMessage = useMemo(() => { + if (!updateState) return "Preparing update..."; + return updateState.message || "Working..."; + }, [updateState]); + + const options: UpdateOption[] = useMemo(() => { + const runLabel = updateState?.latestVersion + ? `Run update to v${updateState.latestVersion}` + : "Run update"; + + return [ + { id: "run-update", name: runLabel, action: "run" }, + { id: "back", name: "Back", action: "back" }, + ]; + }, [updateState?.latestVersion]); + + const handleSelect = async (option: UpdateOption) => { + switch (option.action) { + case "run": + // Perform a manual update (not auto-update) + await services.updateService.performUpdate(false); + return; // Keep selector open to show status changes + case "back": + onCancel(); + return; + } + }; + + return ( + + ); +}; diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 1cb0c6d22..8f0d7da3f 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -8,6 +8,7 @@ import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js"; import { MCPSelector } from "../MCPSelector.js"; import { ModelSelector } from "../ModelSelector.js"; import { SessionSelector } from "../SessionSelector.js"; +import { UpdateSelector } from "../UpdateSelector.js"; import type { ConfigOption, ModelOption } from "../types/selectorTypes.js"; import { UserInput } from "../UserInput.js"; @@ -104,6 +105,10 @@ export const ScreenContent: React.FC = ({ return ; } + if (isScreenActive("update")) { + return ; + } + // Model selector if (isScreenActive("model")) { return ( diff --git a/extensions/cli/src/ui/context/NavigationContext.tsx b/extensions/cli/src/ui/context/NavigationContext.tsx index 1742d8ee8..a13dc99ff 100644 --- a/extensions/cli/src/ui/context/NavigationContext.tsx +++ b/extensions/cli/src/ui/context/NavigationContext.tsx @@ -1,9 +1,9 @@ import React, { createContext, + ReactNode, + useCallback, useContext, useReducer, - useCallback, - ReactNode, } from "react"; /** @@ -17,6 +17,7 @@ export type NavigationScreen = | "free-trial" // Free trial transition UI | "login" // Login prompt | "mcp" // MCP selector + | "update" // Update selector | "session"; // Session selector interface NavigationState { diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index 17aa450fb..a6284e145 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -49,6 +49,7 @@ interface ProcessSlashCommandResultOptions { exit: () => void; onShowConfigSelector: () => void; onShowModelSelector?: () => void; + onShowUpdateSelector?: () => void; onShowMCPSelector?: () => void; onShowSessionSelector?: () => void; onClear?: () => void; @@ -63,6 +64,7 @@ export function processSlashCommandResult({ setChatHistory, exit, onShowConfigSelector, + onShowUpdateSelector, onShowModelSelector, onShowMCPSelector, onShowSessionSelector, @@ -78,6 +80,11 @@ export function processSlashCommandResult({ return null; } + if (result.openUpdateSelector) { + onShowUpdateSelector?.(); + return null; + } + if (result.openConfigSelector) { onShowConfigSelector(); return null; diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index c62854ed4..93926880e 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -51,6 +51,7 @@ export function useChat({ additionalPrompts, onShowConfigSelector, onShowModelSelector, + onShowUpdateSelector, onShowMCPSelector, onShowSessionSelector, onLoginPrompt: _onLoginPrompt, @@ -374,6 +375,7 @@ export function useChat({ onShowModelSelector, onShowMCPSelector, onShowSessionSelector, + onShowUpdateSelector, onClear, }); diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts index a9a840184..8e937802b 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -15,6 +15,7 @@ export interface UseChatProps { additionalPrompts?: string[]; onShowConfigSelector: () => void; onShowMCPSelector: () => void; + onShowUpdateSelector: () => void; onShowModelSelector?: () => void; onShowSessionSelector?: () => void; onLoginPrompt?: (promptText: string) => Promise; @@ -57,6 +58,7 @@ export interface SlashCommandResult { openConfigSelector?: boolean; openModelSelector?: boolean; openMcpSelector?: boolean; + openUpdateSelector?: boolean; openSessionSelector?: boolean; compact?: boolean; }