From 83181070308decf68f42d25b10fa4dbec1eab432 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 20 Jul 2025 12:41:33 -0700 Subject: [PATCH 1/7] fix config selector --- src/ui/ConfigSelector.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ui/ConfigSelector.tsx b/src/ui/ConfigSelector.tsx index 435f4f638..31d8a56a4 100644 --- a/src/ui/ConfigSelector.tsx +++ b/src/ui/ConfigSelector.tsx @@ -69,13 +69,13 @@ const ConfigSelector: React.FC = ({ }); 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) { @@ -197,4 +197,4 @@ const ConfigSelector: React.FC = ({ ); }; -export default ConfigSelector; +export default ConfigSelector; \ No newline at end of file From 00334b9920881e1e9c31c53039f6315490859c6b Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 20 Jul 2025 13:21:36 -0700 Subject: [PATCH 2/7] free trial indicator --- src/args.ts | 3 +- src/auth/workos.ts | 17 ++------- src/commands/chat.ts | 6 ++- src/config.ts | 33 ++++++++++++---- src/onboarding.ts | 10 +++-- src/streamChatResponse.ts | 22 ++++++++--- src/ui/ConfigSelector.tsx | 13 ++----- src/ui/FreeTrialStatus.tsx | 63 +++++++++++++++++++++++++++++++ src/ui/TUIChat.tsx | 21 +++++++++-- src/ui/__tests__/TUIChat.setup.ts | 26 ++++++++++++- src/ui/index.ts | 3 ++ 11 files changed, 170 insertions(+), 47 deletions(-) create mode 100644 src/ui/FreeTrialStatus.tsx diff --git a/src/args.ts b/src/args.ts index 5e8f07946..eb2efcbb0 100644 --- a/src/args.ts +++ b/src/args.ts @@ -44,10 +44,9 @@ async function loadRuleFromHub(slug: string): Promise { } const [ownerSlug, ruleSlug] = parts; - const hubUrl = env.apiBase; const downloadUrl = new URL( `v0/${ownerSlug}/${ruleSlug}/latest/download`, - hubUrl + env.apiBase ); try { diff --git a/src/auth/workos.ts b/src/auth/workos.ts index dc591c5cd..f465c1a1b 100644 --- a/src/auth/workos.ts +++ b/src/auth/workos.ts @@ -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(); diff --git a/src/commands/chat.ts b/src/commands/chat.ts index 6cf14d056..a94b0293d 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -50,6 +50,7 @@ async function initializeChat(options: ChatOptions) { llmApi: result.llmApi, model: result.model, mcpService: result.mcpService, + apiClient: result.apiClient, }; } @@ -58,7 +59,9 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { configureLogger(options.headless ?? false); try { - let { config, llmApi, model, mcpService } = await initializeChat(options); + let { config, llmApi, model, mcpService, apiClient } = await initializeChat( + options + ); // If not in headless mode, start the TUI chat (default) if (!options.headless) { @@ -67,6 +70,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { llmApi, model, mcpService, + apiClient, prompt, options.resume, options.config, diff --git a/src/config.ts b/src/config.ts index 5a741c41c..88e530845 100644 --- a/src/config.ts +++ b/src/config.ts @@ -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 { - 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 }; } diff --git a/src/onboarding.ts b/src/onboarding.ts index b0dba475f..6b5ccd076 100644 --- a/src/onboarding.ts +++ b/src/onboarding.ts @@ -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; -} \ No newline at end of file +} diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index f16d9e0ad..488307955 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -147,9 +147,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) { @@ -159,8 +171,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)) { @@ -386,4 +398,4 @@ export async function streamChatResponse( }); return fullResponse; -} +} \ No newline at end of file diff --git a/src/ui/ConfigSelector.tsx b/src/ui/ConfigSelector.tsx index 31d8a56a4..527ea2ce8 100644 --- a/src/ui/ConfigSelector.tsx +++ b/src/ui/ConfigSelector.tsx @@ -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 = ({ // 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({ @@ -197,4 +190,4 @@ const ConfigSelector: React.FC = ({ ); }; -export default ConfigSelector; \ No newline at end of file +export default ConfigSelector; diff --git a/src/ui/FreeTrialStatus.tsx b/src/ui/FreeTrialStatus.tsx new file mode 100644 index 000000000..e797c3a65 --- /dev/null +++ b/src/ui/FreeTrialStatus.tsx @@ -0,0 +1,63 @@ +import { + DefaultApiInterface, + GetFreeTrialStatus200Response, +} from "@continuedev/sdk/dist/api/dist/index.js"; +import { Box, Text } from "ink"; +import React, { useEffect, useState } from "react"; + +interface FreeTrialStatusProps { + apiClient?: DefaultApiInterface; +} + +const FreeTrialStatus: React.FC = ({ apiClient }) => { + const [status, setStatus] = useState( + 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(); + + // Poll every 5 seconds + const interval = setInterval(fetchStatus, 5000); + + return () => clearInterval(interval); + }, []); + + // Don't render anything while loading or if no status + if (loading || !status || !status.optedInToFreeTrial) { + return null; + } + + const chatUsed = status.chatCount ?? 0; + const chatLimit = status.chatLimit; + + return ( + + + {chatUsed}/{chatLimit} free trial + + + ); +}; + +export default FreeTrialStatus; diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index fd4fabe18..926d77a5a 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -1,13 +1,15 @@ 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 React, { useState, useEffect } from "react"; +import React, { useEffect, useState } from "react"; import { loadAuthConfig } from "../auth/workos.js"; import { initialize } from "../config.js"; 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 { useChat } from "./hooks/useChat.js"; import { useConfigSelector } from "./hooks/useConfigSelector.js"; import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; @@ -22,6 +24,7 @@ interface TUIChatProps { model: ModelConfig; llmApi: BaseLlmApi; mcpService: MCPService; + apiClient?: DefaultApiInterface; configPath?: string; initialPrompt?: string; resume?: boolean; @@ -33,6 +36,7 @@ const TUIChat: React.FC = ({ model: initialModel, llmApi: initialLlmApi, mcpService: initialMcpService, + apiClient, configPath, initialPrompt, resume, @@ -239,8 +243,19 @@ const TUIChat: React.FC = ({ onFileAttached={handleFileAttached} disabled={showOrgSelector || showConfigSelector || !!loginPrompt} /> - - ā— Continue CLI + + {/* Free trial status and Continue CLI info */} + + + + + + ā— Continue CLI + diff --git a/src/ui/__tests__/TUIChat.setup.ts b/src/ui/__tests__/TUIChat.setup.ts index 9a5c3b74e..ffcfb3890 100644 --- a/src/ui/__tests__/TUIChat.setup.ts +++ b/src/ui/__tests__/TUIChat.setup.ts @@ -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(); }); -}); \ No newline at end of file +}); diff --git a/src/ui/index.ts b/src/ui/index.ts index f18a09a7f..930a118fe 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -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, From 1256edc8df47c85c553067982a9ef257195e5e31 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 20 Jul 2025 14:15:34 -0700 Subject: [PATCH 3/7] free trial transition UI --- src/freeTrialTransition.ts | 181 ++++++++++++++++++ src/ui/FreeTrialStatus.tsx | 82 ++++++++- src/ui/FreeTrialTransitionUI.tsx | 304 +++++++++++++++++++++++++++++++ src/ui/TUIChat.tsx | 108 ++++++++++- 4 files changed, 664 insertions(+), 11 deletions(-) create mode 100644 src/freeTrialTransition.ts create mode 100644 src/ui/FreeTrialTransitionUI.tsx diff --git a/src/freeTrialTransition.ts b/src/freeTrialTransition.ts new file mode 100644 index 000000000..1a8910a3d --- /dev/null +++ b/src/freeTrialTransition.ts @@ -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 { + 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 { + // 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); +} diff --git a/src/ui/FreeTrialStatus.tsx b/src/ui/FreeTrialStatus.tsx index e797c3a65..cae46d744 100644 --- a/src/ui/FreeTrialStatus.tsx +++ b/src/ui/FreeTrialStatus.tsx @@ -2,18 +2,30 @@ import { DefaultApiInterface, GetFreeTrialStatus200Response, } from "@continuedev/sdk/dist/api/dist/index.js"; -import { Box, Text } from "ink"; +import { Text } from "ink"; import React, { useEffect, useState } from "react"; +import FreeTrialTransitionUI from "./FreeTrialTransitionUI.js"; interface FreeTrialStatusProps { apiClient?: DefaultApiInterface; + onTransitionComplete?: () => void; + onTransitionStateChange?: (isShowingTransition: boolean) => void; + onSwitchToLocalConfig?: () => void; + onFullReload?: () => void; } -const FreeTrialStatus: React.FC = ({ apiClient }) => { +const FreeTrialStatus: React.FC = ({ + apiClient, + onTransitionComplete, + onTransitionStateChange, + onSwitchToLocalConfig, + onFullReload, +}) => { const [status, setStatus] = useState( null ); const [loading, setLoading] = useState(true); + const [showTransition, setShowTransition] = useState(false); const fetchStatus = async () => { try { @@ -43,6 +55,63 @@ const FreeTrialStatus: React.FC = ({ apiClient }) => { return () => clearInterval(interval); }, []); + // Check if user has maxed out their free trial + useEffect(() => { + if (!status || !status.optedInToFreeTrial || loading) { + return; + } + + const chatUsed = status.chatCount ?? 0; + const chatLimit = status.chatLimit; + + // Check if user has maxed out their free trial + if (true) { + // if (chatUsed >= chatLimit) { + setShowTransition(true); + } + }, [status, loading]); + + // Notify parent when transition state changes + useEffect(() => { + if (onTransitionStateChange) { + onTransitionStateChange(showTransition); + } + }, [showTransition, onTransitionStateChange]); + + const handleTransitionComplete = () => { + setShowTransition(false); + // Optionally refetch status to check if they now have access + fetchStatus(); + if (onTransitionComplete) { + onTransitionComplete(); + } + }; + + const handleSwitchToLocalConfig = () => { + setShowTransition(false); + if (onSwitchToLocalConfig) { + onSwitchToLocalConfig(); + } + }; + + const handleFullReload = () => { + setShowTransition(false); + if (onFullReload) { + onFullReload(); + } + }; + + // Show transition UI if free trial is maxed out + if (showTransition) { + return ( + + ); + } + // Don't render anything while loading or if no status if (loading || !status || !status.optedInToFreeTrial) { return null; @@ -51,12 +120,11 @@ const FreeTrialStatus: React.FC = ({ apiClient }) => { const chatUsed = status.chatCount ?? 0; const chatLimit = status.chatLimit; + // Show normal status for active free trial return ( - - - {chatUsed}/{chatLimit} free trial - - + + {chatUsed}/{chatLimit} free trial + ); }; diff --git a/src/ui/FreeTrialTransitionUI.tsx b/src/ui/FreeTrialTransitionUI.tsx new file mode 100644 index 000000000..1f4584951 --- /dev/null +++ b/src/ui/FreeTrialTransitionUI.tsx @@ -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 { + 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 = ({ + 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 ( + + + šŸš€ Free trial limit reached! + + Choose how you'd like to continue: + + + {selectedOption === 1 ? "ā–¶ " : " "}1. šŸ’³ Sign up for models add-on + (recommended) + + + {selectedOption === 2 ? "ā–¶ " : " "}2. šŸ”‘ Enter your Anthropic API key + + + + Use ↑↓ arrows or 1/2 to select, Enter to confirm + + + ); + } + + if (currentStep === "enterApiKey") { + return ( + + + Enter your Anthropic API key + + + API Key: {"*".repeat(apiKey.length)} + + {errorMessage && {errorMessage}} + + Type your API key and press Enter (must start with 'sk-ant-') + + + ); + } + + if (currentStep === "processing") { + return ( + + + Processing... + + Please wait... + + ); + } + + if (currentStep === "success") { + return ( + + + Success! + + {successMessage} + + + {wasModelsSetup + ? "Press Enter to reload and continue with your new subscription" + : "Press Enter to continue your conversation"} + + + ); + } + + if (currentStep === "error") { + return ( + + + Error + + {errorMessage} + + + {wasModelsSetup + ? "Press Enter to reload and try again" + : "Press Enter to continue"} + + + ); + } + + return null; +}; + +export default FreeTrialTransitionUI; diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 926d77a5a..afd7eadd4 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -2,6 +2,8 @@ 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"; @@ -19,6 +21,8 @@ import OrganizationSelector from "./OrganizationSelector.js"; import Timer from "./Timer.js"; import UserInput from "./UserInput.js"; +const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); + interface TUIChatProps { config: AssistantUnrolled; model: ModelConfig; @@ -55,6 +59,10 @@ const TUIChat: React.FC = ({ } | 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 @@ -79,7 +87,37 @@ const TUIChat: React.FC = ({ } }; - // 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 @@ -106,7 +144,56 @@ const TUIChat: React.FC = ({ // 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, + }, + ]); } }; @@ -173,6 +260,13 @@ const TUIChat: React.FC = ({ onChatReset: resetChatHistory, }); + // Determine if input should be disabled + const isInputDisabled = + showOrgSelector || + showConfigSelector || + !!loginPrompt || + isShowingFreeTrialTransition; + return ( {/* Chat history - takes up all available space above input */} @@ -241,7 +335,7 @@ const TUIChat: React.FC = ({ onInterrupt={handleInterrupt} assistant={assistant} onFileAttached={handleFileAttached} - disabled={showOrgSelector || showConfigSelector || !!loginPrompt} + disabled={isInputDisabled} /> {/* Free trial status and Continue CLI info */} @@ -251,7 +345,13 @@ const TUIChat: React.FC = ({ alignItems="center" > - + ā— Continue CLI From 5c1866f04d7c982312068169e45e0382bfecd129 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 20 Jul 2025 15:07:20 -0700 Subject: [PATCH 4/7] updates to free trial logic --- src/ui/FreeTrialStatus.tsx | 80 +++++++++++++------------------------- src/ui/TUIChat.tsx | 54 ++++++++++++++++++------- 2 files changed, 66 insertions(+), 68 deletions(-) diff --git a/src/ui/FreeTrialStatus.tsx b/src/ui/FreeTrialStatus.tsx index cae46d744..4cd9fb566 100644 --- a/src/ui/FreeTrialStatus.tsx +++ b/src/ui/FreeTrialStatus.tsx @@ -1,31 +1,33 @@ +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"; -import FreeTrialTransitionUI from "./FreeTrialTransitionUI.js"; + +export function isModelUsingFreeTrial(model: ModelConfig): boolean { + return ( + model.provider === "continue-proxy" && + (model as any).apiKeyLocation.startsWith("free_trial:") + ); +} interface FreeTrialStatusProps { apiClient?: DefaultApiInterface; - onTransitionComplete?: () => void; onTransitionStateChange?: (isShowingTransition: boolean) => void; - onSwitchToLocalConfig?: () => void; - onFullReload?: () => void; + model: ModelConfig; } const FreeTrialStatus: React.FC = ({ apiClient, - onTransitionComplete, onTransitionStateChange, - onSwitchToLocalConfig, - onFullReload, + model, }) => { const [status, setStatus] = useState( null ); const [loading, setLoading] = useState(true); - const [showTransition, setShowTransition] = useState(false); const fetchStatus = async () => { try { @@ -55,9 +57,13 @@ const FreeTrialStatus: React.FC = ({ return () => clearInterval(interval); }, []); - // Check if user has maxed out their free trial + // 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; } @@ -65,62 +71,28 @@ const FreeTrialStatus: React.FC = ({ const chatLimit = status.chatLimit; // Check if user has maxed out their free trial - if (true) { - // if (chatUsed >= chatLimit) { - setShowTransition(true); - } - }, [status, loading]); + const shouldShowTransition = + chatUsed >= chatLimit && isModelUsingFreeTrial(model); - // Notify parent when transition state changes - useEffect(() => { if (onTransitionStateChange) { - onTransitionStateChange(showTransition); + onTransitionStateChange(shouldShowTransition); } - }, [showTransition, onTransitionStateChange]); - - const handleTransitionComplete = () => { - setShowTransition(false); - // Optionally refetch status to check if they now have access - fetchStatus(); - if (onTransitionComplete) { - onTransitionComplete(); - } - }; - - const handleSwitchToLocalConfig = () => { - setShowTransition(false); - if (onSwitchToLocalConfig) { - onSwitchToLocalConfig(); - } - }; - - const handleFullReload = () => { - setShowTransition(false); - if (onFullReload) { - onFullReload(); - } - }; - - // Show transition UI if free trial is maxed out - if (showTransition) { - return ( - - ); - } + }, [status, loading, onTransitionStateChange, model]); // Don't render anything while loading or if no status - if (loading || !status || !status.optedInToFreeTrial) { + if ( + loading || + !status || + !status.optedInToFreeTrial || + !isModelUsingFreeTrial(model) + ) { return null; } const chatUsed = status.chatCount ?? 0; const chatLimit = status.chatLimit; - // Show normal status for active free trial + // Only show the normal status text - transition UI is handled by parent return ( {chatUsed}/{chatLimit} free trial diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index afd7eadd4..8240286e6 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -12,6 +12,7 @@ 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"; @@ -260,6 +261,22 @@ const TUIChat: React.FC = ({ 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 || @@ -327,18 +344,29 @@ const TUIChat: React.FC = ({ /> )} - {/* Input area - always at bottom */} - + {/* Free trial transition UI - replaces input when active */} + {isShowingFreeTrialTransition && ( + + )} - {/* Free trial status and Continue CLI info */} + {/* Input area - only show when not showing free trial transition */} + {!isShowingFreeTrialTransition && ( + + )} + + {/* Free trial status and Continue CLI info - always show */} = ({ From 0181eb39b7b28840ed4b7af3d43f264c89aa0571 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 20 Jul 2025 15:10:13 -0700 Subject: [PATCH 5/7] fix: new line --- src/commands/chat.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/commands/chat.ts b/src/commands/chat.ts index 12ecbe712..b5def1f59 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -75,6 +75,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { let { config, llmApi, model, mcpService, apiClient } = await initializeChat( options ); + // Record session start telemetryService.recordSessionStart(); From ce25ca3e1aa9a9459230c149f7609d31d30b5d2d Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 20 Jul 2025 15:17:49 -0700 Subject: [PATCH 6/7] update layout --- src/ui/FreeTrialStatus.tsx | 2 +- src/ui/TUIChat.tsx | 3 +-- src/ui/UpdateNotification.tsx | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/ui/FreeTrialStatus.tsx b/src/ui/FreeTrialStatus.tsx index 4cd9fb566..8c67dbaef 100644 --- a/src/ui/FreeTrialStatus.tsx +++ b/src/ui/FreeTrialStatus.tsx @@ -94,7 +94,7 @@ const FreeTrialStatus: React.FC = ({ // Only show the normal status text - transition UI is handled by parent return ( - + {chatUsed}/{chatLimit} free trial ); diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index e04056ee6..82d852a29 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -379,10 +379,9 @@ const TUIChat: React.FC = ({ model={model} onTransitionStateChange={setIsShowingFreeTrialTransition} /> - - ā— Continue CLI + diff --git a/src/ui/UpdateNotification.tsx b/src/ui/UpdateNotification.tsx index dcf5cb438..5a80b5632 100644 --- a/src/ui/UpdateNotification.tsx +++ b/src/ui/UpdateNotification.tsx @@ -27,7 +27,7 @@ const UpdateNotification: React.FC = () => { }, [currentVersion]); if (!updateAvailable) { - return null; + return ā— Continue CLI; } return ( From 4de3c90eec8698d3097beaaee5b5734db651c5d7 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 20 Jul 2025 15:43:14 -0700 Subject: [PATCH 7/7] fix: hanging tests --- jest.config.mjs | 3 +++ jest.setup.ts | 2 ++ src/ui/FreeTrialStatus.tsx | 5 +++++ src/ui/__mocks__/FreeTrialStatus.tsx | 11 +++++++++++ 4 files changed, 21 insertions(+) create mode 100644 jest.setup.ts create mode 100644 src/ui/__mocks__/FreeTrialStatus.tsx diff --git a/jest.config.mjs b/jest.config.mjs index 9ed1d15ab..8407cab12 100644 --- a/jest.config.mjs +++ b/jest.config.mjs @@ -15,6 +15,8 @@ export default { "/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", @@ -23,6 +25,7 @@ export default { 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)), diff --git a/jest.setup.ts b/jest.setup.ts new file mode 100644 index 000000000..efd9d9715 --- /dev/null +++ b/jest.setup.ts @@ -0,0 +1,2 @@ +// Disable telemetry for tests +process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0"; \ No newline at end of file diff --git a/src/ui/FreeTrialStatus.tsx b/src/ui/FreeTrialStatus.tsx index 8c67dbaef..47a7a9c1a 100644 --- a/src/ui/FreeTrialStatus.tsx +++ b/src/ui/FreeTrialStatus.tsx @@ -51,6 +51,11 @@ const FreeTrialStatus: React.FC = ({ // 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); diff --git a/src/ui/__mocks__/FreeTrialStatus.tsx b/src/ui/__mocks__/FreeTrialStatus.tsx new file mode 100644 index 000000000..1f0ab6c20 --- /dev/null +++ b/src/ui/__mocks__/FreeTrialStatus.tsx @@ -0,0 +1,11 @@ +import React from "react"; + +// Mock FreeTrialStatus component that doesn't create any timers +const FreeTrialStatus: React.FC = () => { + return null; +}; + +export default FreeTrialStatus; +export function isModelUsingFreeTrial(): boolean { + return false; +} \ No newline at end of file