Skip to content

Commit 53f29b3

Browse files
committed
fix(usage): retain current navigation and React lifecycle rules
1 parent 744c319 commit 53f29b3

10 files changed

Lines changed: 18 additions & 91 deletions

File tree

‎apps/server/src/usage/UsageService.ts‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -769,11 +769,7 @@ export const make = Effect.gen(function* () {
769769

770770
const retentionCutoffMs = startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000;
771771

772-
// Pricing only matters once records are aggregated, so the rate table
773-
// loads while transcripts stream instead of gating them: a cold rates
774-
// fetch on a slow network no longer delays the scan by its own timeout.
775-
// Attribution reads T3's own records. A failure there costs the thread
776-
// breakdown, never the totals.
772+
// Scan while pricing loads; attribution failures lose the breakdown, never totals.
777773
const [, scannedDirs, attributionIndex] = yield* Effect.all(
778774
[
779775
ensureRates(false),

‎apps/server/src/usage/usageAggregation.ts‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -136,13 +136,7 @@ export class UsageAggregator {
136136
}
137137
}
138138

139-
/**
140-
* Folds one record in. Returns whether it actually contributed, so callers
141-
* can derive per-window facts (distinct sessions, for one) from the records
142-
* that landed rather than everything the mtime prefilter happened to admit.
143-
* `group` splits buckets further by account and thread. It is resolved only
144-
* for records inside the window, so out-of-window sessions add no threads.
145-
*/
139+
/** Return whether a record contributed; resolve groups only inside the window so other sessions add no threads. */
146140
add(
147141
input: UsageRecord,
148142
sourcePath?: string,

‎apps/web/src/components/usage/UsageExplorer.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -640,7 +640,7 @@ export function UsageExplorer(props: UsageExplorerProps) {
640640
setTimeout(() => URL.revokeObjectURL(anchor.href), 1000);
641641
};
642642

643-
// "/" jumps to search, Escape clears it.
643+
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- register document keyboard shortcuts while the explorer is mounted
644644
useEffect(() => {
645645
const onKey = (event: KeyboardEvent) => {
646646
if (

‎apps/web/src/components/usage/UsagePage.tsx‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,6 @@ import {
8484
resolveUsageShortcut,
8585
type UsageMetric,
8686
} from "./usageShortcuts";
87-
import { useEscapeToGoBack } from "../../hooks/useNavigateBack";
8887
import { PROVIDER_ORDER, PROVIDER_PRESENTATION } from "./usageProviders";
8988
import {
9089
readUsageExplorerPreferences,
@@ -154,7 +153,6 @@ function UsageModelDialogHost({
154153
export function UsagePage() {
155154
const [preferences, setPreferences] = useState(readUsagePagePreferences);
156155
const [explorerPreferences, setExplorerPreferences] = useState(readUsageExplorerPreferences);
157-
useEscapeToGoBack();
158156
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
159157
const hour12 = usePrimarySettings((settings) => resolveHour12(settings.timestampFormat));
160158
const shortcutTitle = (
@@ -182,11 +180,8 @@ export function UsagePage() {
182180
useState<ReadonlySet<EnvironmentId> | null>(null);
183181
const { range, window: requested } = windowSelection;
184182
const periodDays = range.kind === "period" ? range.days : null;
185-
// Servers from before week-long hourly reads answer such a span only by day.
186-
// Once one does, every environment reads it by day, so totals, the range and
187-
// the comparison window all cover the same whole days.
188-
// The environments that needed days are remembered per range, so the page
189-
// goes back to hours as soon as none of them is selected.
183+
// Older servers require day buckets for long ranges; all selected environments
184+
// must use the same granularity, returning to hours when those servers leave.
190185
const [daysNeeded, setDaysNeeded] = useState<{
191186
readonly for: UsageSummaryInput;
192187
readonly ids: ReadonlySet<EnvironmentId>;
@@ -757,12 +752,13 @@ function UsageRangePicker({
757752
readonly onChange: (sinceDay: string, untilDay: string) => void;
758753
readonly compact?: boolean;
759754
}) {
755+
const [now, setNow] = useState(() => Date.now());
760756
const today = new Intl.DateTimeFormat("en-CA", {
761757
timeZone: window.timeZone,
762758
year: "numeric",
763759
month: "2-digit",
764760
day: "2-digit",
765-
}).format(new Date());
761+
}).format(new Date(now));
766762
const [open, setOpen] = useState(false);
767763
const [since, setSince] = useState<string>(window.sinceDay);
768764
const [until, setUntil] = useState<string>(window.untilDay);
@@ -773,6 +769,7 @@ function UsageRangePicker({
773769
onOpenChange={(next) => {
774770
setOpen(next);
775771
if (!next) return;
772+
setNow(Date.now());
776773
setSince(window.sinceDay);
777774
setUntil(window.untilDay);
778775
}}

‎apps/web/src/components/usage/UsageStackedChart.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,7 @@ export function UsageStackedChart({
217217
);
218218
};
219219

220+
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- position the measured tooltip after its hover contents render
220221
useLayoutEffect(() => {
221222
if (hoverIndex !== null) positionTooltip();
222223
}, [hoverIndex, positionTooltip]);

‎apps/web/src/components/usage/usageBreakdown.ts‎

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,6 @@ import {
88

99
import type { ShareSegment } from "./UsageShareBar";
1010

11-
export function sortModelsByTokens(models: readonly ModelTotals[]) {
12-
return models.toSorted(
13-
(left, right) => right.totalTokens - left.totalTokens || right.costUsd - left.costUsd,
14-
);
15-
}
16-
17-
/** Unknown cost yields null cost share; unpriced models still have token shares. */
18-
export function modelShare(model: ModelTotals, metric: "cost" | "tokens"): number | null {
19-
if (metric === "tokens") return model.tokenShare;
20-
return isModelCostUnknown(model) ? null : model.costShare;
21-
}
22-
2311
/** Returns null without input; cache writes count as misses because input was fully processed. */
2412
export function cacheHitRate({ tokens }: ModelTotals): number | null {
2513
const input = tokens.uncachedInputTokens + tokens.cachedInputTokens + tokens.cacheCreationTokens;

‎apps/web/src/state/usage.ts‎

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -238,14 +238,7 @@ export interface UsageView {
238238
readonly refresh: (input?: UsageSummaryInput) => Promise<void>;
239239
}
240240

241-
/**
242-
* Merges every environment that has answered, or that is offline and has
243-
* saved usage. Saved reads are trimmed so each history folder is counted from
244-
* one place, a usable live read first. `keepBucket` narrows the merge,
245-
* for example to one model; source ownership still applies, so the result
246-
* matches that slice of the full merge. Session counts are per directory and
247-
* are not narrowed.
248-
*/
241+
/** Claim live and offline history folders before filtering buckets, so slices match full totals. */
249242
export function mergeAnsweredUsage(
250243
environments: readonly EnvironmentUsageStatus[],
251244
keepBucket?: (bucket: UsageBucket) => boolean,
@@ -422,7 +415,7 @@ export function useUsage(
422415
});
423416
};
424417

425-
// Keep each live read, so an environment's usage still shows while it is offline.
418+
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- persist completed live summaries to offline usage storage
426419
useEffect(() => {
427420
for (const status of environments) {
428421
if (status.offline || status.isPending || status.summary === null) continue;

‎packages/contracts/src/usage.ts‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,4 @@
1-
/**
2-
* Usage reporting contract.
3-
*
4-
* Each environment scans native session files and databases, including work
5-
* driven outside T3 Code. Source status describes gaps in local coverage.
6-
*
7-
* Environments return pre-aggregated `(day, hourStart?, provider, model, sourcePath?)`
8-
* buckets. Raw transcript records never cross the wire. A summary read with
9-
* `groupByThread` also splits buckets by provider account and thread, and lists
10-
* those threads with their projects.
11-
*
1+
/** Aggregated native usage crosses the wire; raw transcript records stay in the environment.
122
* @module usage
133
*/
144
import * as Schema from "effect/Schema";

‎packages/provider-core/src/server/usage.ts‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -73,16 +73,8 @@ export interface TranscriptUsageFormat<State> {
7373
};
7474
/** Enable cross-file deduplication when session records can appear in multiple files. */
7575
readonly sharedSessionsAcrossFiles?: true;
76-
/**
77-
* Present for formats whose transcripts name the working directory their
78-
* session ran in. The server places usage run outside T3 Code in the project
79-
* at that folder.
80-
*
81-
* The engine reads a file's lines that contain one of `markers` until one
82-
* names the folder, and keeps that first answer, so lines that only name the
83-
* folder need not match `usageMarkers`. A line too large to parse whole is
84-
* projected to `selectFields`, which must keep the fields `fromProjected`
85-
* reads.
76+
/** Capture the first session folder, including folder-only lines.
77+
* Projected reads must retain the fields consumed by fromProjected.
8678
*/
8779
readonly workingDirectory?: {
8880
readonly markers: readonly [string, ...string[]];

‎packages/shared/src/usageMerge.ts‎

Lines changed: 4 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -207,23 +207,8 @@ function recordsInT3Threads(summary: UsageSummary, source: UsageSource): number
207207
return records;
208208
}
209209

210-
/**
211-
* Decides which environment owns each physical transcript directory.
212-
*
213-
* Several environments on one machine (worktree servers, for instance) resolve
214-
* the same provider home and would otherwise double count every token.
215-
* Complete scans claim a fingerprint ahead of partial scans. Within a status,
216-
* a server that splits usage by thread wins over one that cannot, then the
217-
* environment that ran most of the directory's work in its own T3 threads,
218-
* so threads and projects keep their usage and the owner does not change
219-
* between refreshes; then the most recently read scan, then the environment
220-
* id. Attribution only decides among scans read within
221-
* {@link ATTRIBUTION_MAX_AGE_MS} of the newest, so an older owner misses at
222-
* most the usage recorded in between, which the next refresh shows. A newer
223-
* partial scan can still contribute cells absent from an older complete scan.
224-
*
225-
* Ownership is decided on whole summaries, so narrowing the buckets
226-
* afterwards (to one model, say) keeps the same owners as the full merge.
210+
/** Claim shared physical folders once; prefer complete, attributed scans within the freshness bound.
211+
* Claim whole summaries before narrowing buckets so slices retain the full merge's owners.
227212
*/
228213
function claimSources(environments: readonly EnvironmentUsage[]): {
229214
readonly ownerByFingerprint: ReadonlyMap<string, EnvironmentId>;
@@ -417,17 +402,8 @@ const EMPTY_MERGED: MergedUsage = {
417402
contributions: [],
418403
};
419404

420-
/**
421-
* Merges every connected environment's summary.
422-
*
423-
* `expectedContractVersion` guards against incompatible server code: rather
424-
* than blocking the page, its data is excluded and the mismatch direction is
425-
* reported so the UI can identify which side needs updating. Versions in
426-
* [{@link USAGE_MERGE_COMPATIBLE_SINCE}, expected] still merge, so an additive
427-
* provider expansion does not drop Claude/Codex totals from older servers.
428-
*
429-
* `keepBucket` narrows the result, to one model for instance, after sources
430-
* are claimed, so the slice matches the same part of the full merge.
405+
/** Exclude incompatible contracts while merging additive provider versions.
406+
* Filter buckets only after folder ownership is decided, so slices match the full merge.
431407
*/
432408
export function mergeUsage(
433409
environments: readonly EnvironmentUsage[],

0 commit comments

Comments
 (0)