| 1 | import * as fs from "fs"; |
| 2 | import * as path from "path"; |
| 3 | |
| 4 | import { Box, Text, useInput } from "ink"; |
| 5 | import open from "open"; |
| 6 | import React, { useState } from "react"; |
| 7 | import useSWR from "swr"; |
| 8 | |
| 9 | import { listUserOrganizations } from "../auth/workos.js"; |
| 10 | import { env } from "../env.js"; |
| 11 | import { |
| 12 | getApiKeyValidationError, |
| 13 | isValidAnthropicApiKey, |
| 14 | } from "../util/apiKeyValidation.js"; |
| 15 | import { updateAnthropicModelInYaml } from "../util/yamlConfigUpdater.js"; |
| 16 | |
| 17 | import { useNavigation } from "./context/NavigationContext.js"; |
| 18 | |
| 19 | const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); |
| 20 | |
| 21 | // Helper functions for input handling |
| 22 | interface ChoiceInputOptions { |
| 23 | input: string; |
| 24 | key: any; |
| 25 | selectedOption: number; |
| 26 | setSelectedOption: (option: number) => void; |
| 27 | hasOrganizations: boolean; |
| 28 | handleOptionSelect: () => void; |
| 29 | } |
| 30 | |
| 31 | function handleChoiceInput(options: ChoiceInputOptions): void { |
| 32 | const { |
| 33 | input, |
| 34 | key, |
| 35 | selectedOption, |
| 36 | setSelectedOption, |
| 37 | hasOrganizations, |
| 38 | handleOptionSelect, |
| 39 | } = options; |
| 40 | if (key.upArrow && selectedOption > 1) { |
| 41 | setSelectedOption(selectedOption - 1); |
| 42 | } else if (key.downArrow && selectedOption < (hasOrganizations ? 4 : 3)) { |
| 43 | setSelectedOption(selectedOption + 1); |
| 44 | } else if (input === "1") { |
| 45 | setSelectedOption(1); |
| 46 | } else if (input === "2") { |
| 47 | setSelectedOption(2); |
| 48 | } else if (input === "3") { |
| 49 | setSelectedOption(3); |
| 50 | } else if (input === "4" && hasOrganizations) { |
| 51 | setSelectedOption(4); |
| 52 | } else if (key.return) { |
| 53 | handleOptionSelect(); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | interface ApiKeyInputOptions { |
| 58 | input: string; |
| 59 | key: any; |
| 60 | apiKey: string; |
| 61 | setApiKey: (key: string) => void; |
| 62 | setErrorMessage: (msg: string) => void; |
| 63 | handleApiKeySubmit: () => void; |
| 64 | } |
| 65 | |
| 66 | function handleApiKeyInput(options: ApiKeyInputOptions): void { |
| 67 | const { input, key, apiKey, setApiKey, setErrorMessage, handleApiKeySubmit } = |
| 68 | options; |
| 69 | if (key.return) { |
| 70 | if (isValidAnthropicApiKey(apiKey)) { |
| 71 | handleApiKeySubmit(); |
| 72 | } else { |
| 73 | setErrorMessage(getApiKeyValidationError(apiKey)); |
| 74 | } |
| 75 | } else if (key.backspace || key.delete) { |
| 76 | setApiKey(apiKey.slice(0, -1)); |
| 77 | setErrorMessage(""); |
| 78 | } else if (input && !key.ctrl && !key.meta) { |
| 79 | setApiKey(apiKey + input); |
| 80 | setErrorMessage(""); |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | interface FreeTrialTransitionUIProps { |
| 85 | onReload: () => void; |
| 86 | } |
| 87 | |
| 88 | /** |
| 89 | * Creates or updates the local config with Anthropic API key |
| 90 | */ |
| 91 | async function createOrUpdateConfig(apiKey: string): Promise<void> { |
| 92 | const configDir = path.dirname(CONFIG_PATH); |
| 93 | |
| 94 | if (!fs.existsSync(configDir)) { |
| 95 | fs.mkdirSync(configDir, { recursive: true }); |
| 96 | } |
| 97 | |
| 98 | const existingContent = fs.existsSync(CONFIG_PATH) |
| 99 | ? fs.readFileSync(CONFIG_PATH, "utf8") |
| 100 | : ""; |
| 101 | |
| 102 | const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey); |
| 103 | fs.writeFileSync(CONFIG_PATH, updatedContent); |
| 104 | } |
| 105 | |
| 106 | const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({ |
| 107 | onReload, |
| 108 | }) => { |
| 109 | const { navigateTo, closeCurrentScreen } = useNavigation(); |
| 110 | const [currentStep, setCurrentStep] = useState< |
| 111 | "choice" | "enterApiKey" | "processing" | "success" | "error" |
| 112 | >("choice"); |
| 113 | const [selectedOption, setSelectedOption] = useState(1); |
| 114 | const [apiKey, setApiKey] = useState(""); |
| 115 | const [errorMessage, setErrorMessage] = useState(""); |
| 116 | const [successMessage, setSuccessMessage] = useState(""); |
| 117 | const [wasModelsSetup, setWasModelsSetup] = useState(false); |
| 118 | |
| 119 | // Fetch organizations using SWR |
| 120 | const { data: organizations } = useSWR( |
| 121 | "organizations", |
| 122 | listUserOrganizations, |
| 123 | { |
| 124 | revalidateOnFocus: false, |
| 125 | revalidateOnReconnect: false, |
| 126 | shouldRetryOnError: false, |
| 127 | }, |
| 128 | ); |
| 129 | |
| 130 | const hasOrganizations = organizations && organizations.length > 0; |
| 131 | |
| 132 | useInput((input, key) => { |
| 133 | if (currentStep === "choice") { |
| 134 | handleChoiceInput({ |
| 135 | input, |
| 136 | key, |
| 137 | selectedOption, |
| 138 | setSelectedOption, |
| 139 | hasOrganizations: !!hasOrganizations, |
| 140 | handleOptionSelect, |
| 141 | }); |
| 142 | } else if (currentStep === "enterApiKey") { |
| 143 | handleApiKeyInput({ |
| 144 | input, |
| 145 | key, |
| 146 | apiKey, |
| 147 | setApiKey, |
| 148 | setErrorMessage, |
| 149 | handleApiKeySubmit, |
| 150 | }); |
| 151 | } else if (currentStep === "success" || currentStep === "error") { |
| 152 | if (key.return) { |
| 153 | closeCurrentScreen(); |
| 154 | // If user went through models setup, do a full reload to register their purchase |
| 155 | if (wasModelsSetup) { |
| 156 | onReload(); |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | }); |
| 161 | |
| 162 | const handleOptionSelect = async () => { |
| 163 | if (selectedOption === 1) { |
| 164 | // Option 1: Open models setup page |
| 165 | setCurrentStep("processing"); |
| 166 | const modelsUrl = new URL("setup-models", env.appUrl).toString(); |
| 167 | setWasModelsSetup(true); // Track that user went through models setup |
| 168 | |
| 169 | try { |
| 170 | await open(modelsUrl); |
| 171 | setSuccessMessage( |
| 172 | `Browser opened to ${modelsUrl}. After setting up your models subscription, press Enter to continue.`, |
| 173 | ); |
| 174 | setCurrentStep("success"); |
| 175 | } catch { |
| 176 | setErrorMessage( |
| 177 | `Could not open browser automatically. Please visit: ${modelsUrl}. After setting up your models subscription, press Enter to continue.`, |
| 178 | ); |
| 179 | setCurrentStep("error"); |
| 180 | } |
| 181 | } else if (selectedOption === 2) { |
| 182 | // Option 2: Enter API key |
| 183 | setCurrentStep("enterApiKey"); |
| 184 | setWasModelsSetup(false); // This is not models setup |
| 185 | } else if (selectedOption === 3) { |
| 186 | // Option 3: Switch to different configuration |
| 187 | navigateTo("config"); |
| 188 | } else if (selectedOption === 4 && hasOrganizations) { |
| 189 | // Option 4: Switch to configuration (includes organization switching) |
| 190 | navigateTo("config"); |
| 191 | } |
| 192 | }; |
| 193 | |
| 194 | const handleApiKeySubmit = async () => { |
| 195 | setCurrentStep("processing"); |
| 196 | |
| 197 | try { |
| 198 | await createOrUpdateConfig(apiKey); |
| 199 | setSuccessMessage( |
| 200 | "✓ API key saved successfully! Switching to local configuration...", |
| 201 | ); |
| 202 | setCurrentStep("success"); |
| 203 | |
| 204 | // After a brief delay, switch to local configuration |
| 205 | setTimeout(() => { |
| 206 | closeCurrentScreen(); |
| 207 | onReload(); |
| 208 | }, 1000); |
| 209 | } catch (error) { |
| 210 | setErrorMessage( |
| 211 | `❌ Error saving API key: ${error}. Press Enter to try again.`, |
| 212 | ); |
| 213 | setCurrentStep("error"); |
| 214 | } |
| 215 | }; |
| 216 | |
| 217 | if (currentStep === "choice") { |
| 218 | return ( |
| 219 | <Box |
| 220 | flexDirection="column" |
| 221 | padding={1} |
| 222 | borderStyle="round" |
| 223 | borderColor="yellow" |
| 224 | > |
| 225 | <Text bold color="yellow"> |
| 226 | 🚀 Free trial limit reached! |
| 227 | </Text> |
| 228 | <Text>Choose how you'd like to continue:</Text> |
| 229 | <Text></Text> |
| 230 | <Text color={selectedOption === 1 ? "cyan" : "white"}> |
| 231 | {selectedOption === 1 ? "▶ " : " "}1. 💳 Sign up for models add-on |
| 232 | (recommended) |
| 233 | </Text> |
| 234 | <Text color={selectedOption === 2 ? "cyan" : "white"}> |
| 235 | {selectedOption === 2 ? "▶ " : " "}2. 🔑 Enter your Anthropic API |
| 236 | key |
| 237 | </Text> |
| 238 | <Text color={selectedOption === 3 ? "cyan" : "white"}> |
| 239 | {selectedOption === 3 ? "▶ " : " "}3. ⚙️ Switch to a different |
| 240 | configuration |
| 241 | </Text> |
| 242 | {hasOrganizations && ( |
| 243 | <Text color={selectedOption === 4 ? "cyan" : "white"}> |
| 244 | {selectedOption === 4 ? "▶ " : " "}4. 🏢 Switch to organization |
| 245 | configuration |
| 246 | </Text> |
| 247 | )} |
| 248 | <Text></Text> |
| 249 | <Text color="gray"> |
| 250 | Use ↑↓ arrows or {hasOrganizations ? "1/2/3/4" : "1/2/3"} to select, |
| 251 | Enter to confirm |
| 252 | </Text> |
| 253 | </Box> |
| 254 | ); |
| 255 | } |
| 256 | |
| 257 | if (currentStep === "enterApiKey") { |
| 258 | return ( |
| 259 | <Box |
| 260 | flexDirection="column" |
| 261 | padding={1} |
| 262 | borderStyle="round" |
| 263 | borderColor="yellow" |
| 264 | > |
| 265 | <Text bold color="yellow"> |
| 266 | Enter your Anthropic API key |
| 267 | </Text> |
| 268 | <Text></Text> |
| 269 | <Text>API Key: {"*".repeat(apiKey.length)}</Text> |
| 270 | <Text></Text> |
| 271 | {errorMessage && <Text color="red">{errorMessage}</Text>} |
| 272 | <Text color="gray"> |
| 273 | Type your API key and press Enter (must start with 'sk-ant-') |
| 274 | </Text> |
| 275 | </Box> |
| 276 | ); |
| 277 | } |
| 278 | |
| 279 | if (currentStep === "processing") { |
| 280 | return ( |
| 281 | <Box |
| 282 | flexDirection="column" |
| 283 | padding={1} |
| 284 | borderStyle="round" |
| 285 | borderColor="blue" |
| 286 | > |
| 287 | <Text bold color="blue"> |
| 288 | Processing... |
| 289 | </Text> |
| 290 | <Text>Please wait...</Text> |
| 291 | </Box> |
| 292 | ); |
| 293 | } |
| 294 | |
| 295 | if (currentStep === "success") { |
| 296 | return ( |
| 297 | <Box |
| 298 | flexDirection="column" |
| 299 | padding={1} |
| 300 | borderStyle="round" |
| 301 | borderColor="green" |
| 302 | > |
| 303 | <Text bold color="green"> |
| 304 | Success! |
| 305 | </Text> |
| 306 | <Text>{successMessage}</Text> |
| 307 | <Text></Text> |
| 308 | <Text color="gray"> |
| 309 | {wasModelsSetup |
| 310 | ? "Press Enter to reload and continue with your new subscription" |
| 311 | : "Press Enter to continue your conversation"} |
| 312 | </Text> |
| 313 | </Box> |
| 314 | ); |
| 315 | } |
| 316 | |
| 317 | if (currentStep === "error") { |
| 318 | return ( |
| 319 | <Box |
| 320 | flexDirection="column" |
| 321 | padding={1} |
| 322 | borderStyle="round" |
| 323 | borderColor="red" |
| 324 | > |
| 325 | <Text bold color="red"> |
| 326 | Error |
| 327 | </Text> |
| 328 | <Text>{errorMessage}</Text> |
| 329 | <Text></Text> |
| 330 | <Text color="gray"> |
| 331 | {wasModelsSetup |
| 332 | ? "Press Enter to reload and try again" |
| 333 | : "Press Enter to continue"} |
| 334 | </Text> |
| 335 | </Box> |
| 336 | ); |
| 337 | } |
| 338 | |
| 339 | return null; |
| 340 | }; |
| 341 | |
| 342 | export { FreeTrialTransitionUI }; |