feat: update service part 1

This commit is contained in:
Dallin Romney 2025-09-02 22:27:47 -07:00
parent 1ff23a6e67
commit 75fd033d2c
14 changed files with 407 additions and 25 deletions

View file

@ -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",
};

View file

@ -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",

View file

@ -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<UpdateServiceState>): void {
this.state = {
...this.state,
...partialState,
};
serviceContainer.set(this.serviceName, this.state);
}
}

View file

@ -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

View file

@ -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;
/**

View file

@ -259,22 +259,16 @@ const commandHandlers: Record<string, CommandHandler> = {
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<SlashCommandResult | null> {
// Only trigger slash commands if slash is the very first character
if (!input.startsWith("/") || !input.trim().startsWith("/")) {
return null;

View file

@ -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<LoadingTextProps> = ({
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 color={color}>
{text}
{dots}
</Text>
);
};

View file

@ -208,6 +208,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
onShowConfigSelector: () => navigateTo("config"),
onShowModelSelector: () => navigateTo("model"),
onShowMCPSelector: () => navigateTo("mcp"),
onShowUpdateSelector: () => navigateTo("update"),
onShowSessionSelector: () => navigateTo("session"),
onLoginPrompt: handleLoginPrompt,
onReload: handleReload,

View file

@ -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<UpdateSelectorProps> = ({ onCancel }) => {
const [selectedIndex, setSelectedIndex] = useState(0);
const updateServiceState = useService<UpdateServiceState>(
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 (
<Selector
title="Update Continue CLI"
options={options}
selectedIndex={selectedIndex}
loading={!!isWorking}
error={error}
loadingMessage={loadingMessage}
currentId={null}
onSelect={handleSelect}
onCancel={onCancel}
onNavigate={setSelectedIndex}
/>
);
};

View file

@ -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<ScreenContentProps> = ({
return <MCPSelector onCancel={closeCurrentScreen} />;
}
if (isScreenActive("update")) {
return <UpdateSelector onCancel={closeCurrentScreen} />;
}
// Model selector
if (isScreenActive("model")) {
return (

View file

@ -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 {

View file

@ -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;

View file

@ -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,
});

View file

@ -15,6 +15,7 @@ export interface UseChatProps {
additionalPrompts?: string[];
onShowConfigSelector: () => void;
onShowMCPSelector: () => void;
onShowUpdateSelector: () => void;
onShowModelSelector?: () => void;
onShowSessionSelector?: () => void;
onLoginPrompt?: (promptText: string) => Promise<string>;
@ -57,6 +58,7 @@ export interface SlashCommandResult {
openConfigSelector?: boolean;
openModelSelector?: boolean;
openMcpSelector?: boolean;
openUpdateSelector?: boolean;
openSessionSelector?: boolean;
compact?: boolean;
}