sailfork / t3code-github / apps/ mobile/ src/ features/ usage/ UsageLimitsPooled.tsx

import { useAtomValue } from "@effect/atom-react";
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { EnvironmentId } from "@t3tools/contracts";
import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display";
import {
  collectLimitAccounts,
  collectExternalUsageLinks,
  collectLimitNotices,
  collectLimitPools,
  cursorUsageWindowDetails,
  displayLimitWindows,
  formatResetsIn,
  paceRemainingPercent,
  remainingPercent,
  type LimitAccount,
  type LimitPoolWindow,
} from "@t3tools/shared/usageLimits";
import { Fragment, type ReactNode, useId, useState } from "react";
import { Linking, Pressable, View } from "react-native";
import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
import { Defs, Path, Pattern, Rect, Svg } from "react-native-svg";
import { useSafeAreaInsets } from "react-native-safe-area-context";

import { SymbolView } from "../../components/ui/AppSymbol";
import { AppText as Text } from "../../components/ui/AppText";
import { ProviderIcon } from "../../components/ProviderIcon";
import { SettingsScreen } from "../settings/components/SettingsScreen";
import { environmentPresentations } from "../../state/presentation";
import { ResetCredits } from "./UsageLimitsSection";
import { usageProviderKind, useProviderColors } from "./usageProviders";

const DRIVER_LABEL: Partial<Record<string, string>> = {
  codex: "Codex",
  claudeAgent: "Claude",
  grok: "Grok",
  antigravity: "Antigravity",
};
const PACE_LABEL = { ahead: "Ahead of pace", on: "On pace", under: "Under pace" } as const;

function accountName(account: LimitAccount) {
  if (account.displayName) return account.displayName;
  if (!account.email) return DRIVER_LABEL[account.driver] ?? String(account.driver);
  return emailInitials(account.email) || "Account";
}

function emailInitials(email: string) {
  const [local = "", domain = ""] = email.split("@");
  return `${local[0] ?? ""}${domain[0] ?? ""}`.toUpperCase();
}

function accountHue(email: string) {
  let hash = 0;
  for (let index = 0; index < email.length; index += 1) {
    hash = (hash * 31 + email.charCodeAt(index)) | 0;
  }
  return Math.abs(hash) % 360;
}

// Same hashed hue as the web account chip, so an account keeps its color across clients.
function AccountChip({ email }: { readonly email: string }) {
  const hue = accountHue(email);
  return (
    <View
      className="size-5 items-center justify-center rounded-full"
      style={{ backgroundColor: `hsl(${hue}, 45%, 82%)` }}
    >
      <Text className="text-[9px] font-t3-bold" style={{ color: `hsl(${hue}, 45%, 28%)` }}>
        {emailInitials(email)}
      </Text>
    </View>
  );
}

// Same gap-and-tick as the Limits rows: two clipped copies of the segment leave a see-through gap.
function PaceGap({
  timeLeft,
  children,
}: {
  readonly timeLeft: number | null;
  readonly children: ReactNode;
}) {
  const [width, setWidth] = useState(0);
  const tickX =
    timeLeft === null || width < 6
      ? null
      : Math.min(Math.max((width * timeLeft) / 100, 3), width - 3);
  return (
    <View
      pointerEvents="none"
      className="absolute inset-0"
      onLayout={(event) => setWidth(event.nativeEvent.layout.width)}
    >
      {tickX === null
        ? children
        : (
            [
              [0, tickX - 3],
              [tickX + 3, width],
            ] as const
          ).map(([start, end]) => (
            <View
              key={start}
              className="absolute top-0 bottom-0 overflow-hidden"
              style={{ left: start, width: end - start }}
            >
              <View className="absolute top-0 bottom-0" style={{ left: -start, width }}>
                {children}
              </View>
            </View>
          ))}
      {tickX !== null ? (
        <View
          className="absolute top-0.5 bottom-0.5 w-0.5 rounded-full bg-foreground"
          style={{ left: tickX - 1 }}
        />
      ) : null}
    </View>
  );
}

function AccountSegment({
  remaining,
  color,
  refillPercent,
}: {
  readonly remaining: number;
  readonly color: string;
  readonly refillPercent: number;
}) {
  const patternId = useId().replace(/:/g, "");
  const [size, setSize] = useState({ width: 0, height: 0 });
  return (
    <View
      pointerEvents="none"
      className="absolute inset-0"
      onLayout={(event) => {
        const { width, height } = event.nativeEvent.layout;
        setSize((previous) =>
          previous.width === width && previous.height === height ? previous : { width, height },
        );
      }}
    >
      {size.width > 0 && size.height > 0 ? (
        // Numeric canvas dimensions clear Android SVG geometry cached before a segment resized.
        <Svg width={size.width} height={size.height} accessible={false}>
          <Defs>
            <Pattern id={patternId} width={6} height={6} patternUnits="userSpaceOnUse">
              <Path d="M-1 1L1 -1M0 6L6 0M5 7L7 5" stroke={color} strokeWidth={1} opacity={0.22} />
            </Pattern>
          </Defs>
          {refillPercent > 0 ? (
            <Rect
              x={`${100 - Math.min(100 - remaining, refillPercent)}%`}
              width={`${Math.min(100 - remaining, refillPercent)}%`}
              height="100%"
              fill={`url(#${patternId})`}
            />
          ) : null}
          <Rect width={`${remaining}%`} height="100%" fill={color} opacity={0.35} />
        </Svg>
      ) : null}
    </View>
  );
}

function PoolWindowCard({
  pool,
  color,
  now,
  environmentIds,
  label,
  description,
  wide,
}: {
  readonly pool: LimitPoolWindow;
  readonly color: string;
  readonly now: number;
  readonly environmentIds: readonly string[] | null;
  readonly label?: string;
  readonly description?: string;
  readonly wide: boolean;
}) {
  const navigation = useNavigation();
  const [barWidth, setBarWidth] = useState(0);
  // Each segment needs room for its account, percent and reset to label itself.
  const segmentWidth = barWidth / Math.max(pool.columns.length, 1);
  const inlineLabels = wide && segmentWidth >= 96;
  const inlineReset = wide && segmentWidth >= 150;
  const inlineName = wide && segmentWidth >= 220;
  const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0);
  const openAccount = (account: LimitAccount) =>
    navigation.navigate("SettingsUsageAccount", {
      accountKey: account.key,
      windowId: pool.id,
      windowKind: pool.kind,
      environmentIds,
      now,
    });
  const summary = (
    <>
      <View className={wide ? "gap-1" : "flex-row items-start justify-between gap-3"}>
        <View className="gap-1">
          <Text className="text-sm font-t3-medium text-foreground">{label ?? pool.label}</Text>
          <View className="flex-row items-baseline gap-1.5">
            <Text className="text-3xl font-t3-bold tabular-nums text-foreground">
              {pool.remainingPercent}%
            </Text>
            <Text className="text-sm text-foreground-muted">left</Text>
          </View>
        </View>
        {pool.pace ? (
          <Text className="text-xs text-foreground-tertiary">{PACE_LABEL[pool.pace]}</Text>
        ) : null}
      </View>
      {description ? <Text className="text-xs text-foreground-muted">{description}</Text> : null}
      {nextRefill ? (
        <Text className="text-xs tabular-nums text-foreground-muted">
          ↻ +{nextRefill.restoresPercent}%{" "}
          {formatResetsIn(nextRefill.member.window, now)
            ?.replace("resets in ", "in ")
            .replace("resets now", "now")}
        </Text>
      ) : null}
    </>
  );
  const bar = (
    <View
      className="flex-row gap-1"
      onLayout={(event) => setBarWidth(event.nativeEvent.layout.width)}
    >
      {pool.columns.map((member, index) => {
        if (!member.window)
          return (
            <View
              key={member.account.key}
              className={wide ? "h-9 min-w-0 flex-1" : "h-7 min-w-0 flex-1"}
            />
          );
        const { account, window } = member;
        const timeLeft = paceRemainingPercent(window, now);
        const credits = account.limits.resetCredits?.availableCount ?? 0;
        const resetsIn = formatResetsIn(window, now)?.replace("resets in ", "");
        return (
          <Pressable
            key={account.key}
            accessibilityRole="button"
            accessibilityLabel={`Segment ${index + 1}, ${accountName(account)}, ${remainingPercent(window)}% left${timeLeft === null ? "" : `, ${timeLeft}% of the window left`}`}
            accessibilityHint="Show account details"
            onPress={() => openAccount(account)}
            className={wide ? "h-9 min-w-0 flex-1 rounded-md" : "h-7 min-w-0 flex-1 rounded-md"}
          >
            <PaceGap timeLeft={timeLeft}>
              <View className="absolute inset-0 rounded-md bg-subtle" />
              <View className="absolute inset-0 overflow-hidden rounded-md">
                <AccountSegment
                  remaining={remainingPercent(window)}
                  color={normalizeProviderAccentColor(account.accentColor) ?? color}
                  refillPercent={window.resetsAt ? member.refillPercent : 0}
                />
              </View>
            </PaceGap>
            {inlineLabels ? (
              <View
                pointerEvents="none"
                className="absolute inset-0 flex-row items-center justify-between gap-2 overflow-hidden rounded-md px-2"
              >
                <View className="min-w-0 shrink flex-row items-center gap-1.5">
                  {account.email ? <AccountChip email={account.email} /> : null}
                  {account.email && !(account.displayName && inlineName) ? null : (
                    <Text
                      numberOfLines={1}
                      className="min-w-0 shrink text-xs font-t3-medium text-foreground"
                    >
                      {accountName(account)}
                    </Text>
                  )}
                  <Text className="text-sm font-t3-bold tabular-nums text-foreground">
                    {remainingPercent(window)}%
                  </Text>
                </View>
                {inlineReset && (resetsIn || credits) ? (
                  <View className="shrink-0 flex-row items-center gap-1 rounded bg-grouped-card/85 px-1.5 py-0.5">
                    {resetsIn ? (
                      <>
                        <SymbolView
                          name="arrow.clockwise"
                          size={11}
                          tintColorClassName="accent-foreground-muted"
                        />
                        <Text className="text-xs tabular-nums text-foreground-muted">
                          {resetsIn}
                        </Text>
                      </>
                    ) : null}
                    {credits ? (
                      <>
                        <SymbolView name="ticket" size={12} tintColorClassName="accent-icon" />
                        <Text className="text-xs font-t3-medium tabular-nums text-foreground">
                          {credits}
                        </Text>
                      </>
                    ) : null}
                  </View>
                ) : null}
              </View>
            ) : (
              <View
                pointerEvents="none"
                className="absolute inset-0 items-center justify-center overflow-hidden rounded-md"
              >
                <Text
                  numberOfLines={1}
                  className="max-w-full shrink text-xs font-t3-medium tabular-nums text-foreground"
                >
                  {index + 1}
                </Text>
              </View>
            )}
          </Pressable>
        );
      })}
    </View>
  );
  const legend = (
    <View>
      {pool.columns.map(({ account, window }, index) => {
        if (!window) return null;
        const segmentColor = normalizeProviderAccentColor(account.accentColor) ?? color;
        const credits = account.limits.resetCredits?.availableCount ?? 0;
        const resetsIn = formatResetsIn(window, now);
        return (
          <Pressable
            key={account.key}
            accessibilityRole="button"
            accessibilityLabel={`Segment ${index + 1}, ${accountName(account)}, ${remainingPercent(window)}% left${resetsIn ? `, ${resetsIn}` : ""}${credits ? `, ${credits} reset credits banked` : ""}`}
            accessibilityHint="Show account details"
            onPress={() => openAccount(account)}
            className="min-h-[44px] flex-row items-center gap-2 active:opacity-60"
          >
            <View className="relative size-5 items-center justify-center overflow-hidden rounded-md bg-subtle-strong">
              <View
                pointerEvents="none"
                className="absolute inset-0"
                style={{ backgroundColor: segmentColor, opacity: 0.35 }}
              />
              <Text className="text-xs font-t3-medium tabular-nums text-foreground">
                {index + 1}
              </Text>
            </View>
            <Text
              numberOfLines={1}
              className="min-w-0 flex-1 text-sm font-t3-medium text-foreground"
            >
              {accountName(account)}
            </Text>
            <Text className="text-sm font-t3-medium tabular-nums text-foreground">
              {remainingPercent(window)}%
            </Text>
            <View className="flex-row items-center gap-1">
              {resetsIn ? (
                <>
                  <SymbolView
                    name="arrow.clockwise"
                    size={12}
                    tintColorClassName="accent-foreground-muted"
                  />
                  <Text className="text-xs tabular-nums text-foreground-muted">
                    {resetsIn.replace("resets in ", "")}
                  </Text>
                </>
              ) : null}
              {credits ? (
                <>
                  {resetsIn ? <Text className="text-xs text-foreground-tertiary">·</Text> : null}
                  <SymbolView name="ticket" size={13} tintColorClassName="accent-icon" />
                  <Text className="text-xs font-t3-medium tabular-nums text-foreground">
                    {credits}
                  </Text>
                </>
              ) : null}
            </View>
          </Pressable>
        );
      })}
    </View>
  );
  if (wide) {
    return (
      <View className="flex-row items-center gap-6 rounded-[24px] border-continuous bg-grouped-card p-4">
        <View className="w-44 gap-1">{summary}</View>
        <View className="min-w-0 flex-1 gap-1">
          {bar}
          {inlineLabels ? null : legend}
        </View>
      </View>
    );
  }
  return (
    <View className="gap-3 rounded-[24px] border-continuous bg-grouped-card p-4">
      {summary}
      {bar}
      {legend}
    </View>
  );
}

export function UsageLimitsSection({
  now,
  failedLabels,
  selectedEnvironmentIds,
  cursorPrompt,
  wide = false,
}: {
  readonly now: number;
  readonly failedLabels: readonly string[];
  readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
  readonly cursorPrompt?: ReactNode;
  readonly wide?: boolean;
}) {
  const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom);
  const selected =
    selectedEnvironmentIds === null
      ? presentations
      : new Map([...presentations].filter(([id]) => selectedEnvironmentIds.has(id)));
  const pools = collectLimitPools(collectLimitAccounts(selected), now);
  const notices = collectLimitNotices(selected);
  const externalLinks = collectExternalUsageLinks(selected);
  const colors = useProviderColors();
  const cursorPromptAt =
    Math.max(
      pools.findIndex((pool) => pool.driver === "codex"),
      pools.findIndex((pool) => pool.driver === "claudeAgent"),
    ) + 1;
  return (
    <View className="gap-6">
      {pools.length === 0 &&
      notices.length === 0 &&
      failedLabels.length === 0 &&
      !cursorPrompt &&
      externalLinks.length === 0 ? (
        <Text className="py-12 text-center text-base text-foreground-muted">
          {selected.size === 0
            ? "Select an environment to see limits."
            : "No provider on the selected environments reports subscription limits."}
        </Text>
      ) : null}
      {pools.map((pool, index) => {
        const windows = displayLimitWindows(pool);
        return (
          <Fragment key={pool.driver}>
            {index === cursorPromptAt ? cursorPrompt : null}
            <View className="gap-3">
              <View className="flex-row items-center gap-2 px-1">
                <ProviderIcon provider={pool.driver} size={18} />
                <Text className="text-base font-t3-medium text-foreground">
                  {DRIVER_LABEL[pool.driver] ?? pool.driver}
                </Text>
              </View>
              {windows.map((window) => {
                const details =
                  pool.driver === "cursor" ? cursorUsageWindowDetails(window.id) : undefined;
                return (
                  <PoolWindowCard
                    key={`${window.kind}:${window.id}`}
                    pool={window}
                    color={colors[usageProviderKind(pool.driver) ?? "codex"]}
                    now={now}
                    environmentIds={
                      selectedEnvironmentIds === null ? null : [...selectedEnvironmentIds]
                    }
                    label={details?.label}
                    description={details?.description}
                    wide={wide}
                  />
                );
              })}
            </View>
          </Fragment>
        );
      })}
      {cursorPromptAt === pools.length ? cursorPrompt : null}
      {externalLinks.map((link) => (
        <View key={link.url} className="gap-3 rounded-xl border border-border-subtle p-4">
          <Text className="text-base font-t3-medium text-foreground">{link.label}</Text>
          <Text className="text-xs text-foreground-muted">{link.accounts.join(", ")}</Text>
          {link.message ? (
            <Text className="text-sm text-foreground-muted">{link.message}</Text>
          ) : null}
          <Pressable
            accessibilityRole="link"
            className="min-h-11 justify-center"
            onPress={() => void Linking.openURL(link.url).catch(() => undefined)}
          >
            <Text className="text-sm font-t3-medium text-primary">Manage usage</Text>
          </Pressable>
        </View>
      ))}
      {notices.length > 0 || failedLabels.length > 0 ? (
        <View
          accessible
          accessibilityRole="alert"
          accessibilityLiveRegion="polite"
          className="flex-row items-start gap-2 rounded-xl border border-warning-border bg-warning px-3.5 py-3"
        >
          <SymbolView
            name="exclamationmark.triangle"
            size={16}
            tintColorClassName="accent-warning-foreground"
          />
          <View className="min-w-0 flex-1 gap-0.5">
            {notices.map((notice) => (
              <Text key={notice} className="text-sm font-t3-medium text-warning-foreground">
                {notice}
              </Text>
            ))}
            {failedLabels.length > 0 ? (
              <Text className="text-sm font-t3-medium text-warning-foreground">
                {failedLabels.join(", ")} could not refresh limits. Showing the last known values.
              </Text>
            ) : null}
          </View>
        </View>
      ) : null}
    </View>
  );
}

type AccountScreenProps = StaticScreenProps<{
  accountKey: string;
  windowId: string;
  windowKind: LimitPoolWindow["kind"];
  environmentIds: readonly string[] | null;
  now: number;
}>;

export function UsageLimitAccountScreen({ route }: AccountScreenProps) {
  const insets = useSafeAreaInsets();
  const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom);
  const { accountKey, windowId, windowKind, environmentIds, now } = route.params;
  const selectedIds =
    environmentIds === null ? null : new Set(environmentIds.map((id) => EnvironmentId.make(id)));
  const selected =
    selectedIds === null
      ? presentations
      : new Map([...presentations].filter(([id]) => selectedIds.has(id)));
  const accounts = collectLimitAccounts(selected);
  const account = accounts.find((candidate) => candidate.key === accountKey);
  const pool = collectLimitPools(accounts, now)
    .find((candidate) => candidate.driver === account?.driver)
    ?.windows.find((candidate) => candidate.id === windowId && candidate.kind === windowKind);
  const window = pool?.members.find((member) => member.account.key === accountKey)?.window;
  const evenPace = window ? paceRemainingPercent(window, now) : null;
  const reset = pool?.resets.find((candidate) => candidate.member.account.key === accountKey);
  const [revealed, setRevealed] = useState(false);
  return (
    <SettingsScreen title="Account">
      <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        contentContainerClassName="gap-5 p-5"
        contentContainerStyle={{ paddingBottom: insets.bottom + 24 }}
      >
        {!account || !window ? (
          <Text className="text-base text-foreground-muted">
            This account is no longer reporting limits on the selected environments.
          </Text>
        ) : (
          <>
            <View className="gap-2">
              <View className="flex-row items-center gap-2">
                <ProviderIcon provider={account.driver} size={24} />
                <Text className="flex-1 text-xl font-t3-bold text-foreground">
                  {account.displayName ?? DRIVER_LABEL[account.driver] ?? account.driver}
                </Text>
              </View>
              {account.email ? (
                <Pressable
                  accessibilityRole="button"
                  accessibilityLabel={revealed ? "Hide account email" : "Reveal account email"}
                  onPress={() => setRevealed((value) => !value)}
                  className="min-h-[44px] justify-center"
                >
                  <Text className="text-sm text-foreground-muted">
                    {revealed ? account.email : "••••••@••••••"}
                  </Text>
                </Pressable>
              ) : null}
              {account.plan ? (
                <Text selectable className="text-sm text-foreground-muted">
                  {account.plan}
                </Text>
              ) : null}
            </View>
            <View className="gap-3 rounded-[24px] border-continuous bg-grouped-card p-4">
              <Text className="text-sm font-t3-medium text-foreground">{window.label}</Text>
              <Text className="text-3xl font-t3-bold tabular-nums text-foreground">
                {remainingPercent(window)}% left
              </Text>
              {window.resetsAt ? (
                <Text selectable className="text-sm text-foreground-muted">
                  Resets{" "}
                  {new Date(window.resetsAt).toLocaleString(undefined, {
                    dateStyle: "medium",
                    timeStyle: "short",
                  })}
                </Text>
              ) : null}
              {evenPace !== null ? (
                <Text className="text-sm text-foreground-muted">
                  Even pace: {evenPace}% left by now
                </Text>
              ) : null}
              {reset && reset.restoresPercent > 0 ? (
                <Text className="text-sm text-foreground-muted">
                  Restores {reset.restoresPercent}% of the pool
                </Text>
              ) : null}
            </View>
            <View className="gap-2 rounded-[24px] border-continuous bg-grouped-card p-4">
              <Text className="text-sm font-t3-medium text-foreground">
                {account.environments.length ? "Signed in" : "Source"}
              </Text>
              {account.environments.length ? (
                account.environments.map((environment) => (
                  <Text key={environment.environmentId} className="text-sm text-foreground-muted">
                    {environment.label}
                  </Text>
                ))
              ) : (
                <Text className="text-sm text-foreground-muted">{account.sourceLabel}</Text>
              )}
            </View>
            {account.redeem && account.limits.resetCredits ? (
              <View className="gap-3 rounded-[24px] border-continuous bg-grouped-card p-4">
                <Text className="text-sm font-t3-medium text-foreground">Reset credits</Text>
                <ResetCredits
                  key={account.key}
                  environmentId={account.redeem.environmentId}
                  input={account.redeem.input}
                  credits={account.limits.resetCredits}
                  now={now}
                />
              </View>
            ) : null}
          </>
        )}
      </ScrollView>
    </SettingsScreen>
  );
}