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