diff --git a/core/config/load.ts b/core/config/load.ts index e4c7e13c4..e152cdd18 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -346,12 +346,8 @@ async function intermediateToFinalConfig({ "summarize", ]); // Default to chat role if not specified - // Free trial provider will be completely ignored - let warnAboutFreeTrial = false; + // Free trial provider is no longer supported — hard-drop any such models models = models.filter((model) => model.providerName !== "free-trial"); - if (models.filter((m) => m.providerName === "free-trial").length) { - warnAboutFreeTrial = true; - } // Tab autocomplete model const tabAutocompleteModels: BaseLLM[] = []; @@ -373,9 +369,7 @@ async function intermediateToFinalConfig({ config.completionOptions, ); if (llm) { - if (llm.providerName === "free-trial") { - warnAboutFreeTrial = true; - } else { + if (llm.providerName !== "free-trial") { tabAutocompleteModels.push(llm); } } @@ -419,9 +413,6 @@ async function intermediateToFinalConfig({ } const { provider, ...options } = embedConfig; if (provider === "transformers.js" || provider === "free-trial") { - if (provider === "free-trial") { - warnAboutFreeTrial = true; - } return new TransformersJsEmbeddingsProvider(); } else { const cls = LLMClasses.find((c) => c.providerName === provider); @@ -459,7 +450,6 @@ async function intermediateToFinalConfig({ } const { name, params } = config.reranker as RerankerDescription; if (name === "free-trial") { - warnAboutFreeTrial = true; return null; } if (name === "llm") { @@ -492,14 +482,6 @@ async function intermediateToFinalConfig({ } const newReranker = getRerankingILLM(config.reranker); - if (warnAboutFreeTrial) { - errors.push({ - fatal: false, - message: - "Model provider 'free-trial' is no longer supported, will be ignored", - }); - } - const continueConfig: ContinueConfig = { ...config, contextProviders, diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 40278fdbe..4634dcefb 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -305,13 +305,13 @@ export async function configYamlToContinueConfig(options: { }); // Models - let warnAboutFreeTrial = false; const defaultModelRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"]; for (const model of config.models ?? []) { model.roles = model.roles ?? defaultModelRoles; // Default to all 4 chat-esque roles if not specified + // Free trial provider is no longer supported — hard-drop if (model.provider === "free-trial") { - warnAboutFreeTrial = true; + continue; } try { const llms = await llmsFromModelConfig({ @@ -386,14 +386,6 @@ export async function configYamlToContinueConfig(options: { ); } - if (warnAboutFreeTrial) { - localErrors.push({ - fatal: false, - message: - "Model provider 'free-trial' is no longer supported, will be ignored.", - }); - } - const { providers, errors: contextErrors } = loadConfigContextProviders( config.context, !!config.docs?.length, diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts index 013222ec0..bd4aebb22 100644 --- a/core/llm/streamChat.ts +++ b/core/llm/streamChat.ts @@ -1,12 +1,10 @@ import { fetchwithRequestOptions } from "@continuedev/fetch"; import { ChatMessage, IDE, PromptLog } from ".."; import { ConfigHandler } from "../config/ConfigHandler"; -import { usesCreditsBasedApiKey } from "../config/usesFreeTrialApiKey"; import { FromCoreProtocol, ToCoreProtocol } from "../protocol"; import { IMessenger, Message } from "../protocol/messenger"; import { TTS } from "../util/tts"; -import { isOutOfStarterCredits } from "./utils/starterCredits"; export async function* llmStreamChat( configHandler: ConfigHandler, @@ -136,8 +134,6 @@ export async function* llmStreamChat( void TTS.read(next.value?.completion); } - void checkForOutOfStarterCredits(configHandler, messenger); - if (!next.done) { throw new Error("Will never happen"); } @@ -149,24 +145,3 @@ export async function* llmStreamChat( throw error; } } - -async function checkForOutOfStarterCredits( - configHandler: ConfigHandler, - messenger: IMessenger, -) { - try { - const { config } = await configHandler.getSerializedConfig(); - const creditStatus = - await configHandler.controlPlaneClient.getCreditStatus(); - - if ( - config && - creditStatus && - isOutOfStarterCredits(usesCreditsBasedApiKey(config), creditStatus) - ) { - void messenger.request("freeTrialExceeded", undefined); - } - } catch (error) { - console.error("Error checking free trial status:", error); - } -} diff --git a/extensions/cli/src/freeTrialTransition.ts b/extensions/cli/src/freeTrialTransition.ts deleted file mode 100644 index 484b9d672..000000000 --- a/extensions/cli/src/freeTrialTransition.ts +++ /dev/null @@ -1,143 +0,0 @@ -import { spawn } from "child_process"; -import * as fs from "fs"; -import * as path from "path"; - -import chalk from "chalk"; -import { setConfigFilePermissions } from "core/util/paths.js"; -import open from "open"; - -import { env } from "./env.js"; -import { - getApiKeyValidationError, - isValidAnthropicApiKey, -} from "./util/apiKeyValidation.js"; -import { gracefulExit } from "./util/exit.js"; -import { question, questionWithChoices } from "./util/prompt.js"; -import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js"; - -const CONFIG_PATH = path.join(env.continueHome, "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 existingContent = fs.existsSync(CONFIG_PATH) - ? fs.readFileSync(CONFIG_PATH, "utf8") - : ""; - - const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey); - fs.writeFileSync(CONFIG_PATH, updatedContent); - setConfigFilePermissions(CONFIG_PATH); -} - -/** - * 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( - onReload?: () => Promise, -): 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 = await questionWithChoices( - chalk.yellow("\nEnter choice (1): "), - ["1", "2", ""], - "1", - 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 { - 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 - await question(chalk.dim("\nPress Enter to exit...")); - await gracefulExit(0); - } else if (choice === "2") { - // Option 2: Enter Anthropic API key - const apiKey = await question( - chalk.white("\nEnter your Anthropic API key: "), - ); - - if (!isValidAnthropicApiKey(apiKey)) { - console.log(chalk.red(`āŒ ${getApiKeyValidationError(apiKey)}`)); - await gracefulExit(1); - } - - try { - await createOrUpdateConfig(apiKey); - console.log(chalk.green(`āœ“ API key saved successfully!`)); - console.log(chalk.green("āœ“ Switching to local configuration...")); - - // If a reload callback is provided, use it instead of restarting - if (onReload) { - await onReload(); - return; - } - } catch (error) { - console.log(chalk.red(`āŒ Error saving API key: ${error}`)); - await gracefulExit(1); - } - } - - // Fallback: restart the CLI if no reload callback was provided - 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 - await gracefulExit(0); -} diff --git a/extensions/cli/src/ui/FreeTrialStatus.tsx b/extensions/cli/src/ui/FreeTrialStatus.tsx deleted file mode 100644 index 5a2c7c78d..000000000 --- a/extensions/cli/src/ui/FreeTrialStatus.tsx +++ /dev/null @@ -1,108 +0,0 @@ -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 = ({ - apiClient, - onTransitionStateChange, - model, -}) => { - 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 { - // 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 ( - - {chatUsed}/{chatLimit} free trial - - ); -}; - -export { FreeTrialStatus }; diff --git a/extensions/cli/src/ui/FreeTrialTransitionUI.tsx b/extensions/cli/src/ui/FreeTrialTransitionUI.tsx deleted file mode 100644 index 4b3cbbeb7..000000000 --- a/extensions/cli/src/ui/FreeTrialTransitionUI.tsx +++ /dev/null @@ -1,334 +0,0 @@ -import * as fs from "fs"; -import * as path from "path"; - -import { Box, Text, useInput } from "ink"; -import open from "open"; -import React, { useState } from "react"; -import useSWR from "swr"; - -import { listUserOrganizations } from "../auth/workos.js"; -import { env } from "../env.js"; -import { - getApiKeyValidationError, - isValidAnthropicApiKey, -} from "../util/apiKeyValidation.js"; -import { updateAnthropicModelInYaml } from "../util/yamlConfigUpdater.js"; - -import { useNavigation } from "./context/NavigationContext.js"; -import { defaultBoxStyles } from "./styles.js"; - -const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); - -// Helper functions for input handling -interface ChoiceInputOptions { - input: string; - key: any; - selectedOption: number; - setSelectedOption: (option: number) => void; - hasOrganizations: boolean; - handleOptionSelect: () => void; -} - -function handleChoiceInput(options: ChoiceInputOptions): void { - const { - input, - key, - selectedOption, - setSelectedOption, - hasOrganizations, - handleOptionSelect, - } = options; - if (key.upArrow && selectedOption > 1) { - setSelectedOption(selectedOption - 1); - } else if (key.downArrow && selectedOption < (hasOrganizations ? 4 : 3)) { - setSelectedOption(selectedOption + 1); - } else if (input === "1") { - setSelectedOption(1); - } else if (input === "2") { - setSelectedOption(2); - } else if (input === "3") { - setSelectedOption(3); - } else if (input === "4" && hasOrganizations) { - setSelectedOption(4); - } else if (key.return) { - handleOptionSelect(); - } -} - -interface ApiKeyInputOptions { - input: string; - key: any; - apiKey: string; - setApiKey: (key: string) => void; - setErrorMessage: (msg: string) => void; - handleApiKeySubmit: () => void; -} - -function handleApiKeyInput(options: ApiKeyInputOptions): void { - const { input, key, apiKey, setApiKey, setErrorMessage, handleApiKeySubmit } = - options; - if (key.return) { - if (isValidAnthropicApiKey(apiKey)) { - handleApiKeySubmit(); - } else { - setErrorMessage(getApiKeyValidationError(apiKey)); - } - } else if (key.backspace || key.delete) { - setApiKey(apiKey.slice(0, -1)); - setErrorMessage(""); - } else if (input && !key.ctrl && !key.meta) { - setApiKey(apiKey + input); - setErrorMessage(""); - } -} - -interface FreeTrialTransitionUIProps { - onReload: () => 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 existingContent = fs.existsSync(CONFIG_PATH) - ? fs.readFileSync(CONFIG_PATH, "utf8") - : ""; - - const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey); - fs.writeFileSync(CONFIG_PATH, updatedContent); -} - -const FreeTrialTransitionUI: React.FC = ({ - onReload, -}) => { - const { navigateTo, closeCurrentScreen } = useNavigation(); - 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); - - // Fetch organizations using SWR - const { data: organizations } = useSWR( - "organizations", - listUserOrganizations, - { - revalidateOnFocus: false, - revalidateOnReconnect: false, - shouldRetryOnError: false, - }, - ); - - const hasOrganizations = organizations && organizations.length > 0; - - useInput((input, key) => { - // Allow Escape to cancel immediately, but Ctrl+C uses two-stage exit - if (key.escape) { - closeCurrentScreen(); - return; - } - - // Handle Ctrl+C with two-stage exit (delegates to main process) - if (key.ctrl && input === "c") { - process.kill(process.pid, "SIGINT"); - return; - } - - if (currentStep === "choice") { - handleChoiceInput({ - input, - key, - selectedOption, - setSelectedOption, - hasOrganizations: !!hasOrganizations, - handleOptionSelect, - }); - } else if (currentStep === "enterApiKey") { - handleApiKeyInput({ - input, - key, - apiKey, - setApiKey, - setErrorMessage, - handleApiKeySubmit, - }); - } else if (currentStep === "success" || currentStep === "error") { - if (key.return) { - closeCurrentScreen(); - // If user went through models setup, do a full reload to register their purchase - if (wasModelsSetup) { - onReload(); - } - } - } - }); - - const handleOptionSelect = async () => { - if (selectedOption === 1) { - // Option 1: Open models setup page - setCurrentStep("processing"); - const modelsUrl = new URL("settings/billing", 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 { - setErrorMessage( - `Could not open browser automatically. Please visit: ${modelsUrl}. After setting up your models subscription, press Enter to continue.`, - ); - setCurrentStep("error"); - } - } else if (selectedOption === 2) { - // Option 2: Enter API key - setCurrentStep("enterApiKey"); - setWasModelsSetup(false); // This is not models setup - } else if (selectedOption === 3) { - // Option 3: Switch to different configuration - navigateTo("config"); - } else if (selectedOption === 4 && hasOrganizations) { - // Option 4: Switch to configuration (includes organization switching) - navigateTo("config"); - } - }; - - 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(() => { - closeCurrentScreen(); - onReload(); - }, 1000); - } catch (error) { - setErrorMessage( - `āŒ Error saving API key: ${error}. Press Enter to try again.`, - ); - setCurrentStep("error"); - } - }; - - if (currentStep === "choice") { - const options = [ - { num: 1, text: "šŸ’³ Sign up for models add-on (recommended)" }, - { num: 2, text: "šŸ”‘ Enter your Anthropic API key" }, - { num: 3, text: "āš™ļø Switch to a different configuration" }, - ]; - - if (hasOrganizations) { - options.push({ - num: 4, - text: "šŸ¢ Switch to organization configuration", - }); - } - - return ( - - - šŸš€ Free trial limit reached! - - Choose how you'd like to continue: - - {options.map((option) => ( - - {selectedOption === option.num ? "āž¤ " : " "} - {option.num}. {option.text} - - ))} - - - ↑/↓ to navigate or {hasOrganizations ? "1/2/3/4" : "1/2/3"} 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 { FreeTrialTransitionUI }; diff --git a/extensions/cli/src/ui/__mocks__/FreeTrialStatus.tsx b/extensions/cli/src/ui/__mocks__/FreeTrialStatus.tsx deleted file mode 100644 index 2359e7f5d..000000000 --- a/extensions/cli/src/ui/__mocks__/FreeTrialStatus.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import React from "react"; - -// Mock FreeTrialStatus component that doesn't create any timers -const FreeTrialStatus: React.FC = () => { - return null; -}; - -export { FreeTrialStatus }; -export function isModelUsingFreeTrial(): boolean { - return false; -} diff --git a/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx b/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx deleted file mode 100644 index dfb3b59ce..000000000 --- a/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx +++ /dev/null @@ -1,173 +0,0 @@ -import { render } from "ink-testing-library"; -import React from "react"; -import { vi } from "vitest"; - -import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js"; - -// Mock the 'open' module to prevent actual URL opening during tests -vi.mock("open", () => ({ - default: vi.fn(), -})); - -// Mock the NavigationContext -vi.mock("../context/NavigationContext.js", () => ({ - useNavigation: () => ({ - navigateTo: vi.fn(), - closeCurrentScreen: vi.fn(), - isScreenActive: vi.fn(() => false), - state: { currentScreen: "free-trial", screenData: null }, - }), -})); - -describe("FreeTrialTransitionUI - Rendering and Props Tests", () => { - const mockOnReload = vi.fn(); - - beforeEach(() => { - vi.clearAllMocks(); - }); - - describe("Initial Choice Screen Rendering", () => { - it("displays all three options with proper formatting", () => { - const { lastFrame } = render( - , - ); - - const frame = lastFrame(); - expect(frame).toContain("šŸš€ Free trial limit reached!"); - expect(frame).toContain("1. šŸ’³ Sign up for models add-on"); - expect(frame).toContain("2. šŸ”‘ Enter your Anthropic API key"); - expect(frame).toContain("3. āš™ļø Switch to a different configuration"); - expect(frame).toContain("↑/↓ to navigate or 1/2/3 to select"); - }); - - it("highlights first option by default", () => { - const { lastFrame } = render( - , - ); - - const frame = lastFrame(); - expect(frame).toContain("āž¤ 1. šŸ’³ Sign up for models add-on"); - expect(frame).not.toContain("āž¤ 2. šŸ”‘ Enter your Anthropic API key"); - expect(frame).not.toContain( - "āž¤ 3. āš™ļø Switch to a different configuration", - ); - }); - - it("renders without crashing when all props are provided", () => { - const { lastFrame } = render( - , - ); - - const frame = lastFrame(); - expect(frame).toBeDefined(); - expect(frame?.length).toBeGreaterThan(0); - }); - - it("renders without crashing when onShowConfigSelector is not provided", () => { - const { lastFrame } = render( - , - ); - - const frame = lastFrame(); - expect(frame).toBeDefined(); - expect(frame?.length).toBeGreaterThan(0); - expect(frame).toContain("3. āš™ļø Switch to a different configuration"); - }); - - it("includes proper user instructions", () => { - const { lastFrame } = render( - , - ); - - const frame = lastFrame(); - expect(frame).toContain("Choose how you'd like to continue:"); - expect(frame).toContain( - "↑/↓ to navigate or 1/2/3 to select, Enter to confirm", - ); - }); - - it("shows all options with proper descriptions", () => { - const { lastFrame } = render( - , - ); - - const frame = lastFrame(); - expect(frame).toContain("Sign up for models add-on (recommended)"); - expect(frame).toContain("Enter your Anthropic API key"); - expect(frame).toContain("Switch to a different configuration"); - }); - }); - - describe("Component Props and Interface", () => { - it("accepts all required callback props", () => { - // Test that component accepts and renders with all props - expect(() => { - render(); - }).not.toThrow(); - }); - - it("accepts optional onShowConfigSelector prop", () => { - // Test that component works without onShowConfigSelector - expect(() => { - render(); - }).not.toThrow(); - }); - }); - - describe("Visual Styling and Layout", () => { - it("renders with proper border styling", () => { - const { lastFrame } = render( - , - ); - - const frame = lastFrame(); - // Check for box border characters (unicode box drawing) - expect(frame).toMatch(/[╭╮╯╰│─]/); - }); - - it("displays with proper spacing and formatting", () => { - const { lastFrame } = render( - , - ); - - const frame = lastFrame(); - // Should have proper spacing between lines - expect(frame?.split("\n").length).toBeGreaterThan(5); - }); - - it("shows selection indicator on first option by default", () => { - const { lastFrame } = render( - , - ); - - const frame = lastFrame(); - const lines = frame?.split("\n") || []; - const modelsLine = lines.find((line) => - line.includes("Sign up for models add-on"), - ); - const apiKeyLine = lines.find((line) => - line.includes("Enter your Anthropic API key"), - ); - const configLine = lines.find((line) => - line.includes("Switch to a different configuration"), - ); - - expect(modelsLine).toContain("āž¤"); - expect(apiKeyLine).not.toContain("āž¤"); - expect(configLine).not.toContain("āž¤"); - }); - }); - - describe("URL Opening Security", () => { - it("should use mocked open function to prevent actual URL opening", async () => { - // This test verifies that we properly mock the 'open' module - // to prevent actual URLs from being opened during test runs - const openModule = await import("open"); - expect(openModule.default).toBeDefined(); - expect(typeof openModule.default).toBe("function"); - }); - }); -}); diff --git a/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.urlHandling.test.tsx b/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.urlHandling.test.tsx deleted file mode 100644 index d1aa186f3..000000000 --- a/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.urlHandling.test.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { vi } from "vitest"; - -// Test URL opening behavior without complex component rendering -describe("FreeTrialTransitionUI - URL Opening Security", () => { - it("should mock URL opening to prevent actual browser launches during tests", () => { - // This test verifies that we properly mock the 'open' module - // to prevent actual URLs from being opened during test runs - - // Import and check that open is mocked - const mockOpen = vi.fn(); - vi.mock("open", () => mockOpen); - - // Verify the mock is properly set up - expect(mockOpen).toBeDefined(); - expect(typeof mockOpen).toBe("function"); - }); - - it("should verify URL format for models setup", () => { - // Test the URL construction logic without actually opening URLs - const baseUrl = "https://test.continue.dev"; - const expectedUrl = new URL("setup-models", baseUrl).toString(); - - expect(expectedUrl).toBe("https://test.continue.dev/setup-models"); - }); - - it("should handle URL construction with different base URLs", () => { - // Test URL construction with various base URLs - const testCases = [ - { - base: "https://continue.dev", - expected: "https://continue.dev/setup-models", - }, - { - base: "https://app.continue.dev", - expected: "https://app.continue.dev/setup-models", - }, - { - base: "http://localhost:3000", - expected: "http://localhost:3000/setup-models", - }, - ]; - - testCases.forEach(({ base, expected }) => { - const url = new URL("setup-models", base).toString(); - expect(url).toBe(expected); - }); - }); - - it("should validate that mocking prevents security issues in tests", () => { - // This test documents the security consideration: - // Without proper mocking, tests could open arbitrary URLs in the user's browser - // The mock ensures this doesn't happen during automated test runs - - const openFunction = vi.fn(); - - // Simulate what would happen if URL opening was called - openFunction("https://malicious-site.com"); - - // Verify the mock was called instead of actual URL opening - expect(openFunction).toHaveBeenCalledWith("https://malicious-site.com"); - expect(openFunction).toHaveBeenCalledTimes(1); - - // In real usage, this would have opened a browser tab, but with mocking it's safe - }); -}); diff --git a/extensions/cli/src/ui/__tests__/TUIChat.freeTrialTransition.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.freeTrialTransition.test.tsx deleted file mode 100644 index cf913fe79..000000000 --- a/extensions/cli/src/ui/__tests__/TUIChat.freeTrialTransition.test.tsx +++ /dev/null @@ -1,21 +0,0 @@ -// Integration tests for free trial transition - simplified version - -describe("TUIChat - Free Trial Transition Integration", () => { - it("should integrate free trial transition with config selector", () => { - // This test verifies that the integration points exist - // More comprehensive integration tests would require complex mocking - // that is difficult to maintain and test reliably. - - // The key integration points are: - // 1. FreeTrialTransitionUI receives onShowConfigSelector callback - // 2. TUIChat provides handleFreeTrialShowConfigSelector function - // 3. Config selector is shown when option 3 is selected - - // These integration points are tested via: - // - Type checking (ensures interfaces match) - // - Manual testing during development - // - E2E tests that exercise the full flow - - expect(true).toBe(true); // Placeholder test - }); -}); diff --git a/extensions/cli/src/ui/__tests__/mocks/MockApiClient.ts b/extensions/cli/src/ui/__tests__/mocks/MockApiClient.ts index d619a6256..f361cd6a7 100644 --- a/extensions/cli/src/ui/__tests__/mocks/MockApiClient.ts +++ b/extensions/cli/src/ui/__tests__/mocks/MockApiClient.ts @@ -1,12 +1,5 @@ // Mock API Client export class MockApiClient { - async getFreeTrialStatus() { - return { - optedInToFreeTrial: true, - chatCount: 5, - chatLimit: 100, - }; - } async listAssistants() { return []; } diff --git a/extensions/cli/src/ui/components/BottomStatusBar.tsx b/extensions/cli/src/ui/components/BottomStatusBar.tsx index e323911da..7af52f4a5 100644 --- a/extensions/cli/src/ui/components/BottomStatusBar.tsx +++ b/extensions/cli/src/ui/components/BottomStatusBar.tsx @@ -4,7 +4,6 @@ import React, { useEffect, useState } from "react"; import { setExitMessageCallback, shouldShowExitMessage } from "../../index.js"; import type { PermissionMode } from "../../permissions/types.js"; import type { NavigationScreen } from "../context/NavigationContext.js"; -import { FreeTrialStatus } from "../FreeTrialStatus.js"; import { UpdateNotification } from "../UpdateNotification.js"; import { ContextPercentageDisplay } from "./ContextPercentageDisplay.js"; @@ -89,24 +88,7 @@ export const BottomStatusBar: React.FC = ({ )} - - {!isRemoteMode && services.model?.model && ( - { - if (shouldShow && navState.currentScreen === "chat") { - navigateTo("free-trial"); - } else if ( - !shouldShow && - navState.currentScreen === "free-trial" - ) { - closeCurrentScreen(); - } - }} - /> - )} - + diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 516cb7811..045101abc 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -8,7 +8,6 @@ import { ConfigSelector } from "../ConfigSelector.js"; import type { NavigationScreen } from "../context/NavigationContext.js"; import { DiffViewer } from "../DiffViewer.js"; import { EditMessageSelector } from "../EditMessageSelector.js"; -import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js"; import type { ActivePermissionRequest, ActiveQuizQuestion, @@ -169,11 +168,6 @@ export const ScreenContent: React.FC = ({ return ; } - // Free trial transition UI - if (isScreenActive("free-trial")) { - return ; - } - // Diff viewer overlay if (isScreenActive("diff")) { return ( diff --git a/extensions/cli/src/ui/context/NavigationContext.tsx b/extensions/cli/src/ui/context/NavigationContext.tsx index 04c1689f5..ca5ceb385 100644 --- a/extensions/cli/src/ui/context/NavigationContext.tsx +++ b/extensions/cli/src/ui/context/NavigationContext.tsx @@ -14,7 +14,6 @@ export type NavigationScreen = | "chat" // Normal chat interface | "config" // Config selector (includes organization switching) | "model" // Model selector - | "free-trial" // Free trial transition UI | "login" // Login prompt | "mcp" // MCP selector | "session" // Session selector diff --git a/extensions/cli/src/ui/context/__tests__/NavigationContext.test.tsx b/extensions/cli/src/ui/context/__tests__/NavigationContext.test.tsx index d3da83ef7..a5508dfa8 100644 --- a/extensions/cli/src/ui/context/__tests__/NavigationContext.test.tsx +++ b/extensions/cli/src/ui/context/__tests__/NavigationContext.test.tsx @@ -78,7 +78,6 @@ describe("NavigationContext", () => { "chat", "config", "model", - "free-trial", "login", "mcp", ]; @@ -168,8 +167,8 @@ describe("NavigationContext", () => { it("closes from any screen back to chat", () => { const { result } = renderHook(() => useNavigation(), { wrapper }); const screens: Array< - "config" | "model" | "free-trial" | "login" | "mcp" - > = ["config", "model", "free-trial", "login", "mcp"]; + "config" | "model" | "login" | "mcp" + > = ["config", "model", "login", "mcp"]; screens.forEach((screen) => { act(() => { @@ -205,7 +204,6 @@ describe("NavigationContext", () => { expect(result.current.isScreenActive("config")).toBe(false); expect(result.current.isScreenActive("model")).toBe(false); expect(result.current.isScreenActive("mcp")).toBe(false); - expect(result.current.isScreenActive("free-trial")).toBe(false); expect(result.current.isScreenActive("login")).toBe(false); }); @@ -213,14 +211,14 @@ describe("NavigationContext", () => { const { result } = renderHook(() => useNavigation(), { wrapper }); act(() => { - result.current.navigateTo("free-trial"); + result.current.navigateTo("config"); }); - expect(result.current.isScreenActive("free-trial")).toBe(true); + expect(result.current.isScreenActive("config")).toBe(true); act(() => { result.current.navigateTo("model"); }); - expect(result.current.isScreenActive("free-trial")).toBe(false); + expect(result.current.isScreenActive("config")).toBe(false); expect(result.current.isScreenActive("model")).toBe(true); act(() => { @@ -308,29 +306,6 @@ describe("NavigationContext", () => { expect(result.current.isScreenActive("chat")).toBe(true); }); - it("handles free trial transition flow", () => { - const { result } = renderHook(() => useNavigation(), { wrapper }); - - // Show free trial screen - act(() => { - result.current.navigateTo("free-trial"); - }); - expect(result.current.isScreenActive("free-trial")).toBe(true); - - // User might navigate to config from free trial - act(() => { - result.current.navigateTo("config"); - }); - expect(result.current.isScreenActive("config")).toBe(true); - expect(result.current.isScreenActive("free-trial")).toBe(false); - - // Return to chat - act(() => { - result.current.closeCurrentScreen(); - }); - expect(result.current.isScreenActive("chat")).toBe(true); - }); - it("handles model switching flow", () => { const { result } = renderHook(() => useNavigation(), { wrapper }); diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 440d8c280..c82f1d60d 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -145,22 +145,6 @@ const Layout = () => { [], ); - useWebviewListener( - "freeTrialExceeded", - async () => { - dispatch(setShowDialog(true)); - onboardingCard.setActiveTab(OnboardingModes.MODELS_ADD_ON); - dispatch( - setDialogMessage( -
- -
, - ), - ); - }, - [], - ); - useWebviewListener( "setupApiKey", async () => { diff --git a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts index b3cbd644d..12ab8582b 100644 --- a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts +++ b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts @@ -30,8 +30,7 @@ export function useOnboardingCard(): UseOnboardingCard { let show: boolean; - // Always show if we explicitly want to, e.g. passing free trial - // and setting up keys + // Always show if we explicitly want to, e.g. setting up keys if (onboardingCard.show) { show = true; } else { diff --git a/gui/src/components/StarterCreditsButton.tsx b/gui/src/components/StarterCreditsButton.tsx deleted file mode 100644 index 51f58d16e..000000000 --- a/gui/src/components/StarterCreditsButton.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { GiftIcon } from "@heroicons/react/24/outline"; -import { CreditStatus } from "core/control-plane/client"; -import StarterCreditsPopover from "./StarterCreditsPopover"; - -interface FreeTrialButtonProps { - creditStatus?: CreditStatus | null; - refreshCreditStatus?: () => Promise; -} - -/** - * @deprecated Use StarterCreditsPopover with a custom button/icon instead. - * This component is kept for backward compatibility. - */ -export default function StarterCreditsButton({ - creditStatus, - refreshCreditStatus, -}: FreeTrialButtonProps) { - return ( - - - - - - ); -} diff --git a/gui/src/components/StarterCreditsPopover.tsx b/gui/src/components/StarterCreditsPopover.tsx deleted file mode 100644 index c80777199..000000000 --- a/gui/src/components/StarterCreditsPopover.tsx +++ /dev/null @@ -1,196 +0,0 @@ -import { - ArrowPathIcon, - GiftIcon, - XMarkIcon, -} from "@heroicons/react/24/outline"; -import { CreditStatus } from "core/control-plane/client"; -import { useContext, useState } from "react"; -import { Button, SecondaryButton, vscButtonBackground } from "."; -import { useAuth } from "../context/Auth"; -import { IdeMessengerContext } from "../context/IdeMessenger"; -import { cn } from "../util/cn"; -import { setLocalStorage } from "../util/localStorage"; -import { ToolbarButtonWithTooltip } from "./StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip"; -import { Listbox, ListboxButton, ListboxOptions, Transition } from "./ui"; - -interface ProgressBarProps { - label: string; - current: number; - total: number; -} - -function ProgressBar({ label, current, total }: ProgressBarProps) { - const percentage = Math.min((current / total) * 100, 100); - - return ( -
-
- {label} - - ${(current / 100).toFixed(2)} / ${(total / 100).toFixed(2)} - -
-
-
-
-
- ); -} - -interface CreditStatusProgressBarsProps { - creditStatus: CreditStatus; -} - -function CreditStatusProgressBar({ - creditStatus, -}: CreditStatusProgressBarsProps) { - const total = 50; - const usage = total - (creditStatus.creditBalance ?? 0); - - return ( - - ); -} - -interface StarterCreditsPopoverProps { - creditStatus?: CreditStatus | null; - refreshCreditStatus?: () => Promise; - children: React.ReactNode; -} - -export default function StarterCreditsPopover({ - creditStatus, - refreshCreditStatus, - children, -}: StarterCreditsPopoverProps) { - const ideMessenger = useContext(IdeMessengerContext); - const { refreshProfiles } = useAuth(); - const [isRefreshing, setIsRefreshing] = useState(false); - - const onSetupApiKeys = async () => { - await ideMessenger.request("controlPlane/openUrl", { - path: "setup-models/api-keys", - orgSlug: undefined, - }); - }; - - const onPurchaseCredits = async () => { - await ideMessenger.request("controlPlane/openUrl", { - path: "settings/billing", - orgSlug: undefined, - }); - }; - - const onHideStarterCreditsUsage = async () => { - // At this point the user doesn't want to see the credit usage UI, so we make sure this is gone right away - setLocalStorage("hasExitedFreeTrial", true); - }; - - const onRefresh = async () => { - if (isRefreshing) { - return; - } - - setIsRefreshing(true); - - const refreshCalls: Promise[] = [ - refreshProfiles("Manual refresh from starter credits button"), - ]; - - if (refreshCreditStatus) { - refreshCalls.push(refreshCreditStatus()); - } - - try { - await Promise.all(refreshCalls); - } finally { - setIsRefreshing(false); - } - }; - - return ( - - - {children} - - - - -
-
- -

Starter credits

-
-
- { - void onRefresh(); - }} - tooltipContent="Refresh credit usage" - > - - - - - -
- -
- - You are currently using starter credits for Continue, which - allows you to use a variety of frontier models at cost. Read - more{" "} - { - await ideMessenger.request("controlPlane/openUrl", { - path: "pricing", - orgSlug: undefined, - }); - ``; - }} - className="cursor-pointer text-blue-400 underline hover:text-blue-300" - > - here - - . - -
- - {!creditStatus ? ( -
- - Loading credit usage... - -
- ) : ( - - )} - -
- - Setup API Keys - - -
-
-
-
-
- ); -} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx index 2f022ea5a..e6ed1a012 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx @@ -1,7 +1,6 @@ import { CubeIcon, ExclamationTriangleIcon, - GiftIcon, PencilIcon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; @@ -14,12 +13,10 @@ import { selectToolCallsByStatus, } from "../../../../redux/selectors/selectToolCalls"; import { setSelectedProfile } from "../../../../redux/slices/profilesSlice"; -import StarterCreditsPopover from "../../../StarterCreditsPopover"; import { ToolTip } from "../../../gui/Tooltip"; import HoverItem from "../../InputToolbar/HoverItem"; import { useAuth } from "../../../../context/Auth"; -import { useCreditStatus } from "../../../../hooks/useCredits"; import { CONFIG_ROUTES } from "../../../../util/navigation"; import { AssistantAndOrgListbox } from "../../../AssistantAndOrgListbox"; @@ -40,9 +37,6 @@ export function BlockSettingsTopToolbar() { const shouldShowError = configError && configError?.length > 0; - const { creditStatus, isUsingFreeTrial, refreshCreditStatus } = - useCreditStatus(); - const handleRulesClick = () => { if (selectedProfile) { dispatch(setSelectedProfile(selectedProfile.id)); @@ -101,19 +95,6 @@ export function BlockSettingsTopToolbar() { {!hasActiveContent && (
- {isUsingFreeTrial && ( - - - - - - - - )} - diff --git a/gui/src/hooks/useCredits.ts b/gui/src/hooks/useCredits.ts index 8f2a4bb45..cd9a841ec 100644 --- a/gui/src/hooks/useCredits.ts +++ b/gui/src/hooks/useCredits.ts @@ -1,23 +1,11 @@ -import { usesCreditsBasedApiKey } from "core/config/usesFreeTrialApiKey"; import { CreditStatus } from "core/control-plane/client"; -import { isOutOfStarterCredits } from "core/llm/utils/starterCredits"; import { useCallback, useContext, useEffect, useState } from "react"; import { IdeMessengerContext } from "../context/IdeMessenger"; -import { useAppSelector } from "../redux/hooks"; -import { getLocalStorage } from "../util/localStorage"; export function useCreditStatus() { - const config = useAppSelector((state) => state.config.config); const ideMessenger = useContext(IdeMessengerContext); const [creditStatus, setCreditStatus] = useState(null); - const hasExitedFreeTrial = getLocalStorage("hasExitedFreeTrial"); - const usingCreditsBasedApiKey = usesCreditsBasedApiKey(config); - const isUsingFreeTrial = usingCreditsBasedApiKey && !hasExitedFreeTrial; - const outOfStarterCredits = creditStatus - ? isOutOfStarterCredits(usingCreditsBasedApiKey, creditStatus) - : false; - const refreshCreditStatus = useCallback(async () => { try { const resp = await ideMessenger.request( @@ -32,28 +20,13 @@ export function useCreditStatus() { } }, [ideMessenger]); + // One-time fetch on mount — no polling useEffect(() => { void refreshCreditStatus(); - - let intervalId: NodeJS.Timeout | null = null; - - if (isUsingFreeTrial) { - intervalId = setInterval(() => { - void refreshCreditStatus(); - }, 15000); - } - - return () => { - if (intervalId) { - clearInterval(intervalId); - } - }; - }, [isUsingFreeTrial, refreshCreditStatus]); + }, [refreshCreditStatus]); return { creditStatus, - outOfStarterCredits, - isUsingFreeTrial, refreshCreditStatus, }; }