All files / src/components/account AccountView.tsx

0% Statements 0/314
100% Branches 1/1
100% Functions 1/1
0% Lines 0/314

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import type { UsageTransaction as AiHydroAccountUsageTransaction, PaymentTransaction } from "@shared/AiHydroAccount"
import { isAiHydroInternalTester } from "@shared/internal/account"
import type { UserOrganization } from "@shared/proto/cline/account"
import { EmptyRequest } from "@shared/proto/cline/common"
import { VSCodeButton, VSCodeDivider, VSCodeDropdown, VSCodeOption, VSCodeTag } from "@vscode/webview-ui-toolkit/react"
import deepEqual from "fast-deep-equal"
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useInterval } from "react-use"
import { type AiHydroUser, handleSignOut } from "@/context/AiHydroAuthContext"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { AccountServiceClient } from "@/services/grpc-client"
import { getEnvironmentColor } from "@/utils/environmentColors"
import HeroTooltip from "../common/HeroTooltip"
import VSCodeButtonLink from "../common/VSCodeButtonLink"
import { updateSetting } from "../settings/utils/settingsHandlers"
import { AccountWelcomeView } from "./AccountWelcomeView"
import { CreditBalance } from "./CreditBalance"
import CreditsHistoryTable from "./CreditsHistoryTable"
import { convertProtoUsageTransactions, getAiHydroUris, getMainRole } from "./helpers"
 
type AccountViewProps = {
	aihydroUser: AiHydroUser | null
	organizations: UserOrganization[] | null
	activeOrganization: UserOrganization | null
	onDone: () => void
}
 
type AiHydroAccountViewProps = {
	aihydroUser: AiHydroUser
	userOrganizations: UserOrganization[] | null
	activeOrganization: UserOrganization | null
	clineEnv: "Production" | "Staging" | "Local"
}
 
type CachedData = {
	balance: number | null
	usageData: AiHydroAccountUsageTransaction[]
	paymentsData: PaymentTransaction[]
	lastFetchTime: number
}
 
const AiHydroEnvOptions = ["Production", "Staging", "Local"] as const
 
const AccountView = ({ onDone, aihydroUser, organizations, activeOrganization }: AccountViewProps) => {
	const { environment } = useExtensionState()
	const titleColor = getEnvironmentColor(environment)
 
	return (
		<div className="fixed inset-0 flex flex-col overflow-hidden pt-[10px] pl-[20px]">
			<div className="flex justify-between items-center mb-[17px] pr-[17px]">
				<h3 className="m-0" style={{ color: titleColor }}>
					Account {environment !== "production" ? ` - ${environment} environment` : ""}
				</h3>
				<VSCodeButton onClick={onDone}>Done</VSCodeButton>
			</div>
			<div className="flex-grow overflow-hidden pr-[8px] flex flex-col">
				<div className="h-full mb-1.5">
					{aihydroUser?.uid ? (
						<AiHydroAccountView
							activeOrganization={activeOrganization}
							aihydroUser={aihydroUser}
							clineEnv={environment === "local" ? "Local" : environment === "staging" ? "Staging" : "Production"}
							key={aihydroUser.uid}
							userOrganizations={organizations}
						/>
					) : (
						<AccountWelcomeView />
					)}
				</div>
			</div>
		</div>
	)
}
 
export const AiHydroAccountView = ({ aihydroUser, userOrganizations, activeOrganization, clineEnv }: AiHydroAccountViewProps) => {
	const { email, displayName, appBaseUrl, uid } = aihydroUser
	const { remoteConfigSettings } = useExtensionState()
 
	// Determine if dropdown should be locked by remote config
	const isLockedByRemoteConfig = Object.keys(remoteConfigSettings || {}).length > 0
	console.log("isLockedByRemoteConfig", isLockedByRemoteConfig)
 
	// Source of truth: Dedicated state for dropdown value that persists through failures
	// and represents that user's current selection.
	const [dropdownValue, setDropdownValue] = useState<string>(activeOrganization?.organizationId || uid)
	const [isLoading, setIsLoading] = useState(false)
 
	// Cache data per organization/user ID to avoid showing empty state when switching
	const dataCache = useRef<Map<string, CachedData>>(new Map())
 
	// Current displayed data
	const [balance, setBalance] = useState<number | null>(null)
	const [usageData, setUsageData] = useState<AiHydroAccountUsageTransaction[]>([])
	const [paymentsData, setPaymentsData] = useState<PaymentTransaction[]>([])
	const [lastFetchTime, setLastFetchTime] = useState<number>(Date.now())
 
	// Load cached data for current dropdown value
	const loadCachedData = useCallback((id: string) => {
		const cached = dataCache.current.get(id)
		if (cached) {
			setBalance(cached.balance)
			setUsageData(cached.usageData)
			setPaymentsData(cached.paymentsData)
			setLastFetchTime(cached.lastFetchTime)
			return true
		}
		return false
	}, [])
 
	// Simple cache function without dependencies
	const cacheCurrentData = useCallback(
		(id: string) => {
			dataCache.current.set(id, {
				balance,
				usageData,
				paymentsData,
				lastFetchTime,
			})
		},
		[balance, usageData, paymentsData, lastFetchTime],
	)
	// Track the active organization ID to detect changes
	const [lastActiveOrgId, setLastActiveOrgId] = useState<string | undefined>(activeOrganization?.organizationId)
	// Use ref for debounce timeout to avoid re-renders
	const debounceTimeoutRef = useRef<NodeJS.Timeout | null>(null)
	// Track if manual fetch is in progress to avoid duplicate fetches
	const manualFetchInProgressRef = useRef<boolean>(false)
	// Track if initial mount fetch has completed to avoid duplicate fetches
	const initialFetchCompleteRef = useRef<boolean>(false)
 
	const isAiHydroTester = useMemo(() => (email ? isAiHydroInternalTester(email) : false), [email])
 
	const fetchUserCredit = useCallback(async () => {
		try {
			const response = await AccountServiceClient.getUserCredits(EmptyRequest.create())
			const newBalance = response?.balance?.currentBalance
			// Always update balance, even if it's 0 or null - don't skip undefined
			setBalance(newBalance ?? null)
			const newUsage = convertProtoUsageTransactions(response.usageTransactions)
			setUsageData((prev) => (deepEqual(newUsage, prev) ? prev : newUsage))
			const newPaymentsData = response.paymentTransactions
			setPaymentsData((prev) => (deepEqual(newPaymentsData, prev) ? prev : newPaymentsData))
		} catch (error) {
			console.error("Failed to fetch user credit:", error)
		}
	}, [])
 
	const fetchCreditBalance = useCallback(
		async (id: string, skipCache = false) => {
			try {
				if (isLoading) {
					return // Prevent multiple concurrent fetches
				}
 
				// Load cached data immediately if available (unless skipping cache)
				if (!skipCache && loadCachedData(id)) {
					// If we have cached data, show it first, then fetch in background
				}
 
				setIsLoading(true)
				if (id === uid) {
					await fetchUserCredit()
				} else {
					const response = await AccountServiceClient.getOrganizationCredits({
						organizationId: id,
					})
					// Update balance - handle all values including 0 and null
					const newBalance = response.balance?.currentBalance
					setBalance(newBalance ?? null)
 
					const newUsage = convertProtoUsageTransactions(response.usageTransactions)
					setUsageData((prev) => (deepEqual(newUsage, prev) ? prev : newUsage))
				}
 
				// Cache the updated data
				cacheCurrentData(id)
			} catch (error) {
				console.error("Failed to fetch credit balance:", error)
			} finally {
				setLastFetchTime(Date.now())
				setIsLoading(false)
			}
		},
		[isLoading, uid, fetchUserCredit, loadCachedData],
	)
 
	const handleOrganizationChange = useCallback(
		async (event: any) => {
			const target = event.target as HTMLSelectElement
			if (!target) {
				return
			}
 
			const newValue = target.value
			if (newValue !== dropdownValue) {
				// Clear any pending debounced fetch since we're doing a manual one
				if (debounceTimeoutRef.current) {
					clearTimeout(debounceTimeoutRef.current)
					debounceTimeoutRef.current = null
				}
 
				// Cache current data before switching
				cacheCurrentData(dropdownValue)
				setDropdownValue(newValue)
 
				// Load cached data for new selection immediately, or clear if no cache
				// Only clear if we don't have cached data to avoid unnecessary flashing
				if (!loadCachedData(newValue)) {
					// No cached data - clear current state to avoid showing wrong data
					setBalance(null)
					setUsageData([])
					setPaymentsData([])
				}
 
				// Set flag to indicate manual fetch in progress
				manualFetchInProgressRef.current = true
 
				// Fetch the new data
				await fetchCreditBalance(newValue)
 
				// Update the last active org ID to prevent the effect from triggering
				setLastActiveOrgId(newValue === uid ? undefined : newValue)
 
				// Send the change to the server
				const organizationId = newValue === uid ? undefined : newValue
				await AccountServiceClient.setUserOrganization({ organizationId })
 
				// Clear the manual fetch flag after everything is done
				manualFetchInProgressRef.current = false
			}
		},
		[uid, dropdownValue, loadCachedData, fetchCreditBalance, cacheCurrentData],
	)
 
	// Fetch balance every 60 seconds
	useInterval(() => {
		fetchCreditBalance(dropdownValue)
	}, 60000)
 
	const aihydroUrl = appBaseUrl || "https://github.com/AI-Hydro/AI-Hydro"
 
	// Fetch balance on mount
	useEffect(() => {
		async function initialFetch() {
			await fetchCreditBalance(dropdownValue)
			initialFetchCompleteRef.current = true
		}
		initialFetch()
	}, [])
 
	useEffect(() => {
		// Handle organization changes with 500ms debounce
		const currentActiveOrgId = activeOrganization?.organizationId
		const hasActiveOrgChanged = currentActiveOrgId !== lastActiveOrgId
 
		// Only handle external organization changes (not dropdown changes)
		// Dropdown changes are handled by handleOrganizationChange
		const isExternalOrgChange = hasActiveOrgChanged && !manualFetchInProgressRef.current
 
		if (isExternalOrgChange) {
			// Clear any existing timeout
			if (debounceTimeoutRef.current) {
				clearTimeout(debounceTimeoutRef.current)
			}
 
			// Update dropdown to match the new active organization
			const newDropdownValue = currentActiveOrgId || uid
			if (newDropdownValue !== dropdownValue) {
				// Cache current data before switching
				cacheCurrentData(dropdownValue)
				setDropdownValue(newDropdownValue)
 
				// Load cached data for new selection immediately, or clear if no cache
				// Only clear data if initial fetch has completed to avoid clearing on mount
				if (!loadCachedData(newDropdownValue) && initialFetchCompleteRef.current) {
					// No cached data - clear to avoid showing wrong data
					setBalance(null)
					setUsageData([])
					setPaymentsData([])
				}
			}
 
			// Only set timeout if initial fetch is complete
			if (initialFetchCompleteRef.current) {
				// Set new timeout to fetch after 500ms
				debounceTimeoutRef.current = setTimeout(() => {
					fetchCreditBalance(newDropdownValue)
					setLastActiveOrgId(currentActiveOrgId)
				}, 500)
			} else {
				// Just update the active org ID
				setLastActiveOrgId(currentActiveOrgId)
			}
		}
 
		// Cleanup timeout on unmount
		return () => {
			if (debounceTimeoutRef.current) {
				clearTimeout(debounceTimeoutRef.current)
			}
		}
	}, [
		activeOrganization?.organizationId,
		lastActiveOrgId,
		uid,
		dropdownValue,
		loadCachedData,
		fetchCreditBalance,
		cacheCurrentData,
	])
 
	return (
		<div className="h-full flex flex-col">
			<div className="flex flex-col pr-3 h-full">
				<div className="flex flex-col w-full">
					<div className="flex items-center mb-6 flex-wrap gap-y-4">
						{/* {user.photoUrl ? (
								<img src={user.photoUrl} alt="Profile" className="size-16 rounded-full mr-4" />
							) : ( */}
						<div className="size-16 rounded-full bg-button-background flex items-center justify-center text-2xl text-[var(--vscode-button-foreground)] mr-4">
							{displayName?.[0] || email?.[0] || "?"}
						</div>
						{/* )} */}
 
						<div className="flex flex-col">
							{displayName && (
								<h2 className="text-foreground m-0 text-lg font-medium flex items-center">{displayName}</h2>
							)}
 
							{email && <div className="text-sm text-[var(--vscode-descriptionForeground)]">{email}</div>}
 
							<div className="flex gap-2 items-center mt-1">
								{isLockedByRemoteConfig ? (
									<HeroTooltip content="This cannot be changed while your organization has remote configuration enabled.">
										<VSCodeDropdown
											className="w-full"
											currentValue={dropdownValue}
											disabled={isLoading || isLockedByRemoteConfig}
											onChange={handleOrganizationChange}>
											<VSCodeOption key="personal" value={uid}>
												Personal
											</VSCodeOption>
											{userOrganizations?.map((org: UserOrganization) => (
												<VSCodeOption key={org.organizationId} value={org.organizationId}>
													{org.name}
												</VSCodeOption>
											))}
										</VSCodeDropdown>
									</HeroTooltip>
								) : (
									<VSCodeDropdown
										className="w-full"
										currentValue={dropdownValue}
										disabled={isLoading}
										onChange={handleOrganizationChange}>
										<VSCodeOption key="personal" value={uid}>
											Personal
										</VSCodeOption>
										{userOrganizations?.map((org: UserOrganization) => (
											<VSCodeOption key={org.organizationId} value={org.organizationId}>
												{org.name}
											</VSCodeOption>
										))}
									</VSCodeDropdown>
								)}
								{activeOrganization && (
									<VSCodeTag className="text-xs p-2" title="Role">
										{getMainRole(activeOrganization.roles)}
									</VSCodeTag>
								)}
							</div>
						</div>
					</div>
				</div>
 
				<div className="w-full flex gap-2 flex-col min-[225px]:flex-row">
					<div className="w-full min-[225px]:w-1/2">
						<VSCodeButtonLink
							appearance="primary"
							className="w-full"
							href={getAiHydroUris(aihydroUrl, "dashboard").href}>
							Dashboard
						</VSCodeButtonLink>
					</div>
					<VSCodeButton appearance="secondary" className="w-full min-[225px]:w-1/2" onClick={() => handleSignOut()}>
						Log out
					</VSCodeButton>
				</div>
 
				<VSCodeDivider className="w-full my-6" />
 
				<CreditBalance
					balance={balance}
					creditUrl={getAiHydroUris(aihydroUrl, "credits", dropdownValue === uid ? "account" : "organization")}
					fetchCreditBalance={() => fetchCreditBalance(dropdownValue)}
					isLoading={isLoading}
					lastFetchTime={lastFetchTime}
				/>
 
				<VSCodeDivider className="mt-6 mb-3 w-full" />
 
				<div className="flex-grow flex flex-col min-h-0 pb-[0px]">
					<CreditsHistoryTable
						isLoading={isLoading}
						paymentsData={paymentsData}
						showPayments={dropdownValue === uid}
						usageData={usageData}
					/>
				</div>
 
				{isAiHydroTester && (
					<div className="w-full gap-1 items-end">
						<VSCodeDivider className="w-full my-3" />
						<div className="text-sm font-semibold">AI-Hydro Environment</div>
						<VSCodeDropdown
							className="w-full mt-1"
							currentValue={clineEnv}
							onChange={async (e) => {
								const target = e.target as HTMLSelectElement
								if (target?.value) {
									const value = target.value as "Local" | "Staging" | "Production"
									updateSetting("clineEnv", value.toLowerCase())
								}
							}}>
							{AiHydroEnvOptions.map((env) => (
								<VSCodeOption key={env} value={env}>
									{env}
								</VSCodeOption>
							))}
						</VSCodeDropdown>
					</div>
				)}
			</div>
		</div>
	)
}
 
export default memo(AccountView)