Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
227 changes: 186 additions & 41 deletions apps/mobile/src/features/usage/UsageRouteScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
isModelCostUnknown,
type DailyTotals,
type MergedUsage,
type ProjectTotals,
} from "@t3tools/shared/usageMerge";
import {
enumerateDays,
Expand Down Expand Up @@ -50,6 +51,12 @@ import type { UsageChartMetric } from "./usageChartData";
import { PROVIDER_LABEL, useProviderColors, useUsageMixColors } from "./usageProviders";

type UsageView = UsageChartMetric | "limits";
type UsageBreakdown = "model" | "project";
const BREAKDOWN_OPTIONS = [
{ value: "model", label: msg("Model") },
{ value: "project", label: msg("Project") },
] as const satisfies readonly { value: UsageBreakdown; label: string }[];

const VIEW_OPTIONS = [
{ value: "cost", label: msg("Cost", { $context: "usage view tab" }) },
{ value: "tokens", label: msg("Tokens", { $context: "usage view tab" }) },
Expand Down Expand Up @@ -117,6 +124,7 @@ function UsageScreen(props: {
}
const { view } = selection;
const setView = (view: UsageView) => setSelection({ params: props.tabParam, view });
const [breakdown, setBreakdown] = useState<UsageBreakdown>("model");
const [measuredWidth, setWidth] = useState(0);
// A workspace pane knows its width in the render that resizes it; measuring lags a frame.
const width = useWorkspaceSettledContentWidth() ?? measuredWidth;
Expand Down Expand Up @@ -395,7 +403,14 @@ function UsageScreen(props: {
columns={width >= 900 ? 6 : wide ? 3 : 2}
/>
<CostSection merged={merged} wide={wide} />
<ModelsSection merged={merged} metric={metric} columns={wide ? 2 : 1} />
<ModelsSection
merged={merged}
metric={metric}
columns={wide ? 2 : 1}
breakdown={breakdown}
onBreakdownChange={setBreakdown}
showEnvironment={selectedEnvironments.length > 1}
/>
</UsageUpdating>
</>
)}
Expand Down Expand Up @@ -838,11 +853,20 @@ function ModelsSection(props: {
readonly merged: MergedUsage;
readonly metric: UsageChartMetric;
readonly columns: 1 | 2;
readonly breakdown: UsageBreakdown;
readonly onBreakdownChange: (value: UsageBreakdown) => void;
readonly showEnvironment: boolean;
}) {
const { merged, metric } = props;
const colors = useProviderColors();
const gt = useGT();
if (merged.models.length === 0) return null;
const m = useMessages();
if (merged.models.length === 0 && merged.projects.length === 0) return null;

const breakdownOptions = BREAKDOWN_OPTIONS.map((option) => ({
...option,
label: m(option.label),
}));

// Hermes lacks toSorted.
const ordered = [...merged.models].sort((a, b) =>
Expand All @@ -852,57 +876,178 @@ function ModelsSection(props: {
);

return (
<SettingsSection title={gt("By model")}>
<View className="flex-row flex-wrap">
{ordered.map((model, index) => (
<SettingsSection
title={gt("Breakdown")}
trailing={
<SegmentedControl
options={breakdownOptions}
selected={props.breakdown}
onSelect={props.onBreakdownChange}
role="tab"
className="w-44"
/>
}
>
{props.breakdown === "project" ? (
<ProjectRows
projects={merged.projects}
metric={metric}
columns={props.columns}
showEnvironment={props.showEnvironment}
/>
) : (
<View className="flex-row flex-wrap">
{ordered.map((model, index) => (
<View
key={`${model.provider}:${model.model}`}
className={cn(
"flex-row items-center gap-3 p-4",
index >= props.columns && "border-t border-border-subtle",
index % props.columns === 1 && "border-l border-border-subtle",
)}
style={{ width: `${100 / props.columns}%` }}
>
<View
className="size-2.5 shrink-0 rounded-full"
style={{ backgroundColor: colors[model.provider] }}
/>
<View className="min-w-0 flex-1 gap-0.5">
<Text className="text-base text-foreground" numberOfLines={1}>
{model.model}
</Text>
<Text className="text-sm text-foreground-muted">
{metric === "tokens"
? isModelCostUnknown(model)
? gt("{share} of tokens · no known rates", {
share: formatPercent(model.tokenShare),
})
: gt("{share} of tokens · {cost}", {
share: formatPercent(model.tokenShare),
cost: formatUsd(model.costUsd),
})
: isModelCostUnknown(model)
? gt("no known rates · {tokens} tokens", {
tokens: formatTokens(model.totalTokens),
})
: gt("{share} of cost · {tokens} tokens", {
share: formatPercent(model.costShare),
tokens: formatTokens(model.totalTokens),
})}
</Text>
</View>
<Text className="text-base tabular-nums text-foreground">
{metric === "tokens"
? formatTokens(model.totalTokens)
: isModelCostUnknown(model)
? gt("Unpriced", { $context: "model with no known price" })
: formatUsd(model.costUsd)}
</Text>
</View>
))}
</View>
)}
</SettingsSection>
);
}

function ProjectRows(props: {
readonly projects: readonly ProjectTotals[];
readonly metric: UsageChartMetric;
readonly columns: 1 | 2;
readonly showEnvironment: boolean;
}) {
const { metric } = props;
const gt = useGT();
// Hermes lacks toSorted.
const ordered = [...props.projects].sort((a, b) =>
metric === "cost"
? b.costUsd - a.costUsd || b.totalTokens - a.totalTokens
: b.totalTokens - a.totalTokens || b.costUsd - a.costUsd,
);
const peak =
ordered[0] === undefined
? 0
: metric === "tokens"
? ordered[0].totalTokens
: ordered[0].costUsd;

return (
<View className="flex-row flex-wrap">
{ordered.map((project, index) => {
const unknown = isModelCostUnknown(project);
const magnitude = metric === "tokens" ? project.totalTokens : project.costUsd;
const label = project.kind === "project" ? project.title : gt("No project");
const value =
metric === "tokens"
? formatTokens(project.totalTokens)
: unknown
? gt("Unpriced", { $context: "model with no known price" })
: formatUsd(project.costUsd);
const detail = [
project.kind === "project" && props.showEnvironment ? project.environmentLabel : null,
project.duplicateTitleId !== null
? gt("ID {id}", { id: project.duplicateTitleId })
: null,
metric === "tokens"
? unknown
? gt("{share} of tokens · no known rates", {
share: formatPercent(project.tokenShare),
})
: gt("{share} of tokens · {cost}", {
share: formatPercent(project.tokenShare),
cost: formatUsd(project.costUsd),
})
: unknown
? gt("no known rates · {tokens} tokens", {
tokens: formatTokens(project.totalTokens),
})
: gt("{share} of cost · {tokens} tokens", {
share: formatPercent(project.costShare),
tokens: formatTokens(project.totalTokens),
}),
!unknown && project.unpricedRecords > 0 ? gt("Some unpriced") : null,
]
.filter((part) => part !== null)
.join(" · ");

return (
<View
key={`${model.provider}:${model.model}`}
key={project.key}
accessible
accessibilityLabel={`${label}, ${value}, ${detail}`}
className={cn(
"flex-row items-center gap-3 p-4",
index >= props.columns && "border-t border-border-subtle",
index % props.columns === 1 && "border-l border-border-subtle",
)}
style={{ width: `${100 / props.columns}%` }}
>
<View
className="size-2.5 shrink-0 rounded-full"
style={{ backgroundColor: colors[model.provider] }}
/>
<View className="min-w-0 flex-1 gap-0.5">
<Text className="text-base text-foreground" numberOfLines={1}>
{model.model}
</Text>
<Text className="text-sm text-foreground-muted">
{metric === "tokens"
? isModelCostUnknown(model)
? gt("{share} of tokens · no known rates", {
share: formatPercent(model.tokenShare),
})
: gt("{share} of tokens · {cost}", {
share: formatPercent(model.tokenShare),
cost: formatUsd(model.costUsd),
})
: isModelCostUnknown(model)
? gt("no known rates · {tokens} tokens", {
tokens: formatTokens(model.totalTokens),
})
: gt("{share} of cost · {tokens} tokens", {
share: formatPercent(model.costShare),
tokens: formatTokens(model.totalTokens),
})}
<Text
className={
project.kind === "project"
? "text-base text-foreground"
: "text-base text-foreground-muted"
}
numberOfLines={2}
>
{label}
</Text>
<Text className="text-sm text-foreground-muted">{detail}</Text>
{magnitude > 0 && peak > 0 ? (
<View className="mt-1 h-1 overflow-hidden rounded-full bg-border-subtle">
<View
className="h-full rounded-full bg-foreground-muted"
style={{ width: `${(magnitude / peak) * 100}%` }}
/>
</View>
) : null}
</View>
<Text className="text-base tabular-nums text-foreground">
{metric === "tokens"
? formatTokens(model.totalTokens)
: isModelCostUnknown(model)
? gt("Unpriced", { $context: "model with no known price" })
: formatUsd(model.costUsd)}
</Text>
<Text className="text-base tabular-nums text-foreground">{value}</Text>
</View>
))}
</View>
</SettingsSection>
);
})}
</View>
);
}

Expand Down
4 changes: 3 additions & 1 deletion apps/mobile/src/i18n/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -5090,10 +5090,12 @@
"c65e6cfd393d8dec": "Nach Typ",
"999c1e12be2b0b07": "Nach Geschwindigkeit",
"acdde9c11660b3e7": "{cost} Aufpreis",
"52eb4ae22e3de46b": "Nach Modell",
"ef85252c278cb404": "Aufschlüsselung",
"0f806caee7d50d39": "{share} der Tokens · keine bekannten Preise",
"fa8c94215417c702": "keine bekannten Preise · {tokens} Tokens",
"77798cfa0f392e89": "Ohne Preis",
"52d5050fe3b493be": "ID {id}",
"48fb19071dd12d24": "Teilweise ohne Preis",
"ab4208cfa3aa2c7c": [
"Einmal gezählt über Umgebungen mit gemeinsamem Transkriptverzeichnis:",
" ",
Expand Down
4 changes: 3 additions & 1 deletion apps/mobile/src/i18n/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -5091,10 +5091,12 @@
"c65e6cfd393d8dec": "By type",
"999c1e12be2b0b07": "By speed",
"acdde9c11660b3e7": "{cost} premium",
"52eb4ae22e3de46b": "By model",
"ef85252c278cb404": "Breakdown",
"0f806caee7d50d39": "{share} of tokens · no known rates",
"fa8c94215417c702": "no known rates · {tokens} tokens",
"77798cfa0f392e89": "Unpriced",
"52d5050fe3b493be": "ID {id}",
"48fb19071dd12d24": "Some unpriced",
"ab4208cfa3aa2c7c": [
"Counted once across environments sharing a transcript directory:",
" ",
Expand Down
4 changes: 3 additions & 1 deletion apps/mobile/src/i18n/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -5084,10 +5084,12 @@
"c65e6cfd393d8dec": "Por tipo",
"999c1e12be2b0b07": "Por velocidad",
"acdde9c11660b3e7": "{cost} de recargo",
"52eb4ae22e3de46b": "Por modelo",
"ef85252c278cb404": "Desglose",
"0f806caee7d50d39": "{share} de los tokens · sin tarifas conocidas",
"fa8c94215417c702": "sin tarifas conocidas · {tokens} tokens",
"77798cfa0f392e89": "Sin precio",
"52d5050fe3b493be": "ID {id}",
"48fb19071dd12d24": "Algunos sin precio",
"ab4208cfa3aa2c7c": [
"Contado una sola vez entre los entornos que comparten un directorio de transcripciones:",
" ",
Expand Down
4 changes: 3 additions & 1 deletion apps/mobile/src/i18n/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -5084,10 +5084,12 @@
"c65e6cfd393d8dec": "Par type",
"999c1e12be2b0b07": "Par vitesse",
"acdde9c11660b3e7": "{cost} de supplément",
"52eb4ae22e3de46b": "Par modèle",
"ef85252c278cb404": "Répartition",
"0f806caee7d50d39": "{share} des tokens · aucun tarif connu",
"fa8c94215417c702": "aucun tarif connu · {tokens} tokens",
"77798cfa0f392e89": "Sans prix",
"52d5050fe3b493be": "ID {id}",
"48fb19071dd12d24": "Certains sans prix",
"ab4208cfa3aa2c7c": [
"Compté une seule fois pour les environnements qui partagent un répertoire de transcriptions :",
" ",
Expand Down
4 changes: 3 additions & 1 deletion apps/mobile/src/i18n/translations/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -5066,10 +5066,12 @@
"c65e6cfd393d8dec": "種類別",
"999c1e12be2b0b07": "速度別",
"acdde9c11660b3e7": "プレミアム {cost}",
"52eb4ae22e3de46b": "モデル別",
"ef85252c278cb404": "内訳",
"0f806caee7d50d39": "トークンの {share} · 単価不明",
"fa8c94215417c702": "単価不明 · {tokens} トークン",
"77798cfa0f392e89": "価格不明",
"52d5050fe3b493be": "ID {id}",
"48fb19071dd12d24": "一部価格不明",
"ab4208cfa3aa2c7c": [
"文字起こしディレクトリを共有する環境間では 1 回だけカウントされます:",
" ",
Expand Down
4 changes: 3 additions & 1 deletion apps/mobile/src/i18n/translations/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -5070,10 +5070,12 @@
"c65e6cfd393d8dec": "유형별",
"999c1e12be2b0b07": "속도별",
"acdde9c11660b3e7": "프리미엄 {cost}",
"52eb4ae22e3de46b": "모델별",
"ef85252c278cb404": "분석",
"0f806caee7d50d39": "토큰의 {share} · 알려진 요율 없음",
"fa8c94215417c702": "알려진 요율 없음 · 토큰 {tokens}개",
"77798cfa0f392e89": "가격 없음",
"52d5050fe3b493be": "ID {id}",
"48fb19071dd12d24": "일부 가격 없음",
"ab4208cfa3aa2c7c": [
"같은 대화 기록 디렉터리를 공유하는 환경 간에는 한 번만 집계됨:",
" ",
Expand Down
4 changes: 3 additions & 1 deletion apps/mobile/src/i18n/translations/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -5084,10 +5084,12 @@
"c65e6cfd393d8dec": "Por tipo",
"999c1e12be2b0b07": "Por velocidade",
"acdde9c11660b3e7": "{cost} de adicional",
"52eb4ae22e3de46b": "Por modelo",
"ef85252c278cb404": "Detalhamento",
"0f806caee7d50d39": "{share} dos tokens · sem taxas conhecidas",
"fa8c94215417c702": "sem taxas conhecidas · {tokens} tokens",
"77798cfa0f392e89": "Sem preço",
"52d5050fe3b493be": "ID {id}",
"48fb19071dd12d24": "Alguns sem preço",
"ab4208cfa3aa2c7c": [
"Contado uma vez entre ambientes que compartilham um diretório de transcrições:",
" ",
Expand Down
4 changes: 3 additions & 1 deletion apps/mobile/src/i18n/translations/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -5163,10 +5163,12 @@
"c65e6cfd393d8dec": "По типу",
"999c1e12be2b0b07": "По скорости",
"acdde9c11660b3e7": "{cost} премиум",
"52eb4ae22e3de46b": "По модели",
"ef85252c278cb404": "Разбивка",
"0f806caee7d50d39": "{share} токенов · цены неизвестны",
"fa8c94215417c702": "цены неизвестны · {tokens} токенов",
"77798cfa0f392e89": "Без цены",
"52d5050fe3b493be": "ID {id}",
"48fb19071dd12d24": "Часть без цены",
"ab4208cfa3aa2c7c": [
"Учитывается один раз для окружений с общей папкой расшифровок:",
" ",
Expand Down
Loading
Loading