diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsx index 48215804ee2dc..42edd82c1fa51 100644 --- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx +++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx @@ -1,7 +1,12 @@ import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; import { ChatGptUsageSummary } from "./ChatGptUsageSummary"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; -import { EnvironmentId, USAGE_CONTRACT_VERSION, type UsageProviderKind } from "@t3tools/contracts"; +import { + EnvironmentId, + USAGE_CONTRACT_VERSION, + type UsageProviderKind, + type UsageSummaryInput, +} from "@t3tools/contracts"; import { type RouteProp, useIsFocused, useRoute } from "@react-navigation/native"; import { updatingProvidersLabel, @@ -18,11 +23,18 @@ import { enumerateDays, enumerateHourStarts, formatCount, + formatDayRange, formatPercent, formatTokens, + formatUsageMonth, formatUsd, - makeWindow, + makePeriodWindow, + parseUsagePeriod, + selectableUsageMonths, + type UsageMonthKey, + type UsagePeriod, } from "@t3tools/shared/usageFormat"; +import type { MenuAction } from "@react-native-menu/menu"; import { formatUsageContractMismatch, usageSourceMessages } from "@t3tools/shared/usageFormatCopy"; import { msg, T, useGT, useLocale, useMessages, Var } from "gt-react-native"; import { use, useRef, useState, type ReactNode } from "react"; @@ -32,6 +44,8 @@ import Animated, { FadeIn, ReduceMotion } from "react-native-reanimated"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { SegmentedControl } from "../../components/ui/SegmentedControl"; +import { ControlPill } from "../../components/ui/ControlPill"; +import { Menu } from "../../components/ui/Menu"; import { useReduceMotionEnabled } from "../../lib/appState"; import { AppText as Text } from "../../components/ui/AppText"; import { useWorkspaceSettledContentWidth } from "../layout/workspace-content-width"; @@ -77,6 +91,11 @@ const WINDOW_OPTIONS = [ label: msg("90d", { $context: "short label for the past 90 days" }), accessibilityLabel: msg("Past 90 days"), }, + { + value: "month", + label: msg("Month", { $context: "short label for the current calendar month" }), + accessibilityLabel: msg("This month"), + }, ] as const; const CHART_HEIGHT = 180; @@ -121,12 +140,13 @@ function UsageScreen(props: { // A workspace pane knows its width in the render that resizes it; measuring lags a frame. const width = useWorkspaceSettledContentWidth() ?? measuredWidth; const wide = width >= WIDE_WIDTH; - const [windowSelection, setWindowSelection] = useState(() => ({ - days: 30, - window: makeWindow(30), - })); - const { days: windowDays, window } = windowSelection; - const isPast24Hours = windowDays === 1; + const [windowSelection, setWindowSelection] = useState<{ + readonly period: UsagePeriod; + readonly window: UsageSummaryInput; + }>(() => ({ period: 30, window: makePeriodWindow(30) })); + const { period, window } = windowSelection; + const isPast24Hours = period === 1; + const isMonthPeriod = typeof period === "string"; const [selectedEnvironmentIds, setSelectedEnvironmentIds] = useState | null>(null); const { merged, environments, selectedEnvironments, isPending, refresh } = useUsage( @@ -173,22 +193,19 @@ function UsageScreen(props: { }, m, ); - const selectWindow = (days: number) => { - setWindowSelection({ - days, - window: makeWindow(days, undefined, days === 1 ? "hour" : "day"), - }); + const selectPeriod = (period: UsagePeriod) => { + setWindowSelection({ period, window: makePeriodWindow(period) }); }; const refreshWindow = () => { if (refreshingRef.current) return; - const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day"); + const nextWindow = makePeriodWindow(period); if ( nextWindow.sinceDay !== window.sinceDay || nextWindow.untilDay !== window.untilDay || nextWindow.sinceTime !== window.sinceTime || nextWindow.untilTime !== window.untilTime ) { - setWindowSelection({ days: windowDays, window: nextWindow }); + setWindowSelection({ period, window: nextWindow }); } refreshingRef.current = true; setRefreshingUsage(true); @@ -209,6 +226,15 @@ function UsageScreen(props: { timeZone: window.timeZone, }; const providers = ; + const monthPicker = + isMonthPeriod && !showingLimits ? ( + + ) : null; const showEnvironmentFilter = environments.length > 0 || selectedEnvironmentIds !== null; const selectEnvironment = (value: string) => { @@ -274,8 +300,8 @@ function UsageScreen(props: { ) : ( @@ -297,6 +323,7 @@ function UsageScreen(props: { role="tab" /> )} + {wide ? monthPicker : null} )} + {monthPicker} {merged.duplicateSources.length > 0 ? ( @@ -409,6 +437,59 @@ function UsageScreen(props: { ); } +function UsageMonthPicker(props: { + readonly period: "month" | UsageMonthKey; + readonly sinceDay: string; + readonly untilDay: string; + readonly onSelect: (period: UsagePeriod) => void; +}) { + const gt = useGT(); + const locale = useLocale(); + const monthKeys = selectableUsageMonths(); + const thisMonth = gt("This month"); + const chooseMonth = gt("Choose month"); + const actions: MenuAction[] = [ + { id: "month", title: thisMonth, state: props.period === "month" ? "on" : "off" }, + ...monthKeys.slice(1).map((key): MenuAction => ({ + id: key, + title: formatUsageMonth(key, true, locale), + state: props.period === key ? "on" : "off", + })), + ]; + return ( + + { + const next = parseUsagePeriod(nativeEvent.event); + if (next !== undefined) props.onSelect(next); + }} + > + + + + {formatDayRange(props.sinceDay, props.untilDay, locale)} + + + ); +} + function UsageUpdating({ dimmed, label, diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index f538b87920412..836ec5fe8508f 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -5102,6 +5102,8 @@ "84f6aa2f92bf1add": "Letzte 30 Tage", "1fffffb1a1de7b75": "90 T.", "e28a99495d050460": "Letzte 90 Tage", + "db8d9d8e534e8258": "Monat", + "c869d7fd448a43fe": "Dieser Monat", "702984447f7f2c3e": "{error} Gespeicherte Summen werden angezeigt.", "c21b18e2a3459148": "Getrennt · gespeicherte Nutzung wird angezeigt", "e5181944df63a9e9": "Warte auf Verbindung…", @@ -5116,6 +5118,7 @@ "ae86762909d453d2": "Verarbeitete Tokens pro Stunde", "66ab3e4edb2b4fe7": "Kosten pro Tag", "08f867ac9eaa7508": "Verarbeitete Tokens pro Tag", + "fbd6302e898c1449": "Monat auswählen", "0b363b02a7e17bcb": "Rohe Token-Kosten", "ea4beda46b22b8b0": "Verarbeitete Tokens", "212d974007cacf3f": "* bei Abrechnung zum vollen API-Preis", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 745201ad99094..3619c5e544f23 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -5104,6 +5104,8 @@ "84f6aa2f92bf1add": "Past 30 days", "1fffffb1a1de7b75": "90d", "e28a99495d050460": "Past 90 days", + "db8d9d8e534e8258": "Month", + "c869d7fd448a43fe": "This month", "702984447f7f2c3e": "{error} Showing saved totals.", "c21b18e2a3459148": "Disconnected · showing saved usage", "e5181944df63a9e9": "Waiting for connection…", @@ -5118,6 +5120,7 @@ "ae86762909d453d2": "Hourly processed tokens", "66ab3e4edb2b4fe7": "Daily cost", "08f867ac9eaa7508": "Daily processed tokens", + "fbd6302e898c1449": "Choose month", "0b363b02a7e17bcb": "Raw token cost", "ea4beda46b22b8b0": "Processed tokens", "212d974007cacf3f": "* if billed at full API rate", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index fb134339cd3c4..e1bd6f36b86ab 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -5096,6 +5096,8 @@ "84f6aa2f92bf1add": "Últimos 30 días", "1fffffb1a1de7b75": "90 d", "e28a99495d050460": "Últimos 90 días", + "db8d9d8e534e8258": "Mes", + "c869d7fd448a43fe": "Este mes", "702984447f7f2c3e": "{error} Se muestran los totales guardados.", "c21b18e2a3459148": "Desconectado · se muestra el uso guardado", "e5181944df63a9e9": "Esperando la conexión…", @@ -5110,6 +5112,7 @@ "ae86762909d453d2": "Tokens procesados por hora", "66ab3e4edb2b4fe7": "Coste por día", "08f867ac9eaa7508": "Tokens procesados por día", + "fbd6302e898c1449": "Elegir mes", "0b363b02a7e17bcb": "Coste bruto de tokens", "ea4beda46b22b8b0": "Tokens procesados", "212d974007cacf3f": "* si se facturara a la tarifa completa de la API", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index d6aef220df3a2..b1f52cf624f9e 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -5096,6 +5096,8 @@ "84f6aa2f92bf1add": "30 derniers jours", "1fffffb1a1de7b75": "90 j", "e28a99495d050460": "90 derniers jours", + "db8d9d8e534e8258": "Mois", + "c869d7fd448a43fe": "Ce mois-ci", "702984447f7f2c3e": "{error} Affichage des totaux enregistrés.", "c21b18e2a3459148": "Déconnecté · utilisation enregistrée affichée", "e5181944df63a9e9": "En attente de connexion…", @@ -5110,6 +5112,7 @@ "ae86762909d453d2": "Tokens traités par heure", "66ab3e4edb2b4fe7": "Coût par jour", "08f867ac9eaa7508": "Tokens traités par jour", + "fbd6302e898c1449": "Choisir un mois", "0b363b02a7e17bcb": "Coût brut des tokens", "ea4beda46b22b8b0": "Tokens traités", "212d974007cacf3f": "* si facturé au tarif API complet", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 8cd9fba5c8332..c8376adf41b04 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -5077,6 +5077,8 @@ "84f6aa2f92bf1add": "過去 30 日間", "1fffffb1a1de7b75": "90 日", "e28a99495d050460": "過去 90 日間", + "db8d9d8e534e8258": "月", + "c869d7fd448a43fe": "今月", "702984447f7f2c3e": "{error} 保存済みの合計を表示しています。", "c21b18e2a3459148": "切断中 · 保存済みの使用量を表示", "e5181944df63a9e9": "接続を待っています…", @@ -5091,6 +5093,7 @@ "ae86762909d453d2": "1 時間ごとの処理トークン", "66ab3e4edb2b4fe7": "1 日ごとのコスト", "08f867ac9eaa7508": "1 日ごとの処理トークン", + "fbd6302e898c1449": "月を選択", "0b363b02a7e17bcb": "トークンの素のコスト", "ea4beda46b22b8b0": "処理トークン", "212d974007cacf3f": "* API の正規料金で請求された場合", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 731eaeecaec22..896c891b07a1f 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -5081,6 +5081,8 @@ "84f6aa2f92bf1add": "지난 30일", "1fffffb1a1de7b75": "90일", "e28a99495d050460": "지난 90일", + "db8d9d8e534e8258": "월", + "c869d7fd448a43fe": "이번 달", "702984447f7f2c3e": "{error} 저장된 합계를 표시합니다.", "c21b18e2a3459148": "연결 끊김 · 저장된 사용량 표시 중", "e5181944df63a9e9": "연결 대기 중…", @@ -5095,6 +5097,7 @@ "ae86762909d453d2": "시간별 처리 토큰", "66ab3e4edb2b4fe7": "일별 비용", "08f867ac9eaa7508": "일별 처리 토큰", + "fbd6302e898c1449": "월 선택", "0b363b02a7e17bcb": "원시 토큰 비용", "ea4beda46b22b8b0": "처리된 토큰", "212d974007cacf3f": "* 전체 API 요율로 청구되는 경우", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 2c4ee1bc64fc4..2747d508761b9 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -5096,6 +5096,8 @@ "84f6aa2f92bf1add": "Últimos 30 dias", "1fffffb1a1de7b75": "90 d", "e28a99495d050460": "Últimos 90 dias", + "db8d9d8e534e8258": "Mês", + "c869d7fd448a43fe": "Este mês", "702984447f7f2c3e": "{error} Mostrando os totais salvos.", "c21b18e2a3459148": "Desconectado · mostrando o uso salvo", "e5181944df63a9e9": "Aguardando conexão…", @@ -5110,6 +5112,7 @@ "ae86762909d453d2": "Tokens processados por hora", "66ab3e4edb2b4fe7": "Custo por dia", "08f867ac9eaa7508": "Tokens processados por dia", + "fbd6302e898c1449": "Escolher mês", "0b363b02a7e17bcb": "Custo bruto de tokens", "ea4beda46b22b8b0": "Tokens processados", "212d974007cacf3f": "* se cobrado pela taxa cheia da API", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index c4f78e560083b..db354600e33c2 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -5175,6 +5175,8 @@ "84f6aa2f92bf1add": "За 30 дней", "1fffffb1a1de7b75": "90 д", "e28a99495d050460": "За 90 дней", + "db8d9d8e534e8258": "Месяц", + "c869d7fd448a43fe": "Этот месяц", "702984447f7f2c3e": "{error} Показаны сохранённые итоги.", "c21b18e2a3459148": "Отключено · показано сохранённое использование", "e5181944df63a9e9": "Ожидание подключения…", @@ -5189,6 +5191,7 @@ "ae86762909d453d2": "Обработанные токены по часам", "66ab3e4edb2b4fe7": "Стоимость по дням", "08f867ac9eaa7508": "Обработанные токены по дням", + "fbd6302e898c1449": "Выбрать месяц", "0b363b02a7e17bcb": "Стоимость токенов без скидок", "ea4beda46b22b8b0": "Обработанные токены", "212d974007cacf3f": "* при оплате по полной цене API", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index fa3a3dd6d039f..84558eb4459c4 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -5102,6 +5102,8 @@ "84f6aa2f92bf1add": "Senaste 30 dagarna", "1fffffb1a1de7b75": "90 d", "e28a99495d050460": "Senaste 90 dagarna", + "db8d9d8e534e8258": "Månad", + "c869d7fd448a43fe": "Den här månaden", "702984447f7f2c3e": "{error} Visar sparade summor.", "c21b18e2a3459148": "Frånkopplad · visar sparad användning", "e5181944df63a9e9": "Väntar på anslutning…", @@ -5116,6 +5118,7 @@ "ae86762909d453d2": "Bearbetade token per timme", "66ab3e4edb2b4fe7": "Kostnad per dag", "08f867ac9eaa7508": "Bearbetade token per dag", + "fbd6302e898c1449": "Välj månad", "0b363b02a7e17bcb": "Rå tokenkostnad", "ea4beda46b22b8b0": "Bearbetade token", "212d974007cacf3f": "* om det debiterades till fullt API-pris", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index f36e76805c298..4945fd6927d51 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -5086,6 +5086,8 @@ "84f6aa2f92bf1add": "过去 30 天", "1fffffb1a1de7b75": "90 天", "e28a99495d050460": "过去 90 天", + "db8d9d8e534e8258": "月", + "c869d7fd448a43fe": "本月", "702984447f7f2c3e": "{error} 正在显示已保存的总计。", "c21b18e2a3459148": "已断开连接 · 正在显示已保存的用量", "e5181944df63a9e9": "正在等待连接…", @@ -5100,6 +5102,7 @@ "ae86762909d453d2": "每小时处理的 token", "66ab3e4edb2b4fe7": "每天费用", "08f867ac9eaa7508": "每天处理的 token", + "fbd6302e898c1449": "选择月份", "0b363b02a7e17bcb": "原始 token 费用", "ea4beda46b22b8b0": "处理的 token", "212d974007cacf3f": "* 按完整 API 费率计费时", diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx index adb05afb92ebb..cdbaaaf2d8af1 100644 --- a/apps/web/src/components/usage/UsagePage.tsx +++ b/apps/web/src/components/usage/UsagePage.tsx @@ -46,12 +46,17 @@ import { enumerateHourStarts, formatCount, formatDateTimeShort, + formatDayRange, formatDayShort, formatHourShort, formatPercent, formatTokens, + formatUsageMonth, formatUsd, - makeWindow, + makePeriodWindow, + parseUsagePeriod, + selectableUsageMonths, + type UsagePeriod, } from "@t3tools/shared/usageFormat"; import { formatUsageContractMismatch, usageSourceMessages } from "@t3tools/shared/usageFormatCopy"; import { Button, InlineButton } from "../ui/button"; @@ -60,12 +65,24 @@ import { Menu, MenuCheckboxItem, MenuItem, + MenuItemDetail, MenuPopup, + MenuRadioGroup, + MenuRadioItem, + MenuRadioItemIndicator, MenuSeparator, MenuTrigger, } from "../ui/menu"; import { ScrollArea } from "../ui/scroll-area"; -import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { + Select, + SelectGroup, + SelectGroupLabel, + SelectItem, + SelectPopup, + SelectTrigger, + SelectValue, +} from "../ui/select"; import { AppRouteModal, AppRouteModalClose } from "../AppRouteModal"; import { Skeleton } from "../ui/skeleton"; import { Toggle, ToggleGroup } from "../ui/toggle-group"; @@ -91,6 +108,7 @@ import { } from "./usageBreakdown"; import { METRIC_OPTIONS, + THIS_MONTH_OPTION, WINDOW_OPTIONS, resolveUsageShortcut, type UsageMetric, @@ -111,10 +129,6 @@ function isUsageMetric(value: string | null | undefined): value is UsageMetric { return METRIC_OPTIONS.some((option) => option.value === value); } -function isUsageWindowDays(value: number): value is UsagePagePreferences["windowDays"] { - return WINDOW_OPTIONS.some((option) => option.days === value); -} - const providerLabel = (provider: UsageProviderKind) => PROVIDER_PRESENTATION[provider].label; function usageLoading( @@ -182,7 +196,10 @@ export function UsagePage() { const locale = useLocale(); const m = useMessages(); const shortcutTitle = ( - option: (typeof METRIC_OPTIONS)[number] | (typeof WINDOW_OPTIONS)[number], + option: + | (typeof METRIC_OPTIONS)[number] + | (typeof WINDOW_OPTIONS)[number] + | typeof THIS_MONTH_OPTION, ) => { const shortcut = shortcutLabelForCommand(keybindings, option.command, { context: { usagePageOpen: true }, @@ -191,13 +208,12 @@ export function UsagePage() { ? gt("{label} ({shortcut})", { label: m(option.label), shortcut }) : m(option.label); }; - const [windowSelection, setWindowSelection] = useState(() => ({ - days: preferences.windowDays, - window: makeWindow( - preferences.windowDays, - undefined, - preferences.windowDays === 1 ? "hour" : "day", - ), + const [windowSelection, setWindowSelection] = useState<{ + readonly period: UsagePeriod; + readonly window: UsageSummaryInput; + }>(() => ({ + period: preferences.windowDays, + window: makePeriodWindow(preferences.windowDays), })); const metric = preferences.metric; const showingLimits = metric === "limits"; @@ -208,8 +224,7 @@ export function UsagePage() { const [selectedEnvironmentIds, setSelectedEnvironmentIds] = useState | null>(null); const hiddenProviders = new Set(preferences.hiddenProviders); - const { days: windowDays, window } = windowSelection; - const isPast24Hours = windowDays === 1; + const { period, window } = windowSelection; const { merged: answeredUsage, environments, @@ -240,13 +255,12 @@ export function UsagePage() { setPreferences(nextPreferences); saveUsagePagePreferences(nextPreferences); }; - const selectWindow = (days: number) => { - if (!isUsageWindowDays(days)) return; - updatePreferences({ windowDays: days }); - setWindowSelection({ - days, - window: makeWindow(days, undefined, days === 1 ? "hour" : "day"), + const selectPeriod = (nextPeriod: UsagePeriod) => { + // A past month is not persisted; reloading falls back to the current month. + updatePreferences({ + windowDays: typeof nextPeriod === "string" && nextPeriod !== "month" ? "month" : nextPeriod, }); + setWindowSelection({ period: nextPeriod, window: makePeriodWindow(nextPeriod) }); }; const selectMetric = (nextMetric: UsageMetric) => { if (nextMetric === "limits") setLimitsNow(Date.now()); @@ -284,12 +298,14 @@ export function UsagePage() { const command = resolveUsageShortcut(event, keybindings); const metricOption = METRIC_OPTIONS.find((option) => option.command === command); const periodOption = WINDOW_OPTIONS.find((option) => option.command === command); - if (!metricOption && !periodOption) return; + const isThisMonth = command === THIS_MONTH_OPTION.command; + if (!metricOption && !periodOption && !isThisMonth) return; event.preventDefault(); event.stopPropagation(); if (metricOption) selectMetric(metricOption.value); - if (periodOption && !showingLimits) selectWindow(periodOption.days); + if (isThisMonth && !showingLimits) selectPeriod("month"); + if (periodOption && !showingLimits) selectPeriod(periodOption.period); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window capture keydown listener for usage metric and period shortcuts @@ -310,14 +326,14 @@ export function UsagePage() { }); return; } - const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day"); + const nextWindow = makePeriodWindow(period); if ( nextWindow.sinceDay !== window.sinceDay || nextWindow.untilDay !== window.untilDay || nextWindow.sinceTime !== window.sinceTime || nextWindow.untilTime !== window.untilTime ) { - setWindowSelection({ days: windowDays, window: nextWindow }); + setWindowSelection({ period, window: nextWindow }); } refreshingRef.current = true; setIsRefreshing(true); @@ -357,6 +373,24 @@ export function UsagePage() { (presentation.serverConfig?.providers ?? []).some(usesChatGptSharing), ); + const isMonthPeriod = typeof period === "string"; + const months = selectableUsageMonths(); + const currentYear = months[0]?.slice(0, 4); + const monthWindow = makePeriodWindow("month"); + const thisMonthRange = formatDayRange(monthWindow.sinceDay, monthWindow.untilDay, locale); + const isPastMonth = isMonthPeriod && period !== "month"; + const monthSegmentLabel = isPastMonth + ? formatUsageMonth(period, period.slice(0, 4) !== currentYear, locale) + : isMonthPeriod + ? m(THIS_MONTH_OPTION.label) + : gt("Select month"); + const monthToggleTitle = isPastMonth + ? formatUsageMonth(period, true, locale) + : shortcutTitle(THIS_MONTH_OPTION); + const rangeLabel = isMonthPeriod + ? `${formatDayRange(shownWindow.sinceDay, shownWindow.untilDay, locale)} · ` + : undefined; + const windowLabel = shownHourly && shownWindow.sinceTime !== undefined && shownWindow.untilTime !== undefined ? gt("{start} to {end}", { @@ -367,7 +401,7 @@ export function UsagePage() { start: formatDayShort(shownWindow.sinceDay, locale), end: formatDayShort(shownWindow.untilDay, locale), }); - const windowOptionLabel = WINDOW_OPTIONS.find((option) => option.days === windowDays)?.label; + const windowOptionLabel = WINDOW_OPTIONS.find((option) => option.period === period)?.label; const metricOptionLabel = METRIC_OPTIONS.find((option) => option.value === metric)?.label; const topbarContent = (
@@ -412,17 +446,58 @@ export function UsagePage() { { const value = next[0]; - if (value) selectWindow(Number(value)); + if (value === undefined || value === "month") return; + const nextPeriod = parseUsagePeriod(value); + if (nextPeriod !== undefined) selectPeriod(nextPeriod); }} > {WINDOW_OPTIONS.map((option) => ( - + {m(option.label)} ))} + + }> + {monthSegmentLabel} + + + + { + const nextPeriod = parseUsagePeriod(value); + if (nextPeriod !== undefined) selectPeriod(nextPeriod); + }} + > + + + + This month + + {thisMonthRange} + + + + {months.slice(1).map((month) => ( + + + + {formatUsageMonth(month, true, locale)} + + + + + ))} + + + )}
{showingLimits ? null : ( - { + const nextPeriod = value === null ? undefined : parseUsagePeriod(value); + if (nextPeriod !== undefined) selectPeriod(nextPeriod); + }} + > - {windowOptionLabel && m(windowOptionLabel)} + + {typeof period === "number" + ? windowOptionLabel && m(windowOptionLabel) + : period === "month" + ? m(THIS_MONTH_OPTION.label) + : formatUsageMonth(period, period.slice(0, 4) !== currentYear, locale)} + {WINDOW_OPTIONS.map((option) => ( {m(option.label)} ))} + + + Months + + + {m(THIS_MONTH_OPTION.label)} + + {months.slice(1).map((month) => ( + + {formatUsageMonth(month, true, locale)} + + ))} + )} @@ -561,6 +661,7 @@ export function UsagePage() { hours={hours} showingKept={showingKept} metric={metric === "tokens" ? "tokens" : "cost"} + rangeLabel={rangeLabel} selectedEnvironments={selectedEnvironments} hiddenProviders={hiddenProviders} refreshingUsage={refreshingUsage} @@ -609,6 +710,7 @@ function UsageOverview({ hours, showingKept, metric, + rangeLabel, selectedEnvironments, hiddenProviders, refreshingUsage, @@ -622,6 +724,7 @@ function UsageOverview({ readonly hours: readonly string[]; readonly showingKept: boolean; readonly metric: "tokens" | "cost"; + readonly rangeLabel: string | undefined; readonly selectedEnvironments: readonly EnvironmentUsageStatus[]; readonly hiddenProviders: ReadonlySet; readonly refreshingUsage: boolean; @@ -693,6 +796,7 @@ function UsageOverview({

+ {rangeLabel} {gt("{count, plural, one {{formatted} sessions} other {{formatted} sessions}}", { count: merged.sessions, diff --git a/apps/web/src/components/usage/UsageProviderChart.tsx b/apps/web/src/components/usage/UsageProviderChart.tsx index b19c479ccd4a3..81abfe5822c97 100644 --- a/apps/web/src/components/usage/UsageProviderChart.tsx +++ b/apps/web/src/components/usage/UsageProviderChart.tsx @@ -202,12 +202,15 @@ function buildChart( const stepX = periods.length < 2 ? 0 : VIEW_WIDTH / (periods.length - 1); const paths = providers.map((provider) => { const slot = PROVIDER_ORDER.indexOf(provider); + const points = columns.map((column, periodIndex) => ({ + x: periodIndex * stepX, + y: valueToY(column.bands[slot]?.value ?? 0, scale.max), + })); + const [only] = points; + // smoothCurve needs two points, so a single period draws as a flat line across the width. const line = curvePath( smoothCurve( - columns.map((column, periodIndex) => ({ - x: periodIndex * stepX, - y: valueToY(column.bands[slot]?.value ?? 0, scale.max), - })), + points.length === 1 && only !== undefined ? [only, { x: VIEW_WIDTH, y: only.y }] : points, ), ); return { @@ -519,12 +522,12 @@ export function UsageProviderChart({ > {periods[0] === undefined ? "" : formatPeriod(periods[0])} - {periods[Math.floor(periods.length / 2)] === undefined + {periods.length === 1 || periods[Math.floor(periods.length / 2)] === undefined ? "" : formatPeriod(periods[Math.floor(periods.length / 2)] ?? "")} - {periods[periods.length - 1] === undefined + {periods.length === 1 || periods[periods.length - 1] === undefined ? "" : formatPeriod(periods[periods.length - 1] ?? "")} diff --git a/apps/web/src/components/usage/usagePagePreferences.test.ts b/apps/web/src/components/usage/usagePagePreferences.test.ts index 075076a9b3c52..f76a218c016bb 100644 --- a/apps/web/src/components/usage/usagePagePreferences.test.ts +++ b/apps/web/src/components/usage/usagePagePreferences.test.ts @@ -32,6 +32,11 @@ describe("Usage page preferences", () => { expect(readUsagePagePreferences()).toEqual({ metric: "tokens", windowDays: 30 }); }); + it("round-trips the this-month period", () => { + saveUsagePagePreferences({ metric: "cost", windowDays: "month" }); + expect(readUsagePagePreferences().windowDays).toBe("month"); + }); + // regression: #10189 an invalid saved usage selection was never replaced it.each([ "not-json", diff --git a/apps/web/src/components/usage/usagePagePreferences.ts b/apps/web/src/components/usage/usagePagePreferences.ts index 1aeaefc43da12..d3db35eacbc78 100644 --- a/apps/web/src/components/usage/usagePagePreferences.ts +++ b/apps/web/src/components/usage/usagePagePreferences.ts @@ -6,7 +6,7 @@ import { getLocalStorageItem, setLocalStorageItem } from "../../hooks/useLocalSt const STORAGE_KEY = "t3code:usage-page-preferences:v1"; const UsagePagePreferencesSchema = Schema.Struct({ metric: Schema.Literals(["cost", "tokens", "limits"]), - windowDays: Schema.Literals([1, 7, 30, 90]), + windowDays: Schema.Literals([1, 7, 30, 90, "month"]), hiddenProviders: Schema.optional(Schema.Array(UsageProviderKind)), }); export type UsagePagePreferences = typeof UsagePagePreferencesSchema.Type; diff --git a/apps/web/src/components/usage/usageShortcuts.ts b/apps/web/src/components/usage/usageShortcuts.ts index 64a81e20a53e4..5834477cc01ac 100644 --- a/apps/web/src/components/usage/usageShortcuts.ts +++ b/apps/web/src/components/usage/usageShortcuts.ts @@ -11,12 +11,18 @@ export const METRIC_OPTIONS = [ ] as const satisfies readonly { value: UsageMetric; label: string; command: KeybindingCommand }[]; export const WINDOW_OPTIONS = [ - { days: 1, label: msg("Past 24h"), command: "usage.period.day" }, - { days: 7, label: msg("7 days"), command: "usage.period.week" }, - { days: 30, label: msg("30 days"), command: "usage.period.month" }, - { days: 90, label: msg("90 days"), command: "usage.period.quarter" }, + { period: 1, label: msg("Past 24h"), command: "usage.period.day" }, + { period: 7, label: msg("7 days"), command: "usage.period.week" }, + { period: 30, label: msg("30 days"), command: "usage.period.month" }, + { period: 90, label: msg("90 days"), command: "usage.period.quarter" }, ] as const; +export const THIS_MONTH_OPTION = { + period: "month", + label: msg("This month"), + command: "usage.period.thisMonth", +} as const; + export function resolveUsageShortcut( event: ShortcutEventLike & { target: EventTarget | null }, keybindings: ResolvedKeybindingsConfig, diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index c7095b8536469..b7c590653eb47 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12208,6 +12208,7 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "d9d87c222c4811a4": "Monat auswählen", "71efdf870da332e8": "{start} bis {end}", "77100b4211d5cf8c": "Navigationspfad der Nutzung", "2f96360836544ae6": "Nutzungszeitraum", @@ -12247,6 +12248,8 @@ "31fd849033990734": "Keine Anbieter", "0d4d01729dabc81e": "{count, plural, one {{count} Anbieter} other {{count} Anbieter}}", "19ace67a44293eba": "Nutzung", + "9f47b4e24a3e8dd0": "Dieser Monat", + "99923f19c9f286aa": "Monate", "26f2732fd6317056": [ "Die API-Schätzung schließt", " ", @@ -12340,6 +12343,7 @@ "2cddd6095abc734a": "7 Tage", "53493056306708cf": "30 Tage", "c719359d18d37ad3": "90 Tage", + "c869d7fd448a43fe": "Dieser Monat", "8367779e149f723b": "Anfrage an die primäre Umgebung während {operation} fehlgeschlagen (HTTP {status}).", "c5cd027743a2b5a6": "Ungültiges Kopplungstoken. Prüfe das Token und versuch es erneut.", "0e4b49c8203aae81": "Zeitüberschreitung beim Warten auf eine authentifizierte Sitzung nach dem Bootstrap.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 2ff8148bb7329..df0d5a7b606a1 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12216,6 +12216,7 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "d9d87c222c4811a4": "Select month", "71efdf870da332e8": "{start} to {end}", "77100b4211d5cf8c": "Usage breadcrumb", "2f96360836544ae6": "Usage period", @@ -12255,6 +12256,8 @@ "31fd849033990734": "No providers", "0d4d01729dabc81e": "{count, plural, one {{count} providers} other {{count} providers}}", "19ace67a44293eba": "Usage", + "9f47b4e24a3e8dd0": "This month", + "99923f19c9f286aa": "Months", "26f2732fd6317056": [ "API estimate excludes", " ", @@ -12348,6 +12351,7 @@ "2cddd6095abc734a": "7 days", "53493056306708cf": "30 days", "c719359d18d37ad3": "90 days", + "c869d7fd448a43fe": "This month", "8367779e149f723b": "Primary environment request failed during {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Invalid pairing token. Check the token and try again.", "0e4b49c8203aae81": "Timed out waiting for authenticated session after bootstrap.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 78c68c4c0dc2f..c1d946af03fd4 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12201,6 +12201,7 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "d9d87c222c4811a4": "Seleccionar mes", "71efdf870da332e8": "Del {start} al {end}", "77100b4211d5cf8c": "Ruta de navegación de uso", "2f96360836544ae6": "Periodo de uso", @@ -12240,6 +12241,8 @@ "31fd849033990734": "No hay proveedores", "0d4d01729dabc81e": "{count, plural, one {{count} proveedor} other {{count} proveedores}}", "19ace67a44293eba": "Uso", + "9f47b4e24a3e8dd0": "Este mes", + "99923f19c9f286aa": "Meses", "26f2732fd6317056": [ "La estimación de API excluye", " ", @@ -12333,6 +12336,7 @@ "2cddd6095abc734a": "7 días", "53493056306708cf": "30 días", "c719359d18d37ad3": "90 días", + "c869d7fd448a43fe": "Este mes", "8367779e149f723b": "Falló una solicitud al entorno principal durante {operation} (HTTP {status}).", "c5cd027743a2b5a6": "El token de emparejamiento no es válido. Revísalo e inténtalo de nuevo.", "0e4b49c8203aae81": "Se agotó el tiempo de espera de la sesión autenticada tras el arranque.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 873767a296ba5..83a8dc48078f4 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12206,6 +12206,7 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "d9d87c222c4811a4": "Choisir un mois", "71efdf870da332e8": "Du {start} au {end}", "77100b4211d5cf8c": "Fil d’Ariane de l’utilisation", "2f96360836544ae6": "Période d’utilisation", @@ -12245,6 +12246,8 @@ "31fd849033990734": "Aucun fournisseur", "0d4d01729dabc81e": "{count, plural, one {{count} fournisseur} other {{count} fournisseurs}}", "19ace67a44293eba": "Utilisation", + "9f47b4e24a3e8dd0": "Ce mois-ci", + "99923f19c9f286aa": "Mois", "26f2732fd6317056": [ "L’estimation API exclut", " ", @@ -12338,6 +12341,7 @@ "2cddd6095abc734a": "7 jours", "53493056306708cf": "30 jours", "c719359d18d37ad3": "90 jours", + "c869d7fd448a43fe": "Ce mois-ci", "8367779e149f723b": "La requête vers l’environnement principal a échoué pendant {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Jeton d’appairage non valide. Vérifiez le jeton et réessayez.", "0e4b49c8203aae81": "Délai dépassé en attendant la session authentifiée après l’amorçage.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 69ac82ad8a247..8a66f10914cb0 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12157,6 +12157,7 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "d9d87c222c4811a4": "月を選択", "71efdf870da332e8": "{start}〜{end}", "77100b4211d5cf8c": "使用量のパンくずリスト", "2f96360836544ae6": "使用量の期間", @@ -12196,6 +12197,8 @@ "31fd849033990734": "プロバイダーなし", "0d4d01729dabc81e": "{count, plural, other {{count} 個のプロバイダー}}", "19ace67a44293eba": "使用量", + "9f47b4e24a3e8dd0": "今月", + "99923f19c9f286aa": "月", "26f2732fd6317056": [ "API の推定額には価格不明の", " ", @@ -12289,6 +12292,7 @@ "2cddd6095abc734a": "7 日間", "53493056306708cf": "30 日間", "c719359d18d37ad3": "90 日間", + "c869d7fd448a43fe": "今月", "8367779e149f723b": "プライマリ環境へのリクエストが {operation} 中に失敗しました (HTTP {status})。", "c5cd027743a2b5a6": "ペアリングトークンが無効です。トークンを確認して、もう一度お試しください。", "0e4b49c8203aae81": "ブートストラップ後、認証済みセッションの待機がタイムアウトしました。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 10782b2ca6166..a136dfa75d127 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12153,6 +12153,7 @@ } ], "b93dc3faeb8d9b2e": "{label}({shortcut})", + "d9d87c222c4811a4": "월 선택", "71efdf870da332e8": "{start}~{end}", "77100b4211d5cf8c": "사용량 이동 경로", "2f96360836544ae6": "사용량 기간", @@ -12192,6 +12193,8 @@ "31fd849033990734": "제공자 없음", "0d4d01729dabc81e": "{count, plural, other {제공자 {count}개}}", "19ace67a44293eba": "사용량", + "9f47b4e24a3e8dd0": "이번 달", + "99923f19c9f286aa": "월", "26f2732fd6317056": [ "API 추정치에는 가격 없는 기록", " ", @@ -12285,6 +12288,7 @@ "2cddd6095abc734a": "7일", "53493056306708cf": "30일", "c719359d18d37ad3": "90일", + "c869d7fd448a43fe": "이번 달", "8367779e149f723b": "{operation} 중 기본 환경 요청에 실패했습니다(HTTP {status}).", "c5cd027743a2b5a6": "잘못된 페어링 토큰입니다. 토큰을 확인하고 다시 시도하세요.", "0e4b49c8203aae81": "부트스트랩 후 인증된 세션을 기다리다 시간이 초과되었습니다.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5b2b9e2b9b381..8926e9b8a704c 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12206,6 +12206,7 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "d9d87c222c4811a4": "Selecionar mês", "71efdf870da332e8": "{start} a {end}", "77100b4211d5cf8c": "Trilha de navegação do uso", "2f96360836544ae6": "Período de uso", @@ -12245,6 +12246,8 @@ "31fd849033990734": "Nenhum provedor", "0d4d01729dabc81e": "{count, plural, one {{count} provedor} other {{count} provedores}}", "19ace67a44293eba": "Uso", + "9f47b4e24a3e8dd0": "Este mês", + "99923f19c9f286aa": "Meses", "26f2732fd6317056": [ "A estimativa da API exclui", " ", @@ -12338,6 +12341,7 @@ "2cddd6095abc734a": "7 dias", "53493056306708cf": "30 dias", "c719359d18d37ad3": "90 dias", + "c869d7fd448a43fe": "Este mês", "8367779e149f723b": "A requisição ao ambiente principal falhou durante {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Token de pareamento inválido. Verifique o token e tente novamente.", "0e4b49c8203aae81": "Tempo esgotado aguardando a sessão autenticada após a inicialização.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 0ecadaba9ded1..61a745951c91a 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12207,6 +12207,7 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "d9d87c222c4811a4": "Выбрать месяц", "71efdf870da332e8": "С {start} по {end}", "77100b4211d5cf8c": "Навигация по использованию", "2f96360836544ae6": "Период использования", @@ -12246,6 +12247,8 @@ "31fd849033990734": "Нет провайдеров", "0d4d01729dabc81e": "{count, plural, one {{count} провайдер} few {{count} провайдера} many {{count} провайдеров} other {{count} провайдера}}", "19ace67a44293eba": "Использование", + "9f47b4e24a3e8dd0": "Этот месяц", + "99923f19c9f286aa": "Месяцы", "26f2732fd6317056": [ "Оценка по API не включает", " ", @@ -12339,6 +12342,7 @@ "2cddd6095abc734a": "7 дней", "53493056306708cf": "30 дней", "c719359d18d37ad3": "90 дней", + "c869d7fd448a43fe": "Этот месяц", "8367779e149f723b": "Запрос к основному окружению не удался во время {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Недействительный токен сопряжения. Проверьте токен и попробуйте ещё раз.", "0e4b49c8203aae81": "Истекло время ожидания аутентифицированного сеанса после начальной загрузки.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 1c01b1112768f..c5c70005b7432 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12214,6 +12214,7 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "d9d87c222c4811a4": "Välj månad", "71efdf870da332e8": "{start} till {end}", "77100b4211d5cf8c": "Sökväg i användning", "2f96360836544ae6": "Användningsperiod", @@ -12253,6 +12254,8 @@ "31fd849033990734": "Inga leverantörer", "0d4d01729dabc81e": "{count, plural, one {{count} leverantör} other {{count} leverantörer}}", "19ace67a44293eba": "Användning", + "9f47b4e24a3e8dd0": "Den här månaden", + "99923f19c9f286aa": "Månader", "26f2732fd6317056": [ "API-uppskattningen utesluter", " ", @@ -12346,6 +12349,7 @@ "2cddd6095abc734a": "7 dagar", "53493056306708cf": "30 dagar", "c719359d18d37ad3": "90 dagar", + "c869d7fd448a43fe": "Den här månaden", "8367779e149f723b": "Begäran till den primära miljön misslyckades under {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Ogiltig parkopplingstoken. Kontrollera token och försök igen.", "0e4b49c8203aae81": "Tidsgränsen överskreds i väntan på en autentiserad session efter uppstart.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 43790340d1167..2781277da254d 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12232,6 +12232,7 @@ } ], "b93dc3faeb8d9b2e": "{label}({shortcut})", + "d9d87c222c4811a4": "选择月份", "71efdf870da332e8": "{start} 至 {end}", "77100b4211d5cf8c": "用量导航", "2f96360836544ae6": "用量时间范围", @@ -12271,6 +12272,8 @@ "31fd849033990734": "没有提供方", "0d4d01729dabc81e": "{count, plural, other {{count} 个提供方}}", "19ace67a44293eba": "用量", + "9f47b4e24a3e8dd0": "本月", + "99923f19c9f286aa": "月份", "26f2732fd6317056": [ "API 估算不包括", " ", @@ -12364,6 +12367,7 @@ "2cddd6095abc734a": "7 天", "53493056306708cf": "30 天", "c719359d18d37ad3": "90 天", + "c869d7fd448a43fe": "本月", "8367779e149f723b": "主环境请求在 {operation} 期间失败(HTTP {status})。", "c5cd027743a2b5a6": "配对 token 无效。请检查后重试。", "0e4b49c8203aae81": "引导完成后等待登录状态超时。", diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index fb6f719bb2346..a2b5da869f332 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -996,19 +996,25 @@ describe("Usage shortcuts", () => { }, ); - it("matches shifted number keys for periods and only on Usage", () => { - const shortcut = event({ key: "!", code: "Digit1", ctrlKey: true, shiftKey: true }); - assert.strictEqual( - resolveShortcutCommand(shortcut, DEFAULT_RESOLVED_KEYBINDINGS, { - platform: "Linux", - context: { usagePageOpen: true }, - }), - "usage.period.day", - ); - assert.isNull( - resolveShortcutCommand(shortcut, DEFAULT_RESOLVED_KEYBINDINGS, { - platform: "Linux", - }), - ); - }); + it.each([ + { key: "!", code: "Digit1", command: "usage.period.day" }, + { key: "%", code: "Digit5", command: "usage.period.thisMonth" }, + ])( + "matches shifted number keys for periods and only on Usage ($key)", + ({ key, code, command }) => { + const shortcut = event({ key, code, ctrlKey: true, shiftKey: true }); + assert.strictEqual( + resolveShortcutCommand(shortcut, DEFAULT_RESOLVED_KEYBINDINGS, { + platform: "Linux", + context: { usagePageOpen: true }, + }), + command, + ); + assert.isNull( + resolveShortcutCommand(shortcut, DEFAULT_RESOLVED_KEYBINDINGS, { + platform: "Linux", + }), + ); + }, + ); }); diff --git a/docs/user/usage.md b/docs/user/usage.md index 43f4c94a19328..29d52fcc6ade4 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -15,6 +15,9 @@ cost, split by token type and by speed. These estimates are not your subscriptio split, such as a provider-reported cost for a model without public rates, shows as **Other**. Select a model under **Breakdown** to see its trend, cache hit rate, and cost per million tokens. +Pick a rolling period, or open the month menu to see **This month** or an earlier calendar month. +The menu lists only months that start within the last 92 days. + Totals depend on the history available on each server. Grok turns without a saved completed-turn record are missing from the totals. Text generation (thread titles, commit messages, PR text, branch names and review guides) is not in @@ -204,7 +207,7 @@ Session, Weekly, or both for each provider. Reopen T3 to refresh expired reading On web and desktop, open Usage from the command palette. While on Usage, press `C`, `T`, or `L` for Cost, Tokens, or Limits while not typing in a field. -Use `Ctrl+Shift+1/2/3/4` (`Cmd+Shift+1/2/3/4` on macOS) for the past -24 hours, 7 days, 30 days, or 90 days. Period shortcuts do nothing on Limits. +Use `Ctrl+Shift+1/2/3/4/5` (`Cmd+Shift+1/2/3/4/5` on macOS) for the past +24 hours, 7 days, 30 days, 90 days, or this month. Period shortcuts do nothing on Limits. Press `Escape` to return to the previous page. Customize these shortcuts in **Settings → Keybindings**. diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index eda5138b760b9..0ade483336735 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -114,6 +114,7 @@ export const STATIC_KEYBINDING_COMMANDS = [ "usage.period.week", "usage.period.month", "usage.period.quarter", + "usage.period.thisMonth", ...MODEL_PICKER_KEYBINDING_COMMANDS, ...THREAD_KEYBINDING_COMMANDS, ] as const; diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index 9a67264d8bd1f..06a8da986d967 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -148,6 +148,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+shift+2", command: "usage.period.week", when: "usagePageOpen" }, { key: "mod+shift+3", command: "usage.period.month", when: "usagePageOpen" }, { key: "mod+shift+4", command: "usage.period.quarter", when: "usagePageOpen" }, + { key: "mod+shift+5", command: "usage.period.thisMonth", when: "usagePageOpen" }, ]; function normalizeKeyToken(token: string): string { diff --git a/packages/shared/src/usageFormat.test.ts b/packages/shared/src/usageFormat.test.ts index 79477fc1ed4d4..cfdb072fb7e4d 100644 --- a/packages/shared/src/usageFormat.test.ts +++ b/packages/shared/src/usageFormat.test.ts @@ -2,7 +2,18 @@ import { describe, expect, it, vi } from "vite-plus/test"; import type { UsageSource } from "@t3tools/contracts"; -import { formatHourShort, formatTokens, makeWindow, usageSourceMessages } from "./usageFormat.ts"; +import { + formatDayRange, + formatHourShort, + formatTokens, + formatUsageMonth, + makePeriodWindow, + makeWindow, + parseUsagePeriod, + selectableUsageMonths, + type UsagePeriod, + usageSourceMessages, +} from "./usageFormat.ts"; function malformedSource(count: number, overrides: Partial = {}): UsageSource { return { @@ -177,6 +188,118 @@ describe("hourly usage formatting", () => { }); }); +describe("usage periods", () => { + function withResolvedZone(timeZone: string, run: () => T): T { + const resolved = new Intl.DateTimeFormat().resolvedOptions(); + const resolvedOptions = vi + .spyOn(Intl.DateTimeFormat.prototype, "resolvedOptions") + .mockReturnValue({ ...resolved, timeZone }); + try { + return run(); + } finally { + resolvedOptions.mockRestore(); + } + } + + const periodCases: { + zone: string; + now: string; + period: UsagePeriod; + sinceDay: string; + untilDay: string; + }[] = [ + { + zone: "America/Los_Angeles", + now: "2026-11-01T03:00:00Z", + period: "month", + sinceDay: "2026-10-01", + untilDay: "2026-10-31", + }, + { + zone: "UTC", + now: "2026-11-08T12:00:00Z", + period: "month", + sinceDay: "2026-11-01", + untilDay: "2026-11-08", + }, + { + zone: "UTC", + now: "2026-11-01T12:00:00Z", + period: "month", + sinceDay: "2026-11-01", + untilDay: "2026-11-01", + }, + { + zone: "UTC", + now: "2026-11-08T12:00:00Z", + period: "2026-10", + sinceDay: "2026-10-01", + untilDay: "2026-10-31", + }, + { + zone: "UTC", + now: "2026-11-08T12:00:00Z", + period: "2028-02", + sinceDay: "2026-11-01", + untilDay: "2026-11-08", + }, + { + zone: "UTC", + now: "2028-03-10T12:00:00Z", + period: "2028-02", + sinceDay: "2028-02-01", + untilDay: "2028-02-29", + }, + ]; + + it.each(periodCases)( + "makePeriodWindow($period) at $now spans $sinceDay to $untilDay", + ({ zone, now, period, sinceDay, untilDay }) => { + const window = withResolvedZone(zone, () => makePeriodWindow(period, new Date(now))); + expect(window.sinceDay).toBe(sinceDay); + expect(window.untilDay).toBe(untilDay); + expect(window.resolution).toBe("day"); + }, + ); + + it.each([ + { now: "2026-11-08T12:00:00Z", months: ["2026-11", "2026-10", "2026-09"] }, + { now: "2027-03-01T12:00:00Z", months: ["2027-03", "2027-02", "2027-01", "2026-12"] }, + ])("selectableUsageMonths at $now offers $months", ({ now, months }) => { + expect(withResolvedZone("UTC", () => selectableUsageMonths(new Date(now)))).toEqual(months); + }); + + it.each([ + { sinceDay: "2026-11-01", untilDay: "2026-11-08", label: "Nov 1 – 8" }, + { sinceDay: "2026-11-08", untilDay: "2026-11-08", label: "Nov 8" }, + { sinceDay: "2026-10-10", untilDay: "2026-11-08", label: "Oct 10 – Nov 8" }, + { sinceDay: "2025-12-12", untilDay: "2026-01-08", label: "Dec 12, 2025 – Jan 8, 2026" }, + ])("formatDayRange($sinceDay, $untilDay) -> $label", ({ sinceDay, untilDay, label }) => { + expect(formatDayRange(sinceDay, untilDay)).toBe(label); + }); + + it("formatDayRange uses the locale's range format outside English", () => { + expect(formatDayRange("2026-11-01", "2026-11-08", "de")).toBe("1.–8. Nov."); + }); + + it("formatUsageMonth uses full month names with and without the year", () => { + expect(formatUsageMonth("2026-10")).toBe("October 2026"); + expect(formatUsageMonth("2026-10", false)).toBe("October"); + expect(formatUsageMonth("2026-10", true, "de")).toBe("Oktober 2026"); + expect(formatUsageMonth("2026-10", false, "de")).toBe("Oktober"); + }); + + it.each([ + { value: "7", parsed: 7 }, + { value: "month", parsed: "month" }, + { value: "2026-10", parsed: "2026-10" }, + { value: "2026-13", parsed: undefined }, + { value: "abc", parsed: undefined }, + ])("parseUsagePeriod($value) -> $parsed", ({ value, parsed }) => { + expect(parseUsagePeriod(value)).toBe(parsed); + }); +}); + describe("token formatting", () => { it("moves to the next unit when rounding reaches it", () => { expect(formatTokens(999_999)).toBe("1M"); diff --git a/packages/shared/src/usageFormat.ts b/packages/shared/src/usageFormat.ts index 45f46ce8f9a0c..ef33bf78f1370 100644 --- a/packages/shared/src/usageFormat.ts +++ b/packages/shared/src/usageFormat.ts @@ -116,6 +116,36 @@ export function formatPercent(share: number, digits = 1): string { return `${percent.toFixed(digits)}%`; } +const SHORT_MONTHS = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", +]; + +const FULL_MONTHS = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", +]; + export function formatDayShort(day: string, locale?: string): string { const [year, month, dayOfMonth] = day.split("-").map((part) => Number(part)); if (year === undefined || month === undefined || dayOfMonth === undefined) return day; @@ -128,21 +158,7 @@ export function formatDayShort(day: string, locale?: string): string { date, ); } - const MONTHS = [ - "Jan", - "Feb", - "Mar", - "Apr", - "May", - "Jun", - "Jul", - "Aug", - "Sep", - "Oct", - "Nov", - "Dec", - ]; - return `${MONTHS[month - 1] ?? ""} ${dayOfMonth}`; + return `${SHORT_MONTHS[month - 1] ?? ""} ${dayOfMonth}`; } export function enumerateDays(sinceDay: string, untilDay: string): readonly string[] { @@ -288,29 +304,37 @@ export function formatRelativeHourShort( return formatDateTimeShort(hourStart, timeZone, hour12, locale); } +function zoneDayFormatter(): { timeZone: string; format: Intl.DateTimeFormat } { + const requested = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; + try { + return { + timeZone: requested, + format: new Intl.DateTimeFormat("en-CA", { + timeZone: requested, + year: "numeric", + month: "2-digit", + day: "2-digit", + }), + }; + } catch { + return { + timeZone: "UTC", + format: new Intl.DateTimeFormat("en-CA", { + timeZone: "UTC", + year: "numeric", + month: "2-digit", + day: "2-digit", + }), + }; + } +} + export function makeWindow( days: number, now = new Date(), resolution: UsageResolution = "day", ): UsageSummaryInput { - let timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; - let format: Intl.DateTimeFormat; - try { - format = new Intl.DateTimeFormat("en-CA", { - timeZone, - year: "numeric", - month: "2-digit", - day: "2-digit", - }); - } catch { - timeZone = "UTC"; - format = new Intl.DateTimeFormat("en-CA", { - timeZone: "UTC", - year: "numeric", - month: "2-digit", - day: "2-digit", - }); - } + const { timeZone, format } = zoneDayFormatter(); const untilDay = format.format(now); if (resolution === "hour") { const untilTimeMs = Math.floor(now.getTime() / 60_000) * 60_000; @@ -338,3 +362,113 @@ export function makeWindow( resolution, }; } + +const USAGE_HISTORY_DAYS = 92; + +export type UsageRollingDays = 1 | 7 | 30 | 90; + +// "YYYY-MM" calendar month keys, e.g. "2026-10". +export type UsageMonthKey = `${number}-${number}`; + +export type UsagePeriod = UsageRollingDays | "month" | UsageMonthKey; + +export function makePeriodWindow(period: UsagePeriod, now = new Date()): UsageSummaryInput { + if (typeof period === "number") { + return period === 1 ? makeWindow(1, now, "hour") : makeWindow(period, now); + } + const { timeZone, format } = zoneDayFormatter(); + const untilDay = format.format(now); + const currentMonth = untilDay.slice(0, 7); + if (period === "month" || period >= currentMonth) { + return { + sinceDay: UsageDay.make(`${currentMonth}-01`), + untilDay: UsageDay.make(untilDay), + timeZone, + resolution: "day", + }; + } + const [year = 0, month = 1] = period.split("-").map((part) => Number.parseInt(part, 10)); + // Date.UTC normalizes day 0 to the last day of the previous month, leap years included. + const lastDay = new Date(Date.UTC(year, month, 0)).getUTCDate(); + return { + sinceDay: UsageDay.make(`${period}-01`), + untilDay: UsageDay.make(`${period}-${lastDay}`), + timeZone, + resolution: "day", + }; +} + +export function selectableUsageMonths(now = new Date()): readonly UsageMonthKey[] { + const { format } = zoneDayFormatter(); + const [year = 0, month = 1, dayOfMonth = 1] = format + .format(now) + .split("-") + .map((part) => Number.parseInt(part, 10)); + const cutoffDay = new Date(Date.UTC(year, month - 1, dayOfMonth - USAGE_HISTORY_DAYS)) + .toISOString() + .slice(0, 10); + const months: UsageMonthKey[] = []; + let cursorYear = year; + let cursorMonth = month; + while (`${cursorYear}-${String(cursorMonth).padStart(2, "0")}-01` > cutoffDay) { + months.push(`${cursorYear}-${String(cursorMonth).padStart(2, "0")}` as UsageMonthKey); + cursorMonth -= 1; + if (cursorMonth === 0) { + cursorMonth = 12; + cursorYear -= 1; + } + } + return months; +} + +export function formatUsageMonth(month: UsageMonthKey, withYear = true, locale?: string): string { + const [year, monthNumber] = month.split("-"); + const name = FULL_MONTHS[Number(monthNumber) - 1]; + if (name === undefined) return month; + const intlLocale = formatLocale(locale); + if (intlLocale !== "en-US") { + return dateTimeFormatter(intlLocale, { + timeZone: "UTC", + month: "long", + ...(withYear ? { year: "numeric" } : {}), + }).format(new Date(Date.UTC(Number(year), Number(monthNumber) - 1, 1))); + } + return withYear ? `${name} ${year}` : name; +} + +export function formatDayRange(sinceDay: string, untilDay: string, locale?: string): string { + const intlLocale = formatLocale(locale); + if (intlLocale !== "en-US") { + const since = new Date(`${sinceDay}T00:00:00Z`); + const until = new Date(`${untilDay}T00:00:00Z`); + if (Number.isNaN(since.getTime()) || Number.isNaN(until.getTime())) { + return `${sinceDay} – ${untilDay}`; + } + const sameYear = sinceDay.slice(0, 4) === untilDay.slice(0, 4); + return dateTimeFormatter(intlLocale, { + timeZone: "UTC", + month: "short", + day: "numeric", + ...(sameYear ? {} : { year: "numeric" }), + }).formatRange(since, until); + } + const [sinceYear = "", sinceMonth = "", sinceDayOfMonth = ""] = sinceDay.split("-"); + const [untilYear = "", untilMonth = "", untilDayOfMonth = ""] = untilDay.split("-"); + const sinceLabel = formatDayShort(sinceDay); + const untilLabel = formatDayShort(untilDay); + if (sinceDay === untilDay) return untilLabel; + if (sinceYear === untilYear && sinceMonth === untilMonth) { + return `${SHORT_MONTHS[Number(sinceMonth) - 1] ?? ""} ${Number(sinceDayOfMonth)} – ${Number(untilDayOfMonth)}`; + } + if (sinceYear === untilYear) return `${sinceLabel} – ${untilLabel}`; + return `${sinceLabel}, ${sinceYear} – ${untilLabel}, ${untilYear}`; +} + +export function parseUsagePeriod(value: string): UsagePeriod | undefined { + if (value === "1") return 1; + if (value === "7") return 7; + if (value === "30") return 30; + if (value === "90") return 90; + if (value === "month") return "month"; + return /^\d{4}-(0[1-9]|1[0-2])$/.test(value) ? (value as UsageMonthKey) : undefined; +}