fix: eliminate free trial system from continue-fork

Delete freeTrialTransition.ts, FreeTrialStatus.tsx, FreeTrialTransitionUI.tsx,
StarterCreditsButton.tsx, StarterCreditsPopover.tsx, and related tests/mocks.

Strengthen free-trial provider filtering to hard-drop (no more warnings).
Remove checkForOutOfStarterCredits from streamChat. Simplify useCredits
hook to a one-time fetch (no polling). Remove freeTrialExceeded listener
from Layout. Clean up navigation context and toolbar references.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Nate 2026-03-20 14:00:02 -07:00
parent 606fba91a3
commit 52c3252902
21 changed files with 13 additions and 1273 deletions

View file

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

View file

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

View file

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

View file

@ -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<void> {
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<void>,
): 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 = 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);
}

View file

@ -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<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 {
// 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 { FreeTrialStatus };

View file

@ -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<void> {
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<FreeTrialTransitionUIProps> = ({
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 (
<Box {...defaultBoxStyles("yellow")}>
<Text bold color="yellow">
🚀 Free trial limit reached!
</Text>
<Text>Choose how you'd like to continue:</Text>
<Text></Text>
{options.map((option) => (
<Text
key={option.num}
color={selectedOption === option.num ? "cyan" : "white"}
>
{selectedOption === option.num ? "➤ " : " "}
{option.num}. {option.text}
</Text>
))}
<Text></Text>
<Text color="gray">
↑/↓ to navigate or {hasOrganizations ? "1/2/3/4" : "1/2/3"} to select,
Enter to confirm
</Text>
</Box>
);
}
if (currentStep === "enterApiKey") {
return (
<Box {...defaultBoxStyles("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 {...defaultBoxStyles("blue")}>
<Text bold color="blue">
Processing...
</Text>
<Text>Please wait...</Text>
</Box>
);
}
if (currentStep === "success") {
return (
<Box {...defaultBoxStyles("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 {...defaultBoxStyles("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 { FreeTrialTransitionUI };

View file

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

View file

@ -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(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
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(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
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(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
const frame = lastFrame();
expect(frame).toBeDefined();
expect(frame?.length).toBeGreaterThan(0);
});
it("renders without crashing when onShowConfigSelector is not provided", () => {
const { lastFrame } = render(
<FreeTrialTransitionUI
onReload={mockOnReload}
// onShowConfigSelector not provided
/>,
);
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(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
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(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
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(<FreeTrialTransitionUI onReload={mockOnReload} />);
}).not.toThrow();
});
it("accepts optional onShowConfigSelector prop", () => {
// Test that component works without onShowConfigSelector
expect(() => {
render(<FreeTrialTransitionUI onReload={mockOnReload} />);
}).not.toThrow();
});
});
describe("Visual Styling and Layout", () => {
it("renders with proper border styling", () => {
const { lastFrame } = render(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
const frame = lastFrame();
// Check for box border characters (unicode box drawing)
expect(frame).toMatch(/[╭╮╯╰│─]/);
});
it("displays with proper spacing and formatting", () => {
const { lastFrame } = render(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
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(
<FreeTrialTransitionUI onReload={mockOnReload} />,
);
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");
});
});
});

View file

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

View file

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

View file

@ -1,12 +1,5 @@
// Mock API Client
export class MockApiClient {
async getFreeTrialStatus() {
return {
optedInToFreeTrial: true,
chatCount: 5,
chatLimit: 100,
};
}
async listAssistants() {
return [];
}

View file

@ -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<BottomStatusBarProps> = ({
</React.Fragment>
)}
</Box>
<Box>
{!isRemoteMode && services.model?.model && (
<FreeTrialStatus
apiClient={services.apiClient?.apiClient || undefined}
model={services.model.model}
onTransitionStateChange={(shouldShow) => {
if (shouldShow && navState.currentScreen === "chat") {
navigateTo("free-trial");
} else if (
!shouldShow &&
navState.currentScreen === "free-trial"
) {
closeCurrentScreen();
}
}}
/>
)}
</Box>
<Box />
<Box marginRight={2} marginLeft={2}>
<UpdateNotification isRemoteMode={isRemoteMode} />
</Box>

View file

@ -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<ScreenContentProps> = ({
return <JobsSelector onCancel={closeCurrentScreen} />;
}
// Free trial transition UI
if (isScreenActive("free-trial")) {
return <FreeTrialTransitionUI onReload={handleReload} />;
}
// Diff viewer overlay
if (isScreenActive("diff")) {
return (

View file

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

View file

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

View file

@ -145,22 +145,6 @@ const Layout = () => {
[],
);
useWebviewListener(
"freeTrialExceeded",
async () => {
dispatch(setShowDialog(true));
onboardingCard.setActiveTab(OnboardingModes.MODELS_ADD_ON);
dispatch(
setDialogMessage(
<div className="flex-1">
<OnboardingCard isDialog />
</div>,
),
);
},
[],
);
useWebviewListener(
"setupApiKey",
async () => {

View file

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

View file

@ -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<void>;
}
/**
* @deprecated Use StarterCreditsPopover with a custom button/icon instead.
* This component is kept for backward compatibility.
*/
export default function StarterCreditsButton({
creditStatus,
refreshCreditStatus,
}: FreeTrialButtonProps) {
return (
<StarterCreditsPopover
creditStatus={creditStatus}
refreshCreditStatus={refreshCreditStatus}
>
<span
style={{
paddingLeft: "8px",
paddingRight: "8px",
paddingTop: "2px",
paddingBottom: "2px",
cursor: "pointer",
transition: "color 200ms, background-color 200ms, box-shadow 200ms",
display: "inline-flex",
}}
>
<GiftIcon className="text-description-muted h-3 w-3 hover:brightness-125" />
</span>
</StarterCreditsPopover>
);
}

View file

@ -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 (
<div className="mb-4">
<div className="mb-1 flex justify-between text-xs">
<span>{label}</span>
<span>
${(current / 100).toFixed(2)} / ${(total / 100).toFixed(2)}
</span>
</div>
<div className="h-2 w-full rounded-full bg-gray-700">
<div
className="h-2 rounded-full transition-all duration-300"
style={{
width: `${percentage}%`,
backgroundColor: vscButtonBackground,
}}
/>
</div>
</div>
);
}
interface CreditStatusProgressBarsProps {
creditStatus: CreditStatus;
}
function CreditStatusProgressBar({
creditStatus,
}: CreditStatusProgressBarsProps) {
const total = 50;
const usage = total - (creditStatus.creditBalance ?? 0);
return (
<ProgressBar label="Starter credits usage" current={usage} total={total} />
);
}
interface StarterCreditsPopoverProps {
creditStatus?: CreditStatus | null;
refreshCreditStatus?: () => Promise<void>;
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<unknown>[] = [
refreshProfiles("Manual refresh from starter credits button"),
];
if (refreshCreditStatus) {
refreshCalls.push(refreshCreditStatus());
}
try {
await Promise.all(refreshCalls);
} finally {
setIsRefreshing(false);
}
};
return (
<Listbox>
<ListboxButton
as="span"
className="!m-0 !flex-none !gap-0 !border-none !bg-transparent !p-0"
>
{children}
</ListboxButton>
<Transition>
<ListboxOptions className="pb-0">
<div className="relative max-w-96 px-4 pb-4">
<div className="flex items-center gap-2">
<GiftIcon className="h-4 w-4" />
<h3 className="text-sm font-semibold">Starter credits</h3>
</div>
<div className="absolute right-3 top-3 flex items-center gap-1">
<ToolbarButtonWithTooltip
onClick={() => {
void onRefresh();
}}
tooltipContent="Refresh credit usage"
>
<ArrowPathIcon
className={cn("h-3 w-3", isRefreshing && "animate-spin-slow")}
/>
</ToolbarButtonWithTooltip>
<ToolbarButtonWithTooltip
onClick={onHideStarterCreditsUsage}
tooltipContent="Hide starter credits usage"
>
<XMarkIcon className="h-3 w-3" />
</ToolbarButtonWithTooltip>
</div>
<div className="mb-4">
<span className="text-description">
You are currently using starter credits for Continue, which
allows you to use a variety of frontier models at cost. Read
more{" "}
<span
onClick={async () => {
await ideMessenger.request("controlPlane/openUrl", {
path: "pricing",
orgSlug: undefined,
});
``;
}}
className="cursor-pointer text-blue-400 underline hover:text-blue-300"
>
here
</span>
.
</span>
</div>
{!creditStatus ? (
<div className="mb-4 flex items-center justify-center py-8">
<span className="text-description">
Loading credit usage...
</span>
</div>
) : (
<CreditStatusProgressBar creditStatus={creditStatus} />
)}
<div className="mt-4 flex gap-2">
<SecondaryButton className="flex-1" onClick={onSetupApiKeys}>
Setup API Keys
</SecondaryButton>
<Button className="flex-1" onClick={onPurchaseCredits}>
Purchase Credits
</Button>
</div>
</div>
</ListboxOptions>
</Transition>
</Listbox>
);
}

View file

@ -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 && (
<div className="flex items-center gap-1.5">
{isUsingFreeTrial && (
<ToolTip content="View remaining starter credits">
<StarterCreditsPopover
creditStatus={creditStatus}
refreshCreditStatus={refreshCreditStatus}
>
<HoverItem px={2}>
<GiftIcon className="text-description-muted h-3 w-3 hover:brightness-125" />
</HoverItem>
</StarterCreditsPopover>
</ToolTip>
)}
<ToolTip content="Configure rules">
<HoverItem onClick={handleRulesClick} px={2}>
<PencilIcon className="text-description-muted h-3 w-3 hover:brightness-125" />

View file

@ -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<CreditStatus | null>(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,
};
}