Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

18.8 KB
Raw Blame
'use client';

import type {
  CodexQuotaSnapshot,
  CodexQuotaWindow,
  CodexRateLimitResetCredit,
} from '@lobechat/electron-client-ipc';
import { uuid } from '@lobechat/utils';
import { Accordion, Button, confirmModal, Flexbox, Icon, Text, toast } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import { RotateCcwIcon, WalletIcon } from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
import { createCodexQuotaReader } from '@/services/codexQuota';
import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';

import QuotaAccountSwitcher from './QuotaAccountSwitcher';
import type { QuotaMenuHelpers, QuotaWindowItem } from './QuotaMenu';
import QuotaMenu, { createQuotaSourceKey } from './QuotaMenu';

const FIVE_HOUR_WINDOW_MINUTES = 5 * 60;
const WEEKLY_WINDOW_MINUTES = 7 * 24 * 60;
const MONTHLY_WINDOW_MIN_MINUTES = 28 * 24 * 60;
const MONTHLY_WINDOW_MAX_MINUTES = 31 * 24 * 60;

// Reference API usage value from the published Codex token rates.
// https://learn.chatgpt.com/docs/pricing#token-rates
const ESTIMATED_USD_PER_CODEX_CREDIT = 0.04;

const formatCreditsUsdEstimate = (credits: CodexQuotaSnapshot['credits'], locale: string) => {
  if (credits?.unlimited || !credits?.balance?.trim()) return;

  const balance = Number(credits.balance);
  if (!Number.isFinite(balance) || balance < 0) return;

  const estimate = balance * ESTIMATED_USD_PER_CODEX_CREDIT;
  return new Intl.NumberFormat(locale, {
    currency: 'USD',
    currencyDisplay: 'narrowSymbol',
    maximumFractionDigits: estimate < 1 ? 2 : 0,
    minimumFractionDigits: 0,
    style: 'currency',
  }).format(estimate);
};

const isConnectionError = (quota: CodexQuotaSnapshot) =>
  /error sending request for url|fetch failed|\b(?:ECONNREFUSED|ENOTFOUND|ETIMEDOUT)\b/i.test(
    quota.error ?? '',
  );

const styles = stylex.create({
  credit: {
    minWidth: '0',
    paddingBlock: '8px',
    paddingInline: '10px',
    borderBlockEndWidth: { 'default': '1px', ':last-child': '0' },
    borderBlockEndStyle: 'solid',
    borderBlockEndColor: cssVar.colorBorderSecondary,
  },
  creditCollapse: { width: '100%' },
  creditExpiry: { flex: 'none', textAlign: 'end', whiteSpace: 'nowrap' },
  creditIndex: {
    flexGrow: '0',
    flexShrink: '0',
    flexBasis: '20px',
    fontVariantNumeric: 'tabular-nums',
    color: cssVar.colorTextTertiary,
    textAlign: 'center',
  },
  creditList: {
    overflow: 'hidden',
    borderWidth: '1px',
    borderStyle: 'solid',
    borderColor: cssVar.colorBorderSecondary,
    borderRadius: cssVar.borderRadius,
    backgroundColor: cssVar.colorFillQuaternary,
    backgroundImage: 'none',
  },
  creditTitle: {
    overflow: 'hidden',
    flex: '1',
    minWidth: '0',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
  },
  feedback: {
    padding: '8px',
    borderWidth: '1px',
    borderStyle: 'solid',
    borderColor: cssVar.colorInfoBorder,
    borderRadius: cssVar.borderRadius,
    color: cssVar.colorInfoText,
    backgroundColor: cssVar.colorInfoBg,
    backgroundImage: 'none',
  },
  // [data-kind='error']
  feedbackError: {
    borderColor: cssVar.colorErrorBorder,
    color: cssVar.colorErrorText,
    backgroundColor: cssVar.colorErrorBg,
    backgroundImage: 'none',
  },
  // [data-kind='success']
  feedbackSuccess: {
    borderColor: cssVar.colorSuccessBorder,
    color: cssVar.colorSuccessText,
    backgroundColor: cssVar.colorSuccessBg,
    backgroundImage: 'none',
  },
  footerSection: {
    paddingBlockStart: '8px',
    borderBlockStartWidth: '1px',
    borderBlockStartStyle: 'solid',
    borderBlockStartColor: cssVar.colorBorderSecondary,
  },
});

const createErrorSnapshot = (error: unknown): CodexQuotaSnapshot => ({
  error: error instanceof Error ? error.message : String(error),
  provider: 'codex',
  rateLimitResetCredits: null,
  session: null,
  status: 'error',
  updatedAt: Date.now(),
  weekly: null,
});

const getAvailableResetCredits = (credits: CodexRateLimitResetCredit[] | undefined, now: number) =>
  [...(credits ?? [])]
    .filter(
      (credit) =>
        credit.status === 'available' && (credit.expiresAt === null || credit.expiresAt > now),
    )
    .sort((left, right) => {
      const expiryDifference =
        (left.expiresAt ?? Number.POSITIVE_INFINITY) -
        (right.expiresAt ?? Number.POSITIVE_INFINITY);
      if (expiryDifference !== 0) return expiryDifference;
      return (left.id ?? '').localeCompare(right.id ?? '');
    });

interface CodexQuotaMenuProps {
  command?: string;
  deviceId?: string;
  env?: Record<string, string>;
}

interface ResetAttempt {
  creditId?: string;
  idempotencyKey: string;
}

interface ResetFeedback {
  kind: 'error' | 'info' | 'success';
  text: string;
}

const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, deviceId, env }) => {
  const { i18n, t } = useTranslation('chat');
  const agentId = useAgentId();
  const sourceKey = createQuotaSourceKey('codex', agentId, deviceId, command, env);
  const activeSourceKeyRef = useRef(sourceKey);
  const resetAttemptRef = useRef<ResetAttempt | null>(null);
  const [resetFeedback, setResetFeedback] = useState<ResetFeedback>();
  const [resetting, setResetting] = useState(false);

  useEffect(() => {
    activeSourceKeyRef.current = sourceKey;
    resetAttemptRef.current = null;
    setResetFeedback(undefined);
    setResetting(false);
  }, [sourceKey]);

  const fetchQuota = useMemo(
    () => createCodexQuotaReader({ agentId, command, deviceId, env }),
    [agentId, command, deviceId, env],
  );

  const getWindowLabel = useCallback(
    (window: CodexQuotaWindow | null, fallback: string) => {
      if (!window) return fallback;
      if (window.windowMinutes === FIVE_HOUR_WINDOW_MINUTES) {
        return t('heteroAgent.codexQuota.fiveHour');
      }
      if (window.windowMinutes === WEEKLY_WINDOW_MINUTES) {
        return t('heteroAgent.quota.weekly');
      }
      if (
        window.windowMinutes >= MONTHLY_WINDOW_MIN_MINUTES &&
        window.windowMinutes <= MONTHLY_WINDOW_MAX_MINUTES
      ) {
        return t('heteroAgent.codexQuota.monthly');
      }
      return fallback;
    },
    [t],
  );

  const getWindows = useCallback(
    (quota: CodexQuotaSnapshot): QuotaWindowItem[] => {
      const rateLimit = quota.rateLimits?.find(
        (rateLimit) => rateLimit.limitId.toLowerCase() === 'codex',
      );

      if (!rateLimit) {
        return [
          {
            key: 'primary',
            label: getWindowLabel(quota.session, t('heteroAgent.quota.session')),
            window: quota.session,
          },
          {
            key: 'secondary',
            label: getWindowLabel(quota.weekly, t('heteroAgent.quota.weekly')),
            window: quota.weekly,
          },
        ];
      }

      return [
        {
          key: `${rateLimit.limitId}:primary`,
          label: getWindowLabel(rateLimit.primary, t('heteroAgent.quota.session')),
          window: rateLimit.primary,
        },
        {
          key: `${rateLimit.limitId}:secondary`,
          label: getWindowLabel(rateLimit.secondary, t('heteroAgent.quota.weekly')),
          window: rateLimit.secondary,
        },
      ];
    },
    [getWindowLabel, t],
  );

  const hasExtraData = useCallback(
    (quota: CodexQuotaSnapshot) => !!quota.credits || (!deviceId && !!quota.rateLimitResetCredits),
    [deviceId],
  );

  const getErrorText = useCallback(
    (quota: CodexQuotaSnapshot) =>
      isConnectionError(quota)
        ? t('heteroAgent.codexQuota.errorConnection')
        : t('heteroAgent.codexQuota.errorGeneric'),
    [t],
  );

  const consumeReset = useCallback(
    async (
      creditId: string | undefined,
      applyQuota: (quota: CodexQuotaSnapshot) => void,
      requestSourceKey: string,
    ) => {
      const previousAttempt = resetAttemptRef.current;
      const attempt =
        previousAttempt && previousAttempt.creditId === creditId
          ? previousAttempt
          : {
              ...(creditId ? { creditId } : {}),
              idempotencyKey: uuid(),
            };
      resetAttemptRef.current = attempt;
      setResetFeedback(undefined);
      setResetting(true);

      try {
        const result = await heterogeneousAgentService.consumeCodexRateLimitResetCredit({
          command,
          ...(attempt.creditId ? { creditId: attempt.creditId } : {}),
          env,
          idempotencyKey: attempt.idempotencyKey,
        });
        if (activeSourceKeyRef.current !== requestSourceKey) return;

        applyQuota(result.quota);
        void fetchQuota
          .acceptLocalSnapshot(result.quota)
          .catch((error) => console.error('[codexQuota:reset-ingest]', error));
        resetAttemptRef.current = null;

        switch (result.outcome) {
          case 'alreadyRedeemed':
          case 'reset': {
            const text = t('heteroAgent.codexQuota.resetSuccess');
            setResetFeedback({ kind: 'success', text });
            toast.success(text);
            break;
          }
          case 'nothingToReset': {
            setResetFeedback({
              kind: 'info',
              text: t('heteroAgent.codexQuota.resetNothingToReset'),
            });
            break;
          }
          case 'noCredit': {
            setResetFeedback({
              kind: 'error',
              text: t('heteroAgent.codexQuota.resetNoCredit'),
            });
            break;
          }
        }
      } catch (error) {
        console.error('Failed to consume Codex rate-limit reset credit:', error);
        if (activeSourceKeyRef.current !== requestSourceKey) return;

        const text = t('heteroAgent.codexQuota.resetFailed');
        setResetFeedback({ kind: 'error', text });
        toast.error(text);
      } finally {
        if (activeSourceKeyRef.current === requestSourceKey) setResetting(false);
      }
    },
    [command, env, fetchQuota, t],
  );

  const confirmReset = useCallback(
    (creditId: string | undefined, applyQuota: (quota: CodexQuotaSnapshot) => void) => {
      const requestSourceKey = sourceKey;
      confirmModal({
        cancelText: t('cancel', { ns: 'common' }),
        content: t('heteroAgent.codexQuota.resetConfirmDescription'),
        okText: t('heteroAgent.codexQuota.resetNow'),
        onOk: () => consumeReset(creditId, applyQuota, requestSourceKey),
        title: t('heteroAgent.codexQuota.resetConfirmTitle'),
      });
    },
    [consumeReset, sourceKey, t],
  );

  const renderResetCredits = useCallback(
    (
      quota: CodexQuotaSnapshot,
      { applyQuota, formatDuration, now }: QuotaMenuHelpers<CodexQuotaSnapshot>,
    ) => {
      const resetCredits = quota.rateLimitResetCredits;

      if (!resetCredits) {
        return (
          <Flexbox className={stylex.props(styles.footerSection).className} gap={4}>
            <Flexbox horizontal align={'center'} gap={4}>
              <Icon icon={RotateCcwIcon} size={14} />
              <Text style={{ fontSize: 12 }} type="secondary">
                {t('heteroAgent.codexQuota.resetCreditsUnavailable')}
              </Text>
            </Flexbox>
          </Flexbox>
        );
      }

      const resetCreditCount = resetCredits.availableCount;
      const availableCredits = getAvailableResetCredits(resetCredits.credits, now).slice(
        0,
        resetCreditCount,
      );
      const nextCredit = availableCredits[0];
      const resetCreditItems = Array.from({ length: resetCreditCount }, (_, index) => ({
        credit: availableCredits[index],
        index: index + 1,
      }));

      return (
        <Flexbox className={stylex.props(styles.footerSection).className}>
          <Accordion
            className={stylex.props(styles.creditCollapse).className}
            defaultValue={[]}
            indicatorPlacement={'end'}
            variant={'borderless'}
            items={[
              {
                children: (
                  <Flexbox gap={8}>
                    {resetCreditItems.length > 0 && (
                      <Flexbox className={stylex.props(styles.creditList).className}>
                        {resetCreditItems.map(({ credit, index }) => {
                          const fallbackExpiry =
                            index === 1 ? resetCredits.nextExpiresAt : undefined;
                          const expiresAt = credit ? credit.expiresAt : fallbackExpiry;
                          const expiresIn = expiresAt ? formatDuration(expiresAt - now) : undefined;

                          return (
                            <Flexbox
                              horizontal
                              align={'center'}
                              className={stylex.props(styles.credit).className}
                              gap={8}
                              key={credit?.id ?? `reset-credit-${index}`}
                            >
                              <Text
                                className={stylex.props(styles.creditIndex).className}
                                style={{ fontSize: 12 }}
                              >
                                {`#${index}`}
                              </Text>
                              <Text
                                strong
                                className={stylex.props(styles.creditTitle).className}
                                style={{ fontSize: 12 }}
                              >
                                {credit?.title || t('heteroAgent.codexQuota.resetCreditTitle')}
                              </Text>
                              <Text
                                className={stylex.props(styles.creditExpiry).className}
                                style={{ fontSize: 12 }}
                                type="secondary"
                              >
                                {expiresAt
                                  ? expiresIn
                                    ? t('heteroAgent.codexQuota.expiresIn', {
                                        duration: expiresIn,
                                      })
                                    : t('heteroAgent.codexQuota.expiresSoon')
                                  : credit
                                    ? t('heteroAgent.codexQuota.doesNotExpire')
                                    : t('heteroAgent.codexQuota.resetCreditDetailsUnavailable')}
                              </Text>
                            </Flexbox>
                          );
                        })}
                      </Flexbox>
                    )}

                    {resetFeedback && (
                      <div
                        aria-live="polite"
                        data-kind={resetFeedback.kind}
                        role={resetFeedback.kind === 'error' ? 'alert' : 'status'}
                        {...stylex.props(
                          styles.feedback,
                          resetFeedback.kind === 'error' && styles.feedbackError,
                          resetFeedback.kind === 'success' && styles.feedbackSuccess,
                        )}
                      >
                        {resetFeedback.text}
                      </div>
                    )}

                    {resetCreditCount > 0 && (
                      <Button
                        block
                        icon={RotateCcwIcon}
                        loading={resetting}
                        size={'small'}
                        type={'primary'}
                        onClick={() => confirmReset(nextCredit?.id ?? undefined, applyQuota)}
                      >
                        {resetting
                          ? t('heteroAgent.codexQuota.resetting')
                          : t('heteroAgent.codexQuota.resetNow')}
                      </Button>
                    )}
                  </Flexbox>
                ),
                disabled: !(resetCreditCount > 0 || !!resetFeedback),
                key: 'reset-credits',
                title: (
                  <Flexbox gap={2}>
                    <Flexbox horizontal align={'center'} gap={4}>
                      <Icon icon={RotateCcwIcon} size={14} />
                      <Text strong style={{ fontSize: 12 }}>
                        {t('heteroAgent.codexQuota.resetCredits', { count: resetCreditCount })}
                      </Text>
                    </Flexbox>
                    {resetCredits.totalEarnedCount !== undefined && (
                      <Text color={cssVar.colorTextTertiary} style={{ fontSize: 12 }}>
                        {t('heteroAgent.codexQuota.totalEarned', {
                          count: resetCredits.totalEarnedCount,
                        })}
                      </Text>
                    )}
                  </Flexbox>
                ),
              },
            ]}
          />
        </Flexbox>
      );
    },
    [confirmReset, resetFeedback, resetting, t],
  );

  return (
    <QuotaMenu
      contentWidth={360}
      createErrorSnapshot={createErrorSnapshot}
      fetchQuota={fetchQuota}
      getErrorText={getErrorText}
      getWindows={getWindows}
      hasExtraData={hasExtraData}
      retainLastSnapshotOnError={false}
      sourceKey={sourceKey}
      title={t('heteroAgent.codexQuota.title')}
      tooltip={t('heteroAgent.codexQuota.tooltip')}
      renderFooter={(quota, helpers) => {
        const { credits } = quota;
        const usdEstimate = formatCreditsUsdEstimate(credits, i18n.language);

        return (
          <>
            {renderResetCredits(quota, helpers)}
            {credits && (
              <Flexbox
                horizontal
                align={'center'}
                className={stylex.props(styles.footerSection).className}
                gap={8}
                justify={'space-between'}
              >
                <Flexbox horizontal align={'center'} gap={4}>
                  <Icon icon={WalletIcon} size={14} />
                  <Text style={{ fontSize: 12 }} type="secondary">
                    {t('heteroAgent.codexQuota.creditsBalance')}
                  </Text>
                </Flexbox>
                <Flexbox horizontal align={'center'} gap={8} justify={'flex-end'} wrap={'wrap'}>
                  <Text style={{ fontSize: 12 }}>
                    {credits.unlimited
                      ? t('heteroAgent.codexQuota.creditsUnlimited')
                      : credits.balance}
                  </Text>
                  {usdEstimate && (
                    <Text style={{ fontSize: 12, whiteSpace: 'nowrap' }} type="secondary">
                      {t('heteroAgent.codexQuota.creditsUsdEstimate', { amount: usdEstimate })}
                    </Text>
                  )}
                </Flexbox>
              </Flexbox>
            )}
          </>
        );
      }}
      renderHeader={(quota) => (
        <QuotaAccountSwitcher placement="top" provider="codex" snapshot={quota} />
      )}
    />
  );
});

CodexQuotaMenu.displayName = 'CodexQuotaMenu';

export default CodexQuotaMenu;