Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions apps/mobile/src/features/usage/UsageLimitsPooled.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ import {
remainingPercent,
type LimitAccount,
type LimitPoolWindow,
resetCreditsForWindow,
} from "@t3tools/shared/usageLimits";
import {
usageShareSummary,
collectExternalUsageLinks,
collectLimitNotices,
cursorUsageWindowDetails,
Expand Down Expand Up @@ -248,7 +250,10 @@ function PoolWindowCard({
);
const { account, window } = member;
const timeLeft = paceRemainingPercent(window, now);
const credits = account.limits.resetCredits?.availableCount ?? 0;
const { count: credits, scope } = resetCreditsForWindow(
account.limits.resetCredits,
window.id,
);
const resetsIn = resetLabels(window, now, m)?.compact;
return (
<Pressable
Expand Down Expand Up @@ -324,6 +329,9 @@ function PoolWindowCard({
<Text className="text-xs font-t3-medium tabular-nums text-foreground">
{credits}
</Text>
{scope ? (
<Text className="text-xs text-foreground-muted">{scope}</Text>
) : null}
</>
) : null}
</View>
Expand Down Expand Up @@ -352,15 +360,18 @@ function PoolWindowCard({
{pool.columns.map(({ account, window }, index) => {
if (!window) return null;
const segmentColor = normalizeProviderAccentColor(account.accentColor) ?? color;
const credits = account.limits.resetCredits?.availableCount ?? 0;
const { count: credits, scope } = resetCreditsForWindow(
account.limits.resetCredits,
window.id,
);
const reset = resetLabels(window, now, m);
const resetsIn = reset?.full;
return (
<Pressable
key={account.key}
accessibilityRole="button"
accessibilityLabel={
resetsIn && credits
(resetsIn && credits
? gt(
"Segment {index}, {account}, {remaining}% left, {resetsIn}, {credits, plural, other {{credits} reset credits banked}}",
{
Expand Down Expand Up @@ -392,7 +403,7 @@ function PoolWindowCard({
index: index + 1,
account: accountName(account, m),
remaining: remainingPercent(window),
})
})) + (credits && scope ? `, ${scope}` : "")
}
accessibilityHint={gt("Show account details")}
onPress={() => openAccount(account)}
Expand Down Expand Up @@ -437,6 +448,7 @@ function PoolWindowCard({
<Text className="text-xs font-t3-medium tabular-nums text-foreground">
{credits}
</Text>
{scope ? <Text className="text-xs text-foreground-muted">{scope}</Text> : null}
</>
) : null}
</View>
Expand Down Expand Up @@ -515,6 +527,7 @@ export function UsageLimitsSection({
pool.driver === "cursor"
? cursorUsageWindowDetails(window.id, pool, m)
: undefined;
const share = window.members.find((member) => member.window.share)?.window.share;
return (
<PoolWindowCard
key={`${window.kind}:${window.id}`}
Expand All @@ -525,7 +538,9 @@ export function UsageLimitsSection({
selectedEnvironmentIds === null ? null : [...selectedEnvironmentIds]
}
label={details?.label}
description={details?.description}
description={
details?.description ?? usageShareSummary(share, windows, m) ?? undefined
}
wide={wide}
/>
);
Expand Down
45 changes: 31 additions & 14 deletions apps/mobile/src/features/usage/UsageLimitsSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,14 @@ import {
paceRemainingPercent,
remainingPercent,
resetCountdown,
sharedUsage,
} from "@t3tools/shared/usageLimits";
import { formatDuration, limitsNotice, resetCreditChoices } from "@t3tools/shared/usageLimitsCopy";
import {
usageShareSummary,
formatDuration,
limitsNotice,
resetCreditChoices,
} from "@t3tools/shared/usageLimitsCopy";
import { msg, T, useGT, useMessages, Var } from "gt-react-native";
import { type ReactNode, useContext, useRef, useState } from "react";
import { Atom } from "effect/reactivity";
Expand Down Expand Up @@ -57,14 +63,19 @@ function useBarColor(driver: Driver): string | null {

function WindowRow(props: {
readonly window: ServerProviderUsageWindow;
readonly windows: ReadonlyArray<ServerProviderUsageWindow>;
readonly color: string | null;
readonly now: number;
}) {
const { window, now } = props;
const remaining = remainingPercent(window);
const shared = sharedUsage(window, props.windows)?.percent ?? 0;
const fill = remaining <= 10 ? "bg-red-500" : remaining <= 30 ? "bg-amber-500" : "bg-foreground";
const fillColor = remaining > 30 && props.color ? { backgroundColor: props.color } : null;
const timeLeft = paceRemainingPercent(window, now);
const pace = paceOf(window, now);
const m = useMessages();
const shareSummary = usageShareSummary(window.share, props.windows, m);
const resetsIn = resetLabels(window, now, m)?.full;
const [barWidth, setBarWidth] = useState(0);
const tickX =
Expand All @@ -77,19 +88,16 @@ function WindowRow(props: {
style={barWidth > 0 ? { width: barWidth } : undefined}
>
<View
className={
remaining <= 10
? "h-full rounded-full bg-red-500"
: remaining <= 30
? "h-full rounded-full bg-amber-500"
: "h-full rounded-full bg-foreground"
}
style={[
{ flex: remaining },
remaining > 30 && props.color ? { backgroundColor: props.color } : null,
]}
className={`h-full ${shared > 0 ? "rounded-l-full" : "rounded-full"} ${window.share ? "opacity-40" : ""} ${fill}`}
style={[{ flex: remaining }, fillColor]}
/>
<View style={{ flex: 100 - remaining }} />
{shared > 0 ? (
<View
className={`h-full opacity-40 ${remaining > 0 ? "rounded-r-full" : "rounded-full"} ${fill}`}
style={[{ flex: shared }, fillColor]}
/>
) : null}
<View style={{ flex: 100 - remaining - shared }} />
</View>
);
return (
Expand All @@ -102,6 +110,9 @@ function WindowRow(props: {
</T>
</Text>
</View>
{shareSummary ? (
<Text className="text-xs text-foreground-tertiary">{shareSummary}</Text>
) : null}
<View
className="h-3 justify-center"
onLayout={(event) => setBarWidth(event.nativeEvent.layout.width)}
Expand Down Expand Up @@ -217,7 +228,13 @@ export function AccountLimits(props: {
) : (
<View className="gap-3">
{limits.windows.map((window) => (
<WindowRow key={window.id} window={window} color={color} now={now} />
<WindowRow
key={window.id}
window={window}
windows={limits.windows}
color={color}
now={now}
/>
))}
</View>
)}
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/src/i18n/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,8 @@
"732708950237004e": "Dieser Client ist älter als der Server auf {environment}; seine Nutzung wird nicht in die Summen einbezogen.",
"9758c2ede06aa19b": "heute {hour}",
"9102fd47fc686f0f": "gestern {hour}",
"a645030d190791e2": "Bis zu {percent}% deines Wochenlimits",
"d9d3e9b17c602345": "Bis zu {percent}% deines {limit}-Limits",
"72777a9fb1f7f637": "Gesamt",
"cb42b8946f737f0c": "Gesamte Nutzung deines Tarifs in diesem Abrechnungszeitraum.",
"935292957f8578fb": "Cursor-Modelle",
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/src/i18n/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,8 @@
"732708950237004e": "This client is older than the server on {environment}; its usage is excluded from totals.",
"9758c2ede06aa19b": "{hour} today",
"9102fd47fc686f0f": "{hour} yesterday",
"a645030d190791e2": "Up to {percent}% of your weekly limit",
"d9d3e9b17c602345": "Up to {percent}% of your {limit} limit",
"72777a9fb1f7f637": "Overall",
"cb42b8946f737f0c": "All usage on your plan this billing cycle.",
"935292957f8578fb": "Cursor Models",
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/src/i18n/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,8 @@
"732708950237004e": "Este cliente es más antiguo que el servidor de {environment}; su uso se excluye de los totales.",
"9758c2ede06aa19b": "Hoy a las {hour}",
"9102fd47fc686f0f": "Ayer a las {hour}",
"a645030d190791e2": "Hasta el {percent}% de tu límite semanal",
"d9d3e9b17c602345": "Hasta el {percent}% de tu límite {limit}",
"72777a9fb1f7f637": "General",
"cb42b8946f737f0c": "Todo el uso de tu plan en este ciclo de facturación.",
"935292957f8578fb": "Modelos de Cursor",
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/src/i18n/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,8 @@
"732708950237004e": "Ce client est plus ancien que le serveur de {environment} ; son utilisation est exclue des totaux.",
"9758c2ede06aa19b": "{hour} aujourd’hui",
"9102fd47fc686f0f": "{hour} hier",
"a645030d190791e2": "Jusqu’à {percent}% de votre limite hebdomadaire",
"d9d3e9b17c602345": "Jusqu’à {percent}% de votre limite {limit}",
"72777a9fb1f7f637": "Global",
"cb42b8946f737f0c": "Toute l’utilisation de votre forfait sur ce cycle de facturation.",
"935292957f8578fb": "Modèles Cursor",
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/src/i18n/translations/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,8 @@
"732708950237004e": "このクライアントは {environment} のサーバーより古いため、その使用量は合計から除外されています。",
"9758c2ede06aa19b": "今日 {hour}",
"9102fd47fc686f0f": "昨日 {hour}",
"a645030d190791e2": "週間上限の最大{percent}%",
"d9d3e9b17c602345": "{limit}の上限の最大{percent}%",
"72777a9fb1f7f637": "全体",
"cb42b8946f737f0c": "この請求期間におけるプランの全使用量です。",
"935292957f8578fb": "Cursor のモデル",
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/src/i18n/translations/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,8 @@
"732708950237004e": "이 클라이언트가 {environment}의 서버보다 오래되어 해당 사용량은 합계에서 제외됩니다.",
"9758c2ede06aa19b": "오늘 {hour}",
"9102fd47fc686f0f": "어제 {hour}",
"a645030d190791e2": "주간 한도의 최대 {percent}%",
"d9d3e9b17c602345": "{limit} 한도의 최대 {percent}%",
"72777a9fb1f7f637": "전체",
"cb42b8946f737f0c": "이번 결제 주기에 요금제에서 사용한 전체 사용량입니다.",
"935292957f8578fb": "Cursor 모델",
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/src/i18n/translations/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,8 @@
"732708950237004e": "Este cliente é mais antigo que o servidor em {environment}; o uso dele fica fora dos totais.",
"9758c2ede06aa19b": "Hoje às {hour}",
"9102fd47fc686f0f": "Ontem às {hour}",
"a645030d190791e2": "Até {percent}% do seu limite semanal",
"d9d3e9b17c602345": "Até {percent}% do seu limite {limit}",
"72777a9fb1f7f637": "Geral",
"cb42b8946f737f0c": "Todo o uso do seu plano neste ciclo de cobrança.",
"935292957f8578fb": "Modelos do Cursor",
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/src/i18n/translations/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,8 @@
"732708950237004e": "Этот клиент старее сервера на {environment}; его использование не учитывается в итогах.",
"9758c2ede06aa19b": "{hour} сегодня",
"9102fd47fc686f0f": "{hour} вчера",
"a645030d190791e2": "До {percent}% вашего недельного лимита",
"d9d3e9b17c602345": "До {percent}% вашего лимита {limit}",
"72777a9fb1f7f637": "Общий",
"cb42b8946f737f0c": "Всё использование по вашему плану в этом расчётном периоде.",
"935292957f8578fb": "Модели Cursor",
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/src/i18n/translations/sv.json
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,8 @@
"732708950237004e": "Den här klienten är äldre än servern på {environment}; dess användning räknas inte med i totalerna.",
"9758c2ede06aa19b": "{hour} i dag",
"9102fd47fc686f0f": "{hour} i går",
"a645030d190791e2": "Upp till {percent}% av din veckogräns",
"d9d3e9b17c602345": "Upp till {percent}% av din {limit}-gräns",
"72777a9fb1f7f637": "Totalt",
"cb42b8946f737f0c": "All användning i din plan under den här faktureringsperioden.",
"935292957f8578fb": "Cursor-modeller",
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/src/i18n/translations/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,8 @@
"732708950237004e": "此客户端比 {environment} 上的服务器版本旧,其用量未计入总计。",
"9758c2ede06aa19b": "今天 {hour}",
"9102fd47fc686f0f": "昨天 {hour}",
"a645030d190791e2": "最多占每周限额的{percent}%",
"d9d3e9b17c602345": "最多占{limit}限额的{percent}%",
"72777a9fb1f7f637": "总体",
"cb42b8946f737f0c": "本计费周期内套餐的全部用量。",
"935292957f8578fb": "Cursor 模型",
Expand Down
18 changes: 12 additions & 6 deletions apps/server/src/provider/ClaudeProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
type ServerProvider,
type ServerProviderModel,
type ServerProviderSlashCommand,
type ServerProviderResetCredits,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
Expand Down Expand Up @@ -65,6 +64,7 @@ import {
claudeUsageResponseToLimits,
recordClaudeUsageResponse,
} from "./claudeUsageLimits.ts";
import { type ClaudeAccountUsage, withClaudeAccountUsage } from "./claudeResetCredits.ts";
import {
BUNDLED_CLAUDE_MODEL_CATALOG,
CLAUDE_EFFORT_LEVELS,
Expand Down Expand Up @@ -674,7 +674,10 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
/** Shared with the adapter so turn events reuse the scoped-bucket names this probe saw. */
scopedLimitNames?: Ref.Ref<ClaudeScopedLimitNames>,
resolveResetCredits?: (version: string) => Effect.Effect<ServerProviderResetCredits | undefined>,
resolveAccountUsage?: (
version: string,
overageIncluded: string | undefined,
) => Effect.Effect<ClaudeAccountUsage | undefined>,
): Effect.fn.Return<
ServerProviderDraft,
never,
Expand Down Expand Up @@ -879,12 +882,15 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
response: capabilities.usage,
checkedAt: usageCheckedAt,
}).limits;
const resetCredits =
resolveResetCredits &&
const accountUsage =
resolveAccountUsage &&
capabilities.subscriptionType &&
!usageLimits.unavailable &&
parsedVersion
? yield* resolveResetCredits(parsedVersion)
? yield* resolveAccountUsage(
parsedVersion,
scopedLimitNames ? (yield* Ref.get(scopedLimitNames)).overageIncluded : undefined,
)
: undefined;
return buildServerProvider({
presentation: CLAUDE_PRESENTATION,
Expand All @@ -905,7 +911,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
...(authMetadata ? authMetadata : {}),
},
...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}),
usageLimits: resetCredits ? { ...usageLimits, resetCredits } : usageLimits,
usageLimits: withClaudeAccountUsage(usageLimits, accountUsage),
},
});
});
Expand Down
28 changes: 21 additions & 7 deletions apps/server/src/provider/Drivers/ClaudeDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
? configDir
: undefined,
);
const resetCreditsCacheFile = ClaudeResetCredits.claudeResetCreditsCacheFile(
path,
stateDir,
configDir,
);
const stampIdentity = withInstanceIdentity({
instanceId,
driverKind: DRIVER_KIND,
Expand Down Expand Up @@ -284,8 +289,13 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
stateDir,
catalog,
scopedLimitNames,
(version) =>
ClaudeResetCredits.readClaudeResetCredits(configDir, version).pipe(
(version, overageIncluded) =>
ClaudeResetCredits.readClaudeAccountUsage(
configDir,
version,
overageIncluded,
resetCreditsCacheFile,
).pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Expand All @@ -307,6 +317,10 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
Effect.provideService(Path.Path, path),
);

const invalidateUsageCache = Cache.invalidateAll(capabilitiesProbeCache).pipe(
Effect.andThen(ClaudeResetCredits.forgetClaudeResetCredits(resetCreditsCacheFile)),
Effect.provideService(FileSystem.FileSystem, fileSystem),
);
const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({
resolveMaintenance,
Expand All @@ -319,7 +333,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
Effect.map(stampIdentity),
),
checkProvider,
invalidateUsageCache: Cache.invalidateAll(capabilitiesProbeCache),
invalidateUsageCache,
enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
resolveMaintenance().pipe(
Effect.flatMap((maintenanceCapabilities) =>
Expand Down Expand Up @@ -395,13 +409,13 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
cause,
}),
),
// A failed claim may still have spent the reset.
Effect.tapError(() => invalidateUsageCache),
Effect.tap((outcome) =>
ResetCreditCoordinator.refreshAfterRedemption({
outcome,
getSnapshot: snapshot.getSnapshot,
refresh: Cache.invalidateAll(capabilitiesProbeCache).pipe(
Effect.andThen(snapshot.refresh),
),
refresh: invalidateUsageCache.pipe(Effect.andThen(snapshot.refresh)),
}).pipe(
Effect.filterOrFail(
(confirmed) => confirmed,
Expand All @@ -428,7 +442,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
accentColor,
enabled,
snapshot,
invalidateCaches: Cache.invalidateAll(capabilitiesProbeCache),
invalidateCaches: invalidateUsageCache,
workspaceRescans: Stream.fromQueue(workspaceRescans),
snapshotForCwd: (cwd: string) =>
snapshot.getSnapshot.pipe(
Expand Down
Loading
Loading