Merge pull request #79 from continuedev/free-trial

Free-trial
This commit is contained in:
Nate Sesti 2025-07-20 15:45:53 -07:00 • committed by GitHub
commit d755ad540a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 856 additions and 65 deletions

View file

@ -15,6 +15,8 @@ export default {
"<rootDir>/node_modules/ink-testing-library/build/index.js",
"^./SyntaxHighlighter\\.js$":
"<rootDir>/src/ui/__mocks__/SyntaxHighlighter.ts",
"^./FreeTrialStatus\\.js$":
"<rootDir>/src/ui/__mocks__/FreeTrialStatus.tsx",
},
extensionsToTreatAsEsm: [".ts", ".tsx"],
preset: "ts-jest/presets/default-esm",
@ -23,6 +25,7 @@ export default {
testPathIgnorePatterns: ["<rootDir>/dist/"],
modulePathIgnorePatterns: ["<rootDir>/dist/"],
transformIgnorePatterns: ["node_modules/(?!(highlight.js|lowlight)/)"],
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
globals: {
__dirname: path.dirname(fileURLToPath(import.meta.url)),
__filename: path.resolve(fileURLToPath(import.meta.url)),

2
jest.setup.ts Normal file
View file

@ -0,0 +1,2 @@
// Disable telemetry for tests
process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0";

View file

@ -44,10 +44,9 @@ async function loadRuleFromHub(slug: string): Promise<string> {
}
const [ownerSlug, ruleSlug] = parts;
const hubUrl = env.apiBase;
const downloadUrl = new URL(
`v0/${ownerSlug}/${ruleSlug}/latest/download`,
hubUrl
env.apiBase
);
try {

View file

@ -1,7 +1,3 @@
import {
Configuration,
DefaultApi,
} from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import * as fs from "fs";
import open from "open";
@ -12,6 +8,7 @@ import { env } from "../env.js";
// Polyfill fetch for Node < 18
import nodeFetch from "node-fetch";
import { getApiClient } from "../config.js";
if (!globalThis.fetch) {
globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch;
}
@ -503,11 +500,7 @@ export async function ensureOrganization(
}
// Need to select organization
const apiClient = new DefaultApi(
new Configuration({
accessToken: authenticatedConfig.accessToken,
})
);
const apiClient = getApiClient(authenticatedConfig.accessToken);
try {
const resp = await apiClient.listOrganizations();
@ -580,11 +573,7 @@ export async function listUserOrganizations(): Promise<
return null;
}
const apiClient = new DefaultApi(
new Configuration({
accessToken: authConfig.accessToken,
})
);
const apiClient = getApiClient(authConfig.accessToken);
try {
const resp = await apiClient.listOrganizations();

View file

@ -2,7 +2,11 @@ import chalk from "chalk";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import * as readlineSync from "readline-sync";
import { CONTINUE_ASCII_ART } from "../asciiArt.js";
import { ensureOrganization, loadAuthConfig, getOrganizationId } from "../auth/workos.js";
import {
ensureOrganization,
getOrganizationId,
loadAuthConfig,
} from "../auth/workos.js";
import { introMessage } from "../intro.js";
import { configureLogger } from "../logger.js";
import { initializeWithOnboarding } from "../onboarding.js";
@ -59,6 +63,7 @@ async function initializeChat(options: ChatOptions) {
llmApi: result.llmApi,
model: result.model,
mcpService: result.mcpService,
apiClient: result.apiClient,
};
}
@ -67,11 +72,13 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
configureLogger(options.headless ?? false);
try {
let { config, llmApi, model, mcpService, apiClient } = await initializeChat(
options
);
// Record session start
telemetryService.recordSessionStart();
let { config, llmApi, model, mcpService } = await initializeChat(options);
// Start active time tracking
telemetryService.startActiveTime();
@ -82,6 +89,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
llmApi,
model,
mcpService,
apiClient,
prompt,
options.resume,
options.config,
@ -179,4 +187,4 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
// Stop active time tracking
telemetryService.stopActiveTime();
}
}
}

View file

@ -113,16 +113,26 @@ async function loadConfigYaml(
return unrollResult.config;
}
export function getApiClient(
accessToken: string | undefined | null
): DefaultApi {
return new DefaultApi(
new Configuration({
basePath: env.apiBase.replace(/\/$/, ""),
accessToken: accessToken ?? undefined,
})
);
}
export async function loadConfig(
authConfig: AuthConfig,
config: string | undefined,
organizationId: string | null
organizationId: string | null,
apiClient?: DefaultApiInterface
): Promise<AssistantUnrolled> {
const apiClient = new DefaultApi(
new Configuration({
accessToken: authConfig?.accessToken ?? undefined,
})
);
if (!apiClient) {
apiClient = getApiClient(authConfig?.accessToken);
}
if (!config) {
// Check if there's a saved assistant slug in auth config
@ -204,11 +214,18 @@ export async function initialize(
llmApi: BaseLlmApi;
model: ModelConfig;
mcpService: MCPService;
apiClient: DefaultApiInterface;
}> {
const organizationId = getOrganizationId(authConfig);
const config = await loadConfig(authConfig, configPath, organizationId);
const apiClient = getApiClient(authConfig?.accessToken);
const config = await loadConfig(
authConfig,
configPath,
organizationId,
apiClient
);
const [llmApi, model] = getLlmApi(config, authConfig);
const mcpService = await MCPService.create(config);
return { config, llmApi, model, mcpService };
return { config, llmApi, model, mcpService, apiClient };
}

181
src/freeTrialTransition.ts Normal file
View file

@ -0,0 +1,181 @@
import chalk from "chalk";
import { spawn } from "child_process";
import * as fs from "fs";
import open from "open";
import * as os from "os";
import * as path from "path";
import * as readlineSync from "readline-sync";
import * as YAML from "yaml";
import { env } from "./env.js";
const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
/**
* Creates or updates the local config with Anthropic API key
*/
async function createOrUpdateConfig(apiKey: string): Promise<void> {
const configDir = path.dirname(CONFIG_PATH);
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
const newModel = {
uses: "anthropic/claude-4-sonnet",
with: {
ANTHROPIC_API_KEY: apiKey,
},
};
if (fs.existsSync(CONFIG_PATH)) {
const existingContent = fs.readFileSync(CONFIG_PATH, "utf8");
let config;
try {
config = YAML.parse(existingContent);
// Make sure models array exists
if (!config.models) {
config.models = [];
}
// Check if model already exists
const existingModelIndex = config.models.findIndex(
(model: any) => model.uses === "anthropic/claude-4-sonnet"
);
if (existingModelIndex >= 0) {
// Update existing model
config.models[existingModelIndex].with.ANTHROPIC_API_KEY = apiKey;
} else {
// Add new model
config.models.push(newModel);
}
} catch (error) {
// If parsing fails, create a new config
config = {
name: "Local Config",
version: "1.0.0",
schema: "v1",
models: [newModel],
};
}
// Write back to file
fs.writeFileSync(CONFIG_PATH, YAML.stringify(config));
} else {
// Create new config file
const config = {
name: "Local Config",
version: "1.0.0",
schema: "v1",
models: [newModel],
};
fs.writeFileSync(CONFIG_PATH, YAML.stringify(config));
}
}
/**
* Handles the free trial transition flow for users who have maxed out their free trial
* This function provides a specialized flow that:
* 1. Assumes the user is already authenticated
* 2. Provides two specific options for continuing
* 3. Returns to the chat without restarting the entire CLI
*/
export async function handleMaxedOutFreeTrial(): Promise<void> {
// Clear the screen but don't show ASCII art - keep it minimal since we're resuming a conversation
console.clear();
console.log(chalk.yellow("🚀 Free trial limit reached!\n"));
console.log("Choose how you'd like to Continue:");
console.log(chalk.white("1. 💳 Sign up for models add-on"));
console.log(chalk.white("2. 🔑 Enter your Anthropic API key"));
const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), {
limit: ["1", "2", ""],
limitMessage: chalk.dim("Please enter 1 or 2"),
});
if (choice === "1" || choice === "") {
// Option 1: Open models setup page
const modelsUrl = new URL("setup-models", env.appUrl).toString();
console.log(chalk.blue(`Opening ${modelsUrl}...`));
try {
await open(modelsUrl);
console.log(chalk.green("\n✓ Browser opened successfully!"));
console.log(
chalk.dim(
"After setting up your models subscription, restart the CLI to continue."
)
);
} catch (error) {
console.log(chalk.yellow("\n⚠ Could not open browser automatically"));
console.log(chalk.white(`Please visit: ${modelsUrl}`));
console.log(
chalk.dim(
"After setting up your models subscription, restart the CLI to continue."
)
);
}
// Wait for user to acknowledge
readlineSync.question(chalk.dim("\nPress Enter to exit..."));
process.exit(0);
} else if (choice === "2") {
// Option 2: Enter Anthropic API key
const apiKey = readlineSync.question(
chalk.white("\nEnter your Anthropic API key: "),
{
limit: /^sk-ant-.+$/, // Must start with "sk-ant-" and have additional characters
limitMessage: chalk.dim(
"Please enter a valid Anthropic key that starts with 'sk-ant'"
),
hideEchoBack: true,
}
);
if (!apiKey || !apiKey.startsWith("sk-ant-")) {
console.log(
chalk.red(
"❌ Invalid Anthropic API key. Please make sure it starts with 'sk-ant'"
)
);
process.exit(1);
}
try {
await createOrUpdateConfig(apiKey);
console.log(chalk.green(`✓ API key saved successfully!`));
} catch (error) {
console.log(chalk.red(`❌ Error saving API key: ${error}`));
process.exit(1);
}
}
// After setup completes, restart the CLI to resume the conversation
console.log(
chalk.green("\n🔄 Restarting Continue CLI to resume your conversation...\n")
);
// Get the path to the current script
const scriptPath = path.resolve(process.argv[1]);
// Restart the CLI with the same arguments, except for the first two (node and script path)
// Use spawn instead of spawnSync, since we want to exit this process
const child = spawn(
process.execPath,
[scriptPath, ...process.argv.slice(2)],
{
stdio: "inherit",
detached: true,
}
);
// Unref the child to allow the parent process to exit
child.unref();
// Exit the current process
process.exit(0);
}

View file

@ -1,5 +1,6 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import * as fs from "fs";
import * as os from "os";
@ -17,6 +18,7 @@ export interface OnboardingResult {
llmApi: BaseLlmApi;
model: ModelConfig;
mcpService: MCPService;
apiClient: DefaultApiInterface;
wasOnboarded: boolean;
}
@ -251,9 +253,11 @@ async function injectRulesIntoConfig(
// Combine processed rules with existing system message if the config has one
const existingSystemMessage = (modifiedConfig as any).systemMessage || "";
const rulesSection = processedRules.join("\n\n");
if (existingSystemMessage) {
(modifiedConfig as any).systemMessage = `${existingSystemMessage}\n\n${rulesSection}`;
(
modifiedConfig as any
).systemMessage = `${existingSystemMessage}\n\n${rulesSection}`;
} else {
(modifiedConfig as any).systemMessage = rulesSection;
}
@ -285,4 +289,4 @@ export async function initializeWithOnboarding(
}
return result;
}
}

View file

@ -174,9 +174,21 @@ async function processStreamingResponse(
break;
}
// Safety check: ensure chunk has the expected structure
if (!chunk.choices || !chunk.choices[0]) {
logger.warn("Malformed chunk received - missing choices", { chunk });
continue;
}
const choice = chunk.choices[0];
if (!choice.delta) {
logger.warn("Malformed chunk received - missing delta", { chunk });
continue;
}
// Handle regular content
if (chunk.choices[0].delta.content) {
const content = chunk.choices[0].delta.content;
if (choice.delta.content) {
const content = choice.delta.content;
if (callbacks?.onContent) {
callbacks.onContent(content);
} else if (!isHeadless) {
@ -186,8 +198,8 @@ async function processStreamingResponse(
}
// Handle tool calls
if (chunk.choices[0].delta.tool_calls) {
for (const toolCallDelta of chunk.choices[0].delta.tool_calls) {
if (choice.delta.tool_calls) {
for (const toolCallDelta of choice.delta.tool_calls) {
// Get or create tool call
if (toolCallDelta.id) {
if (!toolCallsMap.has(toolCallDelta.id)) {
@ -455,4 +467,4 @@ export async function streamChatResponse(
});
return fullResponse;
}
}

View file

@ -1,7 +1,3 @@
import {
Configuration,
DefaultApi,
} from "@continuedev/sdk/dist/api/dist/index.js";
import * as fs from "fs";
import { Box, Text, useInput } from "ink";
import * as os from "os";
@ -12,6 +8,7 @@ import {
getOrganizationId,
loadAuthConfig,
} from "../auth/workos.js";
import { getApiClient } from "../config.js";
interface ConfigOption {
id: string;
@ -56,11 +53,7 @@ const ConfigSelector: React.FC<ConfigSelectorProps> = ({
// Add assistants from current organization if authenticated
if (accessToken) {
const apiClient = new DefaultApi(
new Configuration({
accessToken,
})
);
const apiClient = getApiClient(accessToken);
try {
const assistants = await apiClient.listAssistants({
@ -69,13 +62,13 @@ const ConfigSelector: React.FC<ConfigSelectorProps> = ({
});
for (const assistant of assistants) {
// Use packageSlug as the slug and create a display name from ownerSlug/packageSlug
// Use full ownerSlug/packageSlug as the slug and create a display name from ownerSlug/packageSlug
const displayName = `${assistant.ownerSlug}/${assistant.packageSlug}`;
options.push({
id: assistant.packageSlug,
name: displayName,
type: "assistant",
slug: assistant.packageSlug,
slug: `${assistant.ownerSlug}/${assistant.packageSlug}`,
});
}
} catch (err) {

108
src/ui/FreeTrialStatus.tsx Normal file
View file

@ -0,0 +1,108 @@
import { ModelConfig } from "@continuedev/config-yaml";
import {
DefaultApiInterface,
GetFreeTrialStatus200Response,
} from "@continuedev/sdk/dist/api/dist/index.js";
import { Text } from "ink";
import React, { useEffect, useState } from "react";
export function isModelUsingFreeTrial(model: ModelConfig): boolean {
return (
model.provider === "continue-proxy" &&
(model as any).apiKeyLocation.startsWith("free_trial:")
);
}
interface FreeTrialStatusProps {
apiClient?: DefaultApiInterface;
onTransitionStateChange?: (isShowingTransition: boolean) => void;
model: ModelConfig;
}
const FreeTrialStatus: React.FC<FreeTrialStatusProps> = ({
apiClient,
onTransitionStateChange,
model,
}) => {
const [status, setStatus] = useState<GetFreeTrialStatus200Response | null>(
null
);
const [loading, setLoading] = useState(true);
const fetchStatus = async () => {
try {
if (!apiClient) {
setStatus(null);
setLoading(false);
return;
}
const response = await apiClient.getFreeTrialStatus();
setStatus(response);
setLoading(false);
} catch (error) {
// Silently handle errors - component returns null if no status
setStatus(null);
setLoading(false);
}
};
useEffect(() => {
// Initial fetch
fetchStatus();
// Don't poll in test environment
if (process.env.NODE_ENV === "test") {
return;
}
// Poll every 5 seconds
const interval = setInterval(fetchStatus, 5000);
return () => clearInterval(interval);
}, []);
// Check if user has maxed out their free trial and notify parent
useEffect(() => {
if (!status || !status.optedInToFreeTrial || loading) {
// No transition needed
if (onTransitionStateChange) {
onTransitionStateChange(false);
}
return;
}
const chatUsed = status.chatCount ?? 0;
const chatLimit = status.chatLimit;
// Check if user has maxed out their free trial
const shouldShowTransition =
chatUsed >= chatLimit && isModelUsingFreeTrial(model);
if (onTransitionStateChange) {
onTransitionStateChange(shouldShowTransition);
}
}, [status, loading, onTransitionStateChange, model]);
// Don't render anything while loading or if no status
if (
loading ||
!status ||
!status.optedInToFreeTrial ||
!isModelUsingFreeTrial(model)
) {
return null;
}
const chatUsed = status.chatCount ?? 0;
const chatLimit = status.chatLimit;
// Only show the normal status text - transition UI is handled by parent
return (
<Text color="dim">
{chatUsed}/{chatLimit} free trial
</Text>
);
};
export default FreeTrialStatus;

View file

@ -0,0 +1,304 @@
import * as fs from "fs";
import { Box, Text, useInput } from "ink";
import open from "open";
import * as os from "os";
import * as path from "path";
import React, { useState } from "react";
import * as YAML from "yaml";
import { env } from "../env.js";
const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
interface FreeTrialTransitionUIProps {
onComplete: () => void;
onSwitchToLocalConfig?: () => void;
onFullReload?: () => void;
}
/**
* Creates or updates the local config with Anthropic API key
*/
async function createOrUpdateConfig(apiKey: string): Promise<void> {
const configDir = path.dirname(CONFIG_PATH);
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
const newModel = {
uses: "anthropic/claude-4-sonnet",
with: {
ANTHROPIC_API_KEY: apiKey,
},
};
if (fs.existsSync(CONFIG_PATH)) {
const existingContent = fs.readFileSync(CONFIG_PATH, "utf8");
let config;
try {
config = YAML.parse(existingContent);
// Make sure models array exists
if (!config.models) {
config.models = [];
}
// Check if model already exists
const existingModelIndex = config.models.findIndex(
(model: any) => model.uses === "anthropic/claude-4-sonnet"
);
if (existingModelIndex >= 0) {
// Update existing model
config.models[existingModelIndex].with.ANTHROPIC_API_KEY = apiKey;
} else {
// Add new model
config.models.push(newModel);
}
} catch (error) {
// If parsing fails, create a new config
config = {
name: "Local Config",
version: "1.0.0",
schema: "v1",
models: [newModel],
};
}
// Write back to file
fs.writeFileSync(CONFIG_PATH, YAML.stringify(config));
} else {
// Create new config file
const config = {
name: "Local Config",
version: "1.0.0",
schema: "v1",
models: [newModel],
};
fs.writeFileSync(CONFIG_PATH, YAML.stringify(config));
}
}
const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
onComplete,
onSwitchToLocalConfig,
onFullReload,
}) => {
const [currentStep, setCurrentStep] = useState<
"choice" | "enterApiKey" | "processing" | "success" | "error"
>("choice");
const [selectedOption, setSelectedOption] = useState(1);
const [apiKey, setApiKey] = useState("");
const [errorMessage, setErrorMessage] = useState("");
const [successMessage, setSuccessMessage] = useState("");
const [wasModelsSetup, setWasModelsSetup] = useState(false);
useInput((input, key) => {
if (currentStep === "choice") {
if (key.upArrow && selectedOption > 1) {
setSelectedOption(selectedOption - 1);
} else if (key.downArrow && selectedOption < 2) {
setSelectedOption(selectedOption + 1);
} else if (input === "1") {
setSelectedOption(1);
} else if (input === "2") {
setSelectedOption(2);
} else if (key.return) {
handleOptionSelect();
}
} else if (currentStep === "enterApiKey") {
if (key.return) {
if (apiKey && apiKey.startsWith("sk-ant-")) {
handleApiKeySubmit();
} else {
setErrorMessage(
"Please enter a valid Anthropic API key that starts with 'sk-ant-'"
);
}
} else if (key.backspace || key.delete) {
setApiKey(apiKey.slice(0, -1));
setErrorMessage("");
} else if (input && !key.ctrl && !key.meta) {
setApiKey(apiKey + input);
setErrorMessage("");
}
} else if (currentStep === "success" || currentStep === "error") {
if (key.return) {
// If user went through models setup, do a full reload to register their purchase
if (wasModelsSetup && onFullReload) {
onFullReload();
} else {
onComplete();
}
}
}
});
const handleOptionSelect = async () => {
if (selectedOption === 1) {
// Option 1: Open models setup page
setCurrentStep("processing");
const modelsUrl = new URL("setup-models", env.appUrl).toString();
setWasModelsSetup(true); // Track that user went through models setup
try {
await open(modelsUrl);
setSuccessMessage(
`Browser opened to ${modelsUrl}. After setting up your models subscription, press Enter to continue.`
);
setCurrentStep("success");
} catch (error) {
setErrorMessage(
`Could not open browser automatically. Please visit: ${modelsUrl}. After setting up your models subscription, press Enter to continue.`
);
setCurrentStep("error");
}
} else {
// Option 2: Enter API key
setCurrentStep("enterApiKey");
setWasModelsSetup(false); // This is not models setup
}
};
const handleApiKeySubmit = async () => {
setCurrentStep("processing");
try {
await createOrUpdateConfig(apiKey);
setSuccessMessage(
"✓ API key saved successfully! Switching to local configuration..."
);
setCurrentStep("success");
// After a brief delay, switch to local configuration
setTimeout(() => {
if (onSwitchToLocalConfig) {
onSwitchToLocalConfig();
} else {
onComplete();
}
}, 1000);
} catch (error) {
setErrorMessage(
`❌ Error saving API key: ${error}. Press Enter to try again.`
);
setCurrentStep("error");
}
};
if (currentStep === "choice") {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="yellow"
>
<Text bold color="yellow">
🚀 Free trial limit reached!
</Text>
<Text>Choose how you'd like to continue:</Text>
<Text></Text>
<Text color={selectedOption === 1 ? "cyan" : "white"}>
{selectedOption === 1 ? "▶ " : " "}1. 💳 Sign up for models add-on
(recommended)
</Text>
<Text color={selectedOption === 2 ? "cyan" : "white"}>
{selectedOption === 2 ? "▶ " : " "}2. 🔑 Enter your Anthropic API key
</Text>
<Text></Text>
<Text color="gray">
Use ↑↓ arrows or 1/2 to select, Enter to confirm
</Text>
</Box>
);
}
if (currentStep === "enterApiKey") {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="yellow"
>
<Text bold color="yellow">
Enter your Anthropic API key
</Text>
<Text></Text>
<Text>API Key: {"*".repeat(apiKey.length)}</Text>
<Text></Text>
{errorMessage && <Text color="red">{errorMessage}</Text>}
<Text color="gray">
Type your API key and press Enter (must start with 'sk-ant-')
</Text>
</Box>
);
}
if (currentStep === "processing") {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="blue"
>
<Text bold color="blue">
Processing...
</Text>
<Text>Please wait...</Text>
</Box>
);
}
if (currentStep === "success") {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="green"
>
<Text bold color="green">
Success!
</Text>
<Text>{successMessage}</Text>
<Text></Text>
<Text color="gray">
{wasModelsSetup
? "Press Enter to reload and continue with your new subscription"
: "Press Enter to continue your conversation"}
</Text>
</Box>
);
}
if (currentStep === "error") {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="red"
>
<Text bold color="red">
Error
</Text>
<Text>{errorMessage}</Text>
<Text></Text>
<Text color="gray">
{wasModelsSetup
? "Press Enter to reload and try again"
: "Press Enter to continue"}
</Text>
</Box>
);
}
return null;
};
export default FreeTrialTransitionUI;

View file

@ -1,6 +1,9 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import { Box, Text } from "ink";
import * as os from "node:os";
import * as path from "node:path";
import React, { useEffect, useState } from "react";
import { loadAuthConfig } from "../auth/workos.js";
import { initialize } from "../config.js";
@ -8,6 +11,8 @@ import { introMessage } from "../intro.js";
import { MCPService } from "../mcp.js";
import ConfigSelector from "./ConfigSelector.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 { useMessageRenderer } from "./hooks/useMessageRenderer.js";
@ -18,11 +23,14 @@ import Timer from "./Timer.js";
import UpdateNotification from "./UpdateNotification.js";
import UserInput from "./UserInput.js";
const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
interface TUIChatProps {
config: AssistantUnrolled;
model: ModelConfig;
llmApi: BaseLlmApi;
mcpService: MCPService;
apiClient?: DefaultApiInterface;
configPath?: string;
initialPrompt?: string;
resume?: boolean;
@ -34,6 +42,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
model: initialModel,
llmApi: initialLlmApi,
mcpService: initialMcpService,
apiClient,
configPath,
initialPrompt,
resume,
@ -52,6 +61,10 @@ const TUIChat: React.FC<TUIChatProps> = ({
} | null>(null);
const [loginToken, setLoginToken] = useState("");
// State for free trial transition
const [isShowingFreeTrialTransition, setIsShowingFreeTrialTransition] =
useState(false);
// Start file indexing as soon as the component mounts
useEffect(() => {
// Start indexing files in the background immediately
@ -76,7 +89,37 @@ const TUIChat: React.FC<TUIChatProps> = ({
}
};
// Reload function for after login
// Full reload function - clears history and reinitializes (for models subscription)
const handleFullReload = async () => {
try {
// Reload auth config and reinitialize
const authConfig = loadAuthConfig();
const {
config: newAssistant,
llmApi: newLlmApi,
model: newModel,
mcpService: newMcpService,
} = await initialize(authConfig, configPath);
// Update all the state
setAssistant(newAssistant);
setModel(newModel);
setLlmApi(newLlmApi);
setMcpService(newMcpService);
// Clear the screen completely
process.stdout.write("\x1b[2J\x1b[H");
// Show the new intro message
introMessage(newAssistant, newModel, newMcpService);
} catch (error: any) {
console.error(
`Failed to reload after models subscription: ${error.message}`
);
}
};
// Partial reload function - preserves history (for login or other config changes)
const handleReload = async () => {
try {
// Reload auth config and reinitialize
@ -103,7 +146,56 @@ const TUIChat: React.FC<TUIChatProps> = ({
// Show the new intro message
introMessage(newAssistant, newModel, newMcpService);
} catch (error: any) {
console.error(`Failed to reload after login: ${error.message}`);
console.error(
`Failed to reload after configuration change: ${error.message}`
);
}
};
// Switch to local config - preserves chat history unlike handleReload
const handleSwitchToLocalConfig = async () => {
try {
// Reload auth config and reinitialize with local config path
const authConfig = loadAuthConfig();
const {
config: newAssistant,
llmApi: newLlmApi,
model: newModel,
mcpService: newMcpService,
} = await initialize(authConfig, CONFIG_PATH);
// Update configuration state but preserve chat history
setAssistant(newAssistant);
setModel(newModel);
setLlmApi(newLlmApi);
setMcpService(newMcpService);
// Add a system message to indicate the configuration switch
setMessages((prev) => [
...prev,
{
role: "system",
content:
"✓ Switched to local configuration with your Anthropic API key",
messageType: "system" as const,
},
]);
// Don't clear screen or reset chat history - just continue the conversation!
} catch (error: any) {
console.error(
`Failed to switch to local configuration: ${error.message}`
);
// Show error message in chat but don't break the flow
setMessages((prev) => [
...prev,
{
role: "system",
content: `❌ Error switching to local configuration: ${error.message}`,
messageType: "system" as const,
},
]);
}
};
@ -170,6 +262,29 @@ const TUIChat: React.FC<TUIChatProps> = ({
onChatReset: resetChatHistory,
});
// Handle free trial transition completion
const handleFreeTrialTransitionComplete = () => {
setIsShowingFreeTrialTransition(false);
handleReload();
};
const handleFreeTrialSwitchToLocal = () => {
setIsShowingFreeTrialTransition(false);
handleSwitchToLocalConfig();
};
const handleFreeTrialFullReload = () => {
setIsShowingFreeTrialTransition(false);
handleFullReload();
};
// Determine if input should be disabled
const isInputDisabled =
showOrgSelector ||
showConfigSelector ||
!!loginPrompt ||
isShowingFreeTrialTransition;
return (
<Box flexDirection="column" height="100%">
{/* Chat history - takes up all available space above input */}
@ -230,26 +345,44 @@ const TUIChat: React.FC<TUIChatProps> = ({
/>
)}
{/* Input area - always at bottom */}
<UserInput
onSubmit={handleUserMessage}
isWaitingForResponse={isWaitingForResponse}
inputMode={inputMode}
onInterrupt={handleInterrupt}
assistant={assistant}
onFileAttached={handleFileAttached}
disabled={showOrgSelector || showConfigSelector || !!loginPrompt}
/>
{/* Free trial transition UI - replaces input when active */}
{isShowingFreeTrialTransition && (
<FreeTrialTransitionUI
onComplete={handleFreeTrialTransitionComplete}
onSwitchToLocalConfig={handleFreeTrialSwitchToLocal}
onFullReload={handleFreeTrialFullReload}
/>
)}
{/* Input area - only show when not showing free trial transition */}
{!isShowingFreeTrialTransition && (
<UserInput
onSubmit={handleUserMessage}
isWaitingForResponse={isWaitingForResponse}
inputMode={inputMode}
onInterrupt={handleInterrupt}
assistant={assistant}
onFileAttached={handleFileAttached}
disabled={isInputDisabled}
/>
)}
{/* Free trial status and Continue CLI info - always show */}
<Box
marginRight={2}
justifyContent="space-between"
flexDirection="row"
marginLeft={2}
justifyContent="space-between"
alignItems="center"
>
<Box>
<FreeTrialStatus
apiClient={apiClient}
model={model}
onTransitionStateChange={setIsShowingFreeTrialTransition}
/>
</Box>
<Box marginRight={2}>
<UpdateNotification />
</Box>
<Text color="gray">● Continue CLI</Text>
</Box>
</Box>
</Box>

View file

@ -27,7 +27,7 @@ const UpdateNotification: React.FC = () => {
}, [currentVersion]);
if (!updateAvailable) {
return null;
return <Text color="gray">● Continue CLI</Text>;
}
return (

View file

@ -0,0 +1,11 @@
import React from "react";
// Mock FreeTrialStatus component that doesn't create any timers
const FreeTrialStatus: React.FC<any> = () => {
return null;
};
export default FreeTrialStatus;
export function isModelUsingFreeTrial(): boolean {
return false;
}

View file

@ -95,11 +95,35 @@ jest.mock("glob", () => ({
]),
}));
// Mock API Client
export class MockApiClient {
async getFreeTrialStatus() {
return {
optedInToFreeTrial: true,
chatCount: 5,
chatLimit: 100,
};
}
async listAssistants() {
return [];
}
async getAssistant() {
return { configResult: { config: mockAssistant } };
}
async listOrganizations() {
return { organizations: [] };
}
async syncSecrets() {
return [];
}
}
export const createProps = (overrides: any = {}) => ({
config: mockAssistant,
model: "test-model",
llmApi: new MockLlmApi(),
mcpService: new MockMCPService(),
apiClient: new MockApiClient(),
configPath: undefined,
initialPrompt: undefined,
resume: false,
@ -113,4 +137,4 @@ describe("TUIChat setup", () => {
expect(createProps).toBeDefined();
expect(mockAssistant).toBeDefined();
});
});
});

View file

@ -1,5 +1,6 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import { render } from "ink";
import React from "react";
import { introMessage } from "../intro.js";
@ -13,6 +14,7 @@ export async function startTUIChat(
llmApi: BaseLlmApi,
model: ModelConfig,
mcpService: MCPService,
apiClient?: DefaultApiInterface,
initialPrompt?: string,
resume?: boolean,
configPath?: string,
@ -28,6 +30,7 @@ export async function startTUIChat(
model,
llmApi,
mcpService,
apiClient,
configPath,
initialPrompt,
resume,