Skip to content

Commit 95faf3a

Browse files
bmdavis419claude
andcommitted
perf(usage): the usage page loads in a fraction of a second and dims only what is still updating
The usage page waited on every source before showing anything. Cursor's account API alone took 19-32s, and the loading state dimmed the whole page, so it was hard to tell what was stale. Server: - Fetch Cursor account pages concurrently after the first page. - Cache Cursor account records per credential and refresh only the newest edge. Answer from the cache with the source marked `refreshing`; a request with `awaitRefresh` waits for the fresh records. - Scan transcript, OpenCode, Antigravity and Cursor sources concurrently and persist the scan cache after responding. Client: - The usage query shows the cached answer, then sends one `awaitRefresh` follow-up when a source is refreshing. - A shared helper reports which providers are still loading. Web mutes only those figures, keeps the previous window on screen while a new one loads, and animates chart lines between states; loading lines sit flat and rise into place. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 06e6274 commit 95faf3a

20 files changed

Lines changed: 2623 additions & 582 deletions

‎apps/mobile/src/features/usage/UsageRouteScreen.tsx‎

Lines changed: 113 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,18 @@
11
import { ChatGptUsageSummary } from "./ChatGptUsageSummary";
22
import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";
3-
import { EnvironmentId, USAGE_CONTRACT_VERSION } from "@t3tools/contracts";
3+
import {
4+
EnvironmentId,
5+
USAGE_CONTRACT_VERSION,
6+
type UsageProviderKind,
7+
type UsageSummary,
8+
} from "@t3tools/contracts";
49
import { type RouteProp, useIsFocused, useNavigation, useRoute } from "@react-navigation/native";
510
import { cursorKeychainAccessEnvironments } from "@t3tools/client-runtime/state/usage";
11+
import {
12+
updatingProvidersLabel,
13+
usageEnvironmentProgress,
14+
usageProgress,
15+
} from "@t3tools/client-runtime/state/usage-progress";
616
import {
717
isCompatibleUsageContractVersion,
818
isModelCostUnknown,
@@ -21,9 +31,16 @@ import {
2131
formatUsd,
2232
makeWindow,
2333
} from "@t3tools/shared/usageFormat";
24-
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
25-
import { Platform, Pressable, RefreshControl, View } from "react-native";
26-
import Animated, { FadeIn, ReduceMotion } from "react-native-reanimated";
34+
import { useCallback, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
35+
import { ActivityIndicator, Platform, Pressable, RefreshControl, View } from "react-native";
36+
import Animated, {
37+
FadeIn,
38+
ReduceMotion,
39+
useAnimatedStyle,
40+
useSharedValue,
41+
withDelay,
42+
withTiming,
43+
} from "react-native-reanimated";
2744
import { useSafeAreaInsets } from "react-native-safe-area-context";
2845

2946
import { SegmentedControl } from "../../components/SegmentedControl";
@@ -65,6 +82,7 @@ const METRIC_OPTIONS = [
6582
] as const satisfies readonly { value: UsageChartMetric; label: string }[];
6683

6784
const CHART_HEIGHT = 180;
85+
const providerLabel = (provider: UsageProviderKind) => PROVIDER_LABEL[provider];
6886
const CURSOR_KEYCHAIN_COPY = "Requires access to your Cursor login in macOS Keychain.";
6987

7088
/**
@@ -150,9 +168,11 @@ export function UsageRouteScreen() {
150168
[isPast24Hours, merged.daily, merged.hourly],
151169
);
152170

153-
const [refreshingUsage, setRefreshingUsage] = useState(false);
171+
// Summaries on screen when a pull to refresh began.
172+
const [refreshingFrom, setRefreshingFrom] = useState<ReadonlySet<UsageSummary> | null>(null);
154173
const refreshingRef = useRef(false);
155174
const showingLimits = tab === "limits";
175+
const progress = usageProgress(selectedEnvironments, { refreshingFrom, providerLabel });
156176
const selectWindow = (days: number) => {
157177
setWindowSelection({
158178
days,
@@ -171,18 +191,16 @@ export function UsageRouteScreen() {
171191
setWindowSelection({ days: windowDays, window: nextWindow });
172192
}
173193
refreshingRef.current = true;
174-
setRefreshingUsage(true);
194+
setRefreshingFrom(
195+
new Set(selectedEnvironments.flatMap(({ summary }) => (summary === null ? [] : [summary]))),
196+
);
175197
void refresh(nextWindow).finally(() => {
176198
refreshingRef.current = false;
177-
setRefreshingUsage(false);
199+
setRefreshingFrom(null);
178200
});
179201
};
180202

181203
const showEnvironmentFilter = environments.length > 0 || selectedEnvironmentIds !== null;
182-
const hasLoadingEnvironments = selectedEnvironments.some(isUsageLoading);
183-
const filterAccessibilityLabel = hasLoadingEnvironments
184-
? "Filter usage environments, some environments are loading"
185-
: "Filter usage environments";
186204
const filterIcon =
187205
selectedEnvironmentIds === null
188206
? "line.3.horizontal.decrease"
@@ -198,14 +216,14 @@ export function UsageRouteScreen() {
198216
...environments.map((environment) => ({
199217
id: environment.environmentId,
200218
title: environment.label,
201-
subtitle: usageEnvironmentStatus(environment),
219+
subtitle: usageEnvironmentStatus(environment, refreshingFrom),
202220
state:
203221
selectedEnvironmentIds === null || selectedEnvironmentIds.has(environment.environmentId)
204222
? ("on" as const)
205223
: ("off" as const),
206224
})),
207225
],
208-
[environments, selectedEnvironmentIds],
226+
[environments, refreshingFrom, selectedEnvironmentIds],
209227
);
210228
const selectEnvironment = useCallback(
211229
(value: string) => {
@@ -224,37 +242,24 @@ export function UsageRouteScreen() {
224242
<ControlPillMenu
225243
accessible
226244
accessibilityRole="button"
227-
accessibilityLabel={filterAccessibilityLabel}
245+
accessibilityLabel="Filter usage environments"
228246
title="Environments"
229247
actions={environmentActions}
230248
onPressAction={({ nativeEvent }) => selectEnvironment(nativeEvent.event)}
231249
>
232250
<Pressable
233251
accessibilityRole="button"
234-
accessibilityLabel={filterAccessibilityLabel}
252+
accessibilityLabel="Filter usage environments"
235253
className={cn(
236254
"items-center justify-center rounded-full",
237255
Platform.OS === "ios" ? "size-[28px]" : "size-[44px]",
238256
)}
239257
>
240258
<SymbolView name={filterIcon} size={22} tintColorClassName="accent-icon" />
241-
{hasLoadingEnvironments ? (
242-
<View
243-
pointerEvents="none"
244-
className="absolute -right-[2px] -top-[2px] size-[9px] rounded-full bg-amber-500"
245-
/>
246-
) : null}
247259
</Pressable>
248260
</ControlPillMenu>
249261
) : null,
250-
[
251-
showEnvironmentFilter,
252-
environmentActions,
253-
selectEnvironment,
254-
filterAccessibilityLabel,
255-
filterIcon,
256-
hasLoadingEnvironments,
257-
],
262+
[showEnvironmentFilter, environmentActions, selectEnvironment, filterIcon],
258263
);
259264

260265
useLayoutEffect(() => {
@@ -273,7 +278,7 @@ export function UsageRouteScreen() {
273278
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
274279
refreshControl={
275280
<RefreshControl
276-
refreshing={showingLimits ? limits.refreshing : refreshingUsage}
281+
refreshing={showingLimits ? limits.refreshing : refreshingFrom !== null}
277282
onRefresh={showingLimits ? () => void limits.refresh() : refreshWindow}
278283
/>
279284
}
@@ -342,26 +347,28 @@ export function UsageRouteScreen() {
342347
{message}
343348
</Text>
344349
))}
345-
<ChartCard
346-
merged={merged}
347-
days={chartDays}
348-
daily={chartTotals}
349-
metric={metric}
350-
sinceDay={window.sinceDay}
351-
untilDay={window.untilDay}
352-
isPast24Hours={isPast24Hours}
353-
timeZone={window.timeZone}
354-
/>
355-
<ProviderSection
356-
merged={merged}
357-
metric={metric}
358-
cursorAccessEnvironments={cursorAccessEnvironments}
359-
showCursorEnvironment={selectedEnvironments.length > 1}
360-
onCursorEnabled={refreshAfterCursorEnable}
361-
/>
362-
<TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
363-
<CostSection merged={merged} />
364-
<ModelsSection merged={merged} metric={metric} />
350+
<UsageUpdating dimmed={progress.dimmed} label={progress.label}>
351+
<ChartCard
352+
merged={merged}
353+
days={chartDays}
354+
daily={chartTotals}
355+
metric={metric}
356+
sinceDay={window.sinceDay}
357+
untilDay={window.untilDay}
358+
isPast24Hours={isPast24Hours}
359+
timeZone={window.timeZone}
360+
/>
361+
<ProviderSection
362+
merged={merged}
363+
metric={metric}
364+
cursorAccessEnvironments={cursorAccessEnvironments}
365+
showCursorEnvironment={selectedEnvironments.length > 1}
366+
onCursorEnabled={refreshAfterCursorEnable}
367+
/>
368+
<TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
369+
<CostSection merged={merged} />
370+
<ModelsSection merged={merged} metric={metric} />
371+
</UsageUpdating>
365372
</>
366373
)}
367374
</>
@@ -372,6 +379,53 @@ export function UsageRouteScreen() {
372379
);
373380
}
374381

382+
/**
383+
* Dims totals that are about to change and says what is still updating. The
384+
* status overlays the first child's top-right corner, the chart card's label
385+
* row, so appearing never moves anything.
386+
*/
387+
function UsageUpdating({
388+
dimmed,
389+
label,
390+
children,
391+
}: {
392+
readonly dimmed: boolean;
393+
readonly label: string | null;
394+
readonly children: ReactNode;
395+
}) {
396+
const opacity = useSharedValue(1);
397+
useLayoutEffect(() => {
398+
// The delay keeps a quick cached answer from flashing the dim.
399+
opacity.set(
400+
dimmed
401+
? withDelay(150, withTiming(0.5, { duration: 150, reduceMotion: ReduceMotion.System }))
402+
: withTiming(1, { duration: 150, reduceMotion: ReduceMotion.System }),
403+
);
404+
}, [opacity, dimmed]);
405+
const dimStyle = useAnimatedStyle(() => ({ opacity: opacity.get() }));
406+
407+
return (
408+
<View>
409+
<Animated.View style={dimStyle} className="gap-6" accessibilityState={{ busy: dimmed }}>
410+
{children}
411+
</Animated.View>
412+
{label !== null ? (
413+
<Animated.View
414+
entering={FadeIn.delay(150).duration(150).reduceMotion(ReduceMotion.System)}
415+
accessibilityLiveRegion="polite"
416+
pointerEvents="none"
417+
className="absolute right-4 top-4 h-5 max-w-[55%] flex-row items-center gap-1.5"
418+
>
419+
<ActivityIndicator size="small" colorClassName="accent-adaptive-sky-600-400" />
420+
<Text className="shrink text-sm text-adaptive-sky-600-400" numberOfLines={1}>
421+
{label}
422+
</Text>
423+
</Animated.View>
424+
) : null}
425+
</View>
426+
);
427+
}
428+
375429
function CursorEnableAction({
376430
environmentId,
377431
label,
@@ -841,11 +895,10 @@ function ModelsSection(props: { readonly merged: MergedUsage; readonly metric: U
841895
* one that failed, or one whose transcripts another environment already
842896
* reported.
843897
*/
844-
function isUsageLoading(environment: EnvironmentUsageStatus) {
845-
return environment.isPending || (environment.summary === null && environment.error === null);
846-
}
847-
848-
function usageEnvironmentStatus(environment: EnvironmentUsageStatus): string {
898+
function usageEnvironmentStatus(
899+
environment: EnvironmentUsageStatus,
900+
refreshingFrom: ReadonlySet<UsageSummary> | null,
901+
): string {
849902
if (
850903
environment.summary &&
851904
!isCompatibleUsageContractVersion(environment.summary.contractVersion, USAGE_CONTRACT_VERSION)
@@ -861,7 +914,10 @@ function usageEnvironmentStatus(environment: EnvironmentUsageStatus): string {
861914
return environment.summary ? "Disconnected · showing saved usage" : "Waiting for connection…";
862915
if (environment.error)
863916
return environment.summary ? "Usage unavailable · showing saved totals" : "Usage unavailable";
864-
if (isUsageLoading(environment))
865-
return environment.summary ? "Updating usage…" : "Loading usage…";
917+
const progress = usageEnvironmentProgress(environment, refreshingFrom);
918+
if (progress.phase === "loading") return "Loading usage…";
919+
if (progress.phase === "stale") return "Updating usage…";
920+
if (progress.phase === "partway")
921+
return updatingProvidersLabel(progress.providers, providerLabel);
866922
return "Usage up to date";
867923
}

0 commit comments

Comments
 (0)