Merge remote-tracking branch 'origin/main' into t3bot/usage-environment-filters-merge
# Conflicts: # apps/web/src/components/usage/UsagePage.tsx
This commit is contained in:
commit
d0df7fd877
9 files changed
+511
-340
No files matched your search
@@ -160,6 +160,109 @@ it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves icon hrefs from object-literal route metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(
|
||||
cwd,
|
||||
"src/routes/__root.tsx",
|
||||
`export const Route = createRootRoute({
|
||||
head: () => ({
|
||||
links: [
|
||||
{ rel: "stylesheet", href: "/app.css" },
|
||||
{ rel: "icon", href: "/brand/logo.svg" },
|
||||
],
|
||||
}),
|
||||
});`,
|
||||
);
|
||||
yield* writeTextFile(cwd, "public/brand/logo.svg", "<svg>brand</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("public/brand/logo.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves object-literal icon metadata when href precedes rel", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(
|
||||
cwd,
|
||||
"src/root.tsx",
|
||||
`const links = [{ href: "/brand/logo.svg", rel: "shortcut icon" }];`,
|
||||
);
|
||||
yield* writeTextFile(cwd, "public/brand/logo.svg", "<svg>brand</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("public/brand/logo.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves object-literal icon metadata alongside nested objects", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(
|
||||
cwd,
|
||||
"src/root.tsx",
|
||||
`const links = [{ attributes: {}, rel: "icon", href: "/brand/logo.svg" }];`,
|
||||
);
|
||||
yield* writeTextFile(cwd, "public/brand/logo.svg", "<svg>brand</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("public/brand/logo.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips icon metadata without an href and keeps scanning", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(
|
||||
cwd,
|
||||
"src/root.tsx",
|
||||
`const links = [{ rel: "icon" }, { rel: "icon", href: "/brand/logo.svg" }];`,
|
||||
);
|
||||
yield* writeTextFile(cwd, "public/brand/logo.svg", "<svg>brand</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("public/brand/logo.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
// A large icon source with no icon metadata used to pin the server's event loop for
|
||||
// minutes: the object pattern was unanchored, so it restarted at every offset and
|
||||
// rescanned forward from each one. Anchoring keeps this proportional to file size.
|
||||
it.effect("scans large icon sources without an icon in reasonable time", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
// Mirrors a generated single-file build: large, brace-sparse, and no icon metadata.
|
||||
const filler = `<p>${"pokopia companion guide ".repeat(24)}</p>\n`;
|
||||
yield* writeTextFile(
|
||||
cwd,
|
||||
"index.html",
|
||||
`<!doctype html><html><head><title>guide</title></head><body>\n${filler.repeat(1200)}</body></html>`,
|
||||
);
|
||||
|
||||
const startedAt = performance.now();
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
const elapsedMs = performance.now() - startedAt;
|
||||
|
||||
expect(resolved).toBeNull();
|
||||
expect(elapsedMs).toBeLessThan(5_000);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns null when no icon is present", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
|
||||
@@ -55,10 +55,13 @@ const ICON_SOURCE_FILES = [
|
||||
] as const;
|
||||
|
||||
// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
|
||||
// The tag pattern is anchored on `<link`, so it only starts at real candidates. Object metadata
|
||||
// is matched by scanning brace-free runs instead of by one combined pattern: an unanchored
|
||||
// pattern restarts at every offset and rescans forward, which is quadratic on large sources.
|
||||
const LINK_ICON_HTML_RE =
|
||||
/<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
|
||||
const LINK_ICON_OBJ_RE =
|
||||
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
|
||||
const ICON_REL_RE = /\brel\s*:\s*["'](?:icon|shortcut icon)["']/i;
|
||||
const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i;
|
||||
|
||||
export class ProjectFaviconResolutionError extends Schema.TaggedErrorClass<ProjectFaviconResolutionError>()(
|
||||
"ProjectFaviconResolutionError",
|
||||
@@ -99,8 +102,13 @@ export class ProjectFaviconResolver extends Context.Service<
|
||||
function extractIconHref(source: string): string | null {
|
||||
const htmlMatch = source.match(LINK_ICON_HTML_RE);
|
||||
if (htmlMatch?.[1]) return htmlMatch[1];
|
||||
const objMatch = source.match(LINK_ICON_OBJ_RE);
|
||||
if (objMatch?.[1]) return objMatch[1];
|
||||
// Icon metadata counts when `rel` and `href` share a brace-free run, so a run holding `rel`
|
||||
// but no href falls through to the next one rather than ending the search.
|
||||
for (const run of source.split("}")) {
|
||||
if (!ICON_REL_RE.test(run)) continue;
|
||||
const hrefMatch = run.match(ICON_HREF_RE);
|
||||
if (hrefMatch?.[1]) return hrefMatch[1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -266,7 +266,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
aria-label={`Thread actions for ${activeThreadTitle}`}
|
||||
aria-haspopup="menu"
|
||||
onClick={openMenuFromTitle}
|
||||
className="group/thread-title inline-flex min-w-0 flex-1 cursor-pointer items-center gap-1 rounded-sm text-left focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
className="group/thread-title inline-flex min-w-0 cursor-pointer items-center gap-1 rounded-sm text-left focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
/>
|
||||
}
|
||||
>
|
||||
|
||||
@@ -8,11 +8,22 @@ describe("resolveClerkSignInProps", () => {
|
||||
expect(resolveClerkSignInProps(href, false)).toEqual({ forceRedirectUrl: href });
|
||||
});
|
||||
|
||||
it("omits the redirect override on packaged desktop", () => {
|
||||
expect(resolveClerkSignInProps("t3code://app/#/settings/general", true)).toEqual({});
|
||||
it("removes a Clerk virtual pathname and callback params while preserving the desktop route", () => {
|
||||
expect(
|
||||
resolveClerkSignInProps(
|
||||
"t3code://app/CLERK-ROUTER/VIRTUAL/sign-up?__clerk_status=complete#/settings/connections",
|
||||
true,
|
||||
),
|
||||
).toEqual({
|
||||
forceRedirectUrl: "t3code://app/#/settings/connections",
|
||||
signUpForceRedirectUrl: "t3code://app/#/settings/connections",
|
||||
});
|
||||
});
|
||||
|
||||
it("omits the redirect override on development desktop", () => {
|
||||
expect(resolveClerkSignInProps("t3code-dev://app/#/settings/general", true)).toEqual({});
|
||||
it("preserves a clean development desktop route", () => {
|
||||
expect(resolveClerkSignInProps("t3code-dev://app/#/settings/general", true)).toEqual({
|
||||
forceRedirectUrl: "t3code-dev://app/#/settings/general",
|
||||
signUpForceRedirectUrl: "t3code-dev://app/#/settings/general",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,19 @@
|
||||
export interface ClerkSignInProps {
|
||||
forceRedirectUrl?: string;
|
||||
signUpForceRedirectUrl?: string;
|
||||
}
|
||||
|
||||
// Clerk's native-app allowlist only authorizes the bare renderer root
|
||||
// (t3code://app/), which @clerk/electron's OAuth transport already supplies,
|
||||
// so any page-derived redirect override gets the whole sign-in request
|
||||
// rejected. On Electron, omit the override and let Clerk use its defaults.
|
||||
export function resolveClerkSignInProps(href: string, isElectron: boolean): ClerkSignInProps {
|
||||
if (isElectron) return {};
|
||||
if (isElectron) {
|
||||
// Electron routes through the hash, so reset any Clerk virtual pathname without losing the T3 page.
|
||||
const redirectUrl = new URL(href);
|
||||
redirectUrl.pathname = "/";
|
||||
redirectUrl.search = "";
|
||||
|
||||
return {
|
||||
forceRedirectUrl: redirectUrl.toString(),
|
||||
signUpForceRedirectUrl: redirectUrl.toString(),
|
||||
};
|
||||
}
|
||||
return { forceRedirectUrl: href };
|
||||
}
|
||||
@@ -555,9 +555,8 @@ export function ThemeLibrary({
|
||||
<h3 className="text-sm font-medium tracking-[-0.005em] text-foreground">Themes</h3>
|
||||
<div className="flex flex-wrap items-center justify-end gap-3">
|
||||
<Button
|
||||
className="h-7 rounded-md border border-border/70 bg-muted/30 px-2 text-xs font-medium text-foreground shadow-none hover:bg-accent/40"
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
openThemeEditor({
|
||||
editingThemeId: null,
|
||||
@@ -570,7 +569,7 @@ export function ThemeLibrary({
|
||||
<PlusIcon />
|
||||
Create theme
|
||||
</Button>
|
||||
<Button size="xs" variant="ghost" onClick={() => onImportOpenChange(true)}>
|
||||
<Button size="xs" variant="outline" onClick={() => onImportOpenChange(true)}>
|
||||
<UploadIcon />
|
||||
Import theme
|
||||
</Button>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { EnvironmentId, UsageProviderKind } from "@t3tools/contracts";
|
||||
import { useCanGoBack, useNavigate, useRouter } from "@tanstack/react-router";
|
||||
import { ArrowLeftIcon, CheckIcon, RefreshCwIcon, XIcon } from "lucide-react";
|
||||
import { CheckIcon, RefreshCwIcon, XIcon } from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { isElectron } from "../../env";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
|
||||
import { isEnvironmentUsageStillReporting } from "../../state/usageEnvironmentScope";
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
makeWindow,
|
||||
} from "@t3tools/shared/usageFormat";
|
||||
import { ScrollArea } from "../ui/scroll-area";
|
||||
import { SidebarInset } from "../ui/sidebar";
|
||||
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "../../workspaceTitlebar";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { UsageChartLegend, UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
|
||||
import { PROVIDER_COLOR, PROVIDER_LABEL, PROVIDER_MARK, PROVIDER_ORDER } from "./usageProviders";
|
||||
@@ -31,9 +33,6 @@ export function UsagePage() {
|
||||
const [metric, setMetric] = useState<UsageChartMetric>("cost");
|
||||
const [breakdown, setBreakdown] = useState<"model" | "day">("model");
|
||||
const [environmentFilter, setEnvironmentFilter] = useState<EnvironmentId | null>(null);
|
||||
const canGoBack = useCanGoBack();
|
||||
const navigate = useNavigate();
|
||||
const router = useRouter();
|
||||
|
||||
// Recomputed only when the window length changes, so a re-render does not
|
||||
// shift the range and refetch every environment.
|
||||
@@ -72,193 +71,259 @@ export function UsagePage() {
|
||||
const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
|
||||
|
||||
return (
|
||||
<ScrollArea className="h-full">
|
||||
<div className="mx-auto flex w-full max-w-6xl flex-col gap-8 px-6 py-6">
|
||||
<header className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Back"
|
||||
onClick={() => {
|
||||
if (canGoBack) {
|
||||
router.history.back();
|
||||
return;
|
||||
}
|
||||
void navigate({ to: "/" });
|
||||
}}
|
||||
className="mt-1 cursor-pointer rounded-md border border-border p-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ArrowLeftIcon className="size-3.5" />
|
||||
</button>
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-2xl font-semibold text-foreground">Usage</h1>
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
|
||||
{!isElectron && (
|
||||
<header
|
||||
className={cn(
|
||||
"workspace-topbar px-3 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5",
|
||||
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
|
||||
)}
|
||||
>
|
||||
<h1 className="text-sm font-medium text-foreground">Usage</h1>
|
||||
</header>
|
||||
)}
|
||||
|
||||
{isElectron && (
|
||||
<div
|
||||
className={cn(
|
||||
"drag-region flex h-[52px] shrink-0 items-center px-5 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none wco:h-[env(titlebar-area-height)] wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]",
|
||||
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
|
||||
)}
|
||||
>
|
||||
<h1 className="text-xs font-medium tracking-wide text-muted-foreground/70">Usage</h1>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<div className="mx-auto flex w-full max-w-6xl flex-col gap-8 px-6 py-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{formatDayShort(window.sinceDay)} to {formatDayShort(window.untilDay)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
<Select
|
||||
value={
|
||||
selectedEnvironmentId === null ? "all" : `environment:${selectedEnvironmentId}`
|
||||
}
|
||||
onValueChange={(value) => {
|
||||
if (value === null) return;
|
||||
setEnvironmentFilter(
|
||||
value === "all" ? null : (value.slice("environment:".length) as EnvironmentId),
|
||||
);
|
||||
}}
|
||||
items={[
|
||||
{ value: "all", label: "All environments" },
|
||||
...options.map((environment) => ({
|
||||
value: `environment:${environment.environmentId}`,
|
||||
label: environment.label,
|
||||
})),
|
||||
]}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-44" aria-label="Filter environments">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
<SelectItem value="all">All environments</SelectItem>
|
||||
{options.map((environment) => (
|
||||
<SelectItem
|
||||
key={environment.environmentId}
|
||||
value={`environment:${environment.environmentId}`}
|
||||
>
|
||||
{environment.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
<div className="flex overflow-hidden rounded-md border border-border">
|
||||
{WINDOW_OPTIONS.map((option) => (
|
||||
<button
|
||||
key={option.days}
|
||||
type="button"
|
||||
onClick={() => setWindowDays(option.days)}
|
||||
className={cn(
|
||||
"cursor-pointer px-3 py-1.5 text-xs",
|
||||
option.days === windowDays
|
||||
? "bg-muted text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
<Select
|
||||
value={
|
||||
selectedEnvironmentId === null ? "all" : `environment:${selectedEnvironmentId}`
|
||||
}
|
||||
onValueChange={(value) => {
|
||||
if (value === null) return;
|
||||
setEnvironmentFilter(
|
||||
value === "all"
|
||||
? null
|
||||
: (value.slice("environment:".length) as EnvironmentId),
|
||||
);
|
||||
}}
|
||||
items={[
|
||||
{ value: "all", label: "All environments" },
|
||||
...options.map((environment) => ({
|
||||
value: `environment:${environment.environmentId}`,
|
||||
label: environment.label,
|
||||
})),
|
||||
]}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={refresh}
|
||||
aria-label="Refresh usage"
|
||||
className="cursor-pointer rounded-md border border-border p-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<RefreshCwIcon className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{isPending || (usableEnvironmentCount === 0 && isPartial) ? (
|
||||
<>
|
||||
{environments.length > 1 ? <UsageDeviceStrip environments={environments} /> : null}
|
||||
<UsageSkeleton />
|
||||
</>
|
||||
) : options.length === 0 ? (
|
||||
<UsageEmptyState>Connect an environment to see usage.</UsageEmptyState>
|
||||
) : usableEnvironmentCount === 0 ? (
|
||||
<>
|
||||
<UsageCoverageNotice
|
||||
environments={environments}
|
||||
duplicateSources={merged.duplicateSources}
|
||||
staleEnvironments={merged.staleEnvironments}
|
||||
isPartial={isPartial}
|
||||
/>
|
||||
<UsageEmptyState>
|
||||
{selectedEnvironmentId === null
|
||||
? "No connected environment could report usage."
|
||||
: "This environment is unavailable for usage."}
|
||||
</UsageEmptyState>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<UsageCoverageNotice
|
||||
environments={environments}
|
||||
duplicateSources={merged.duplicateSources}
|
||||
staleEnvironments={merged.staleEnvironments}
|
||||
isPartial={isPartial}
|
||||
/>
|
||||
|
||||
{/* Cost first: the financial answer, then the provider split. */}
|
||||
<section className="grid gap-6 lg:grid-cols-[minmax(0,20rem)_minmax(0,1fr)]">
|
||||
{/* The summary follows the chart toggle, so the headline and the
|
||||
series are always reading the same units. */}
|
||||
<div className="flex flex-col gap-5">
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="text-xs tracking-wide text-muted-foreground uppercase">
|
||||
{metric === "cost" ? "Raw token cost" : "Processed tokens"}
|
||||
</span>
|
||||
<span className="text-4xl font-semibold text-foreground tabular-nums">
|
||||
{metric === "cost"
|
||||
? `${formatUsd(merged.costUsd)}*`
|
||||
: formatTokens(merged.totalTokens)}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{metric === "cost"
|
||||
? "* if billed at full API rate"
|
||||
: `Input, cache reads and output across ${formatCount(merged.sessions)} sessions.`}
|
||||
</span>
|
||||
<SelectTrigger size="sm" className="w-44" aria-label="Filter environments">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
<SelectItem value="all">All environments</SelectItem>
|
||||
{options.map((environment) => (
|
||||
<SelectItem
|
||||
key={environment.environmentId}
|
||||
value={`environment:${environment.environmentId}`}
|
||||
>
|
||||
{environment.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
<div className="flex overflow-hidden rounded-md border border-border">
|
||||
{WINDOW_OPTIONS.map((option) => (
|
||||
<button
|
||||
key={option.days}
|
||||
type="button"
|
||||
onClick={() => setWindowDays(option.days)}
|
||||
className={cn(
|
||||
"cursor-pointer px-3 py-1.5 text-xs",
|
||||
option.days === windowDays
|
||||
? "bg-muted text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={refresh}
|
||||
aria-label="Refresh usage"
|
||||
className="cursor-pointer rounded-md border border-border p-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<RefreshCwIcon className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{orderedProviders.map((provider) => {
|
||||
const share = metric === "cost" ? provider.costShare : provider.tokenShare;
|
||||
return (
|
||||
<div key={provider.provider} className="flex flex-col gap-1.5">
|
||||
<div className="flex items-baseline justify-between">
|
||||
<span className="flex items-center gap-2 text-sm text-foreground">
|
||||
<ProviderMark provider={provider.provider} className="size-4" />
|
||||
{PROVIDER_LABEL[provider.provider]}
|
||||
</span>
|
||||
<span className="text-sm text-foreground tabular-nums">
|
||||
{metric === "cost"
|
||||
? formatUsd(provider.costUsd)
|
||||
: formatTokens(provider.totalTokens)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-1 w-full overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
className="h-full"
|
||||
style={{
|
||||
width: `${(share * 100).toFixed(1)}%`,
|
||||
backgroundColor: PROVIDER_COLOR[provider.provider],
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{isPending || (usableEnvironmentCount === 0 && isPartial) ? (
|
||||
<>
|
||||
{environments.length > 1 ? <UsageDeviceStrip environments={environments} /> : null}
|
||||
<UsageSkeleton />
|
||||
</>
|
||||
) : options.length === 0 ? (
|
||||
<UsageEmptyState>Connect an environment to see usage.</UsageEmptyState>
|
||||
) : usableEnvironmentCount === 0 ? (
|
||||
<>
|
||||
<UsageCoverageNotice
|
||||
environments={environments}
|
||||
duplicateSources={merged.duplicateSources}
|
||||
staleEnvironments={merged.staleEnvironments}
|
||||
isPartial={isPartial}
|
||||
/>
|
||||
<UsageEmptyState>
|
||||
{selectedEnvironmentId === null
|
||||
? "No connected environment could report usage."
|
||||
: "This environment is unavailable for usage."}
|
||||
</UsageEmptyState>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<UsageCoverageNotice
|
||||
environments={environments}
|
||||
duplicateSources={merged.duplicateSources}
|
||||
staleEnvironments={merged.staleEnvironments}
|
||||
isPartial={isPartial}
|
||||
/>
|
||||
|
||||
{/* Cost first: the financial answer, then the provider split. */}
|
||||
<section className="grid gap-6 lg:grid-cols-[minmax(0,20rem)_minmax(0,1fr)]">
|
||||
{/* The summary follows the chart toggle, so the headline and the
|
||||
series are always reading the same units. */}
|
||||
<div className="flex flex-col gap-5">
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="text-xs tracking-wide text-muted-foreground uppercase">
|
||||
{metric === "cost" ? "Raw token cost" : "Processed tokens"}
|
||||
</span>
|
||||
<span className="text-4xl font-semibold text-foreground tabular-nums">
|
||||
{metric === "cost"
|
||||
? `${formatUsd(merged.costUsd)}*`
|
||||
: formatTokens(merged.totalTokens)}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{metric === "cost"
|
||||
? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
|
||||
: `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
|
||||
? "* if billed at full API rate"
|
||||
: `Input, cache reads and output across ${formatCount(merged.sessions)} sessions.`}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h2 className="text-sm font-medium text-foreground">
|
||||
Daily {metric === "tokens" ? "processed tokens" : "cost"}
|
||||
</h2>
|
||||
<div className="flex items-center gap-4">
|
||||
{orderedProviders.map((provider) => {
|
||||
const share = metric === "cost" ? provider.costShare : provider.tokenShare;
|
||||
return (
|
||||
<div key={provider.provider} className="flex flex-col gap-1.5">
|
||||
<div className="flex items-baseline justify-between">
|
||||
<span className="flex items-center gap-2 text-sm text-foreground">
|
||||
<ProviderMark provider={provider.provider} className="size-4" />
|
||||
{PROVIDER_LABEL[provider.provider]}
|
||||
</span>
|
||||
<span className="text-sm text-foreground tabular-nums">
|
||||
{metric === "cost"
|
||||
? formatUsd(provider.costUsd)
|
||||
: formatTokens(provider.totalTokens)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-1 w-full overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
className="h-full"
|
||||
style={{
|
||||
width: `${(share * 100).toFixed(1)}%`,
|
||||
backgroundColor: PROVIDER_COLOR[provider.provider],
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{metric === "cost"
|
||||
? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
|
||||
: `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h2 className="text-sm font-medium text-foreground">
|
||||
Daily {metric === "tokens" ? "processed tokens" : "cost"}
|
||||
</h2>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex overflow-hidden rounded-md border border-border">
|
||||
{(["cost", "tokens"] as const).map((option) => (
|
||||
<button
|
||||
key={option}
|
||||
type="button"
|
||||
onClick={() => setMetric(option)}
|
||||
className={cn(
|
||||
"cursor-pointer px-2.5 py-1 text-[10px] tracking-wide uppercase",
|
||||
option === metric
|
||||
? "bg-muted text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{option}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<UsageChartLegend />
|
||||
</div>
|
||||
</div>
|
||||
<UsageProviderChart days={days} daily={merged.daily} metric={metric} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="grid grid-cols-2 gap-px border-y border-border bg-border md:grid-cols-5">
|
||||
<Metric
|
||||
label="Processed tokens"
|
||||
value={formatTokens(merged.totalTokens)}
|
||||
detail={`${formatTokens(dailyAverage)} per active day`}
|
||||
/>
|
||||
<Metric
|
||||
label="Cached input"
|
||||
value={formatTokens(merged.cachedInputTokens)}
|
||||
detail={`${formatPercent(cachedShare)} of observed input`}
|
||||
/>
|
||||
<Metric
|
||||
label="Uncached input"
|
||||
value={formatTokens(merged.uncachedInputTokens)}
|
||||
detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
|
||||
/>
|
||||
<Metric
|
||||
label="Output"
|
||||
value={formatTokens(merged.outputTokens)}
|
||||
detail={`includes ${formatTokens(merged.reasoningTokens)} reasoning`}
|
||||
/>
|
||||
<Metric
|
||||
label="Cache savings"
|
||||
value={formatUsd(merged.costQuality.cacheSavingsUsd)}
|
||||
detail={
|
||||
merged.costUsd > 0
|
||||
? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw token cost`
|
||||
: "vs full input rates"
|
||||
}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 className="text-sm font-medium text-foreground">Breakdown</h2>
|
||||
<div className="flex overflow-hidden rounded-md border border-border">
|
||||
{(["cost", "tokens"] as const).map((option) => (
|
||||
{(["model", "day"] as const).map((option) => (
|
||||
<button
|
||||
key={option}
|
||||
type="button"
|
||||
onClick={() => setMetric(option)}
|
||||
onClick={() => setBreakdown(option)}
|
||||
className={cn(
|
||||
"cursor-pointer px-2.5 py-1 text-[10px] tracking-wide uppercase",
|
||||
option === metric
|
||||
option === breakdown
|
||||
? "bg-muted text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
@@ -267,160 +332,103 @@ export function UsagePage() {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<UsageChartLegend />
|
||||
</div>
|
||||
</div>
|
||||
<UsageProviderChart days={days} daily={merged.daily} metric={metric} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="grid grid-cols-2 gap-px border-y border-border bg-border md:grid-cols-5">
|
||||
<Metric
|
||||
label="Processed tokens"
|
||||
value={formatTokens(merged.totalTokens)}
|
||||
detail={`${formatTokens(dailyAverage)} per active day`}
|
||||
/>
|
||||
<Metric
|
||||
label="Cached input"
|
||||
value={formatTokens(merged.cachedInputTokens)}
|
||||
detail={`${formatPercent(cachedShare)} of observed input`}
|
||||
/>
|
||||
<Metric
|
||||
label="Uncached input"
|
||||
value={formatTokens(merged.uncachedInputTokens)}
|
||||
detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
|
||||
/>
|
||||
<Metric
|
||||
label="Output"
|
||||
value={formatTokens(merged.outputTokens)}
|
||||
detail={`includes ${formatTokens(merged.reasoningTokens)} reasoning`}
|
||||
/>
|
||||
<Metric
|
||||
label="Cache savings"
|
||||
value={formatUsd(merged.costQuality.cacheSavingsUsd)}
|
||||
detail={
|
||||
merged.costUsd > 0
|
||||
? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw token cost`
|
||||
: "vs full input rates"
|
||||
}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 className="text-sm font-medium text-foreground">Breakdown</h2>
|
||||
<div className="flex overflow-hidden rounded-md border border-border">
|
||||
{(["model", "day"] as const).map((option) => (
|
||||
<button
|
||||
key={option}
|
||||
type="button"
|
||||
onClick={() => setBreakdown(option)}
|
||||
className={cn(
|
||||
"cursor-pointer px-2.5 py-1 text-[10px] tracking-wide uppercase",
|
||||
option === breakdown
|
||||
? "bg-muted text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{option}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{breakdown === "model" ? (
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border text-left text-xs text-muted-foreground">
|
||||
<th className="py-2 font-normal">Model</th>
|
||||
<th className="py-2 text-right font-normal">Cost</th>
|
||||
<th className="py-2 text-right font-normal">Share</th>
|
||||
<th className="py-2 text-right font-normal">Tokens</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{merged.models.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={4} className="py-6 text-center text-muted-foreground">
|
||||
No activity in this window.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
merged.models.map((model) => (
|
||||
<tr
|
||||
key={`${model.provider}:${model.model}`}
|
||||
className="border-b border-border/50"
|
||||
>
|
||||
<td className="py-2 text-foreground">
|
||||
<span className="flex items-center gap-2">
|
||||
<ProviderMark provider={model.provider} className="size-3.5" />
|
||||
{model.model}
|
||||
</span>
|
||||
</td>
|
||||
<td className="py-2 text-right text-foreground tabular-nums">
|
||||
{formatUsd(model.costUsd)}
|
||||
</td>
|
||||
<td className="py-2 text-right text-muted-foreground tabular-nums">
|
||||
{formatPercent(model.costShare)}
|
||||
</td>
|
||||
<td className="py-2 text-right text-muted-foreground tabular-nums">
|
||||
{formatTokens(model.totalTokens)}
|
||||
</td>
|
||||
{breakdown === "model" ? (
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border text-left text-xs text-muted-foreground">
|
||||
<th className="py-2 font-normal">Model</th>
|
||||
<th className="py-2 text-right font-normal">Cost</th>
|
||||
<th className="py-2 text-right font-normal">Share</th>
|
||||
<th className="py-2 text-right font-normal">Tokens</th>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border text-left text-xs text-muted-foreground">
|
||||
<th className="py-2 font-normal">Day</th>
|
||||
{PROVIDER_ORDER.map((provider) => (
|
||||
<th key={provider} className="py-2 text-right font-normal">
|
||||
{PROVIDER_LABEL[provider]}
|
||||
</th>
|
||||
))}
|
||||
<th className="py-2 text-right font-normal">Total</th>
|
||||
<th className="py-2 text-right font-normal">Tokens</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{recentDays.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={5} className="py-6 text-center text-muted-foreground">
|
||||
No activity in this window.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
recentDays.map((day) => (
|
||||
<tr key={day.day} className="border-b border-border/50">
|
||||
<td className="py-2 text-foreground">{formatDayShort(day.day)}</td>
|
||||
{PROVIDER_ORDER.map((provider) => (
|
||||
<td
|
||||
key={provider}
|
||||
className="py-2 text-right text-muted-foreground tabular-nums"
|
||||
>
|
||||
{formatUsd(day.byProvider.get(provider)?.costUsd ?? 0)}
|
||||
</thead>
|
||||
<tbody>
|
||||
{merged.models.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={4} className="py-6 text-center text-muted-foreground">
|
||||
No activity in this window.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
merged.models.map((model) => (
|
||||
<tr
|
||||
key={`${model.provider}:${model.model}`}
|
||||
className="border-b border-border/50"
|
||||
>
|
||||
<td className="py-2 text-foreground">
|
||||
<span className="flex items-center gap-2">
|
||||
<ProviderMark provider={model.provider} className="size-3.5" />
|
||||
{model.model}
|
||||
</span>
|
||||
</td>
|
||||
<td className="py-2 text-right text-foreground tabular-nums">
|
||||
{formatUsd(model.costUsd)}
|
||||
</td>
|
||||
<td className="py-2 text-right text-muted-foreground tabular-nums">
|
||||
{formatPercent(model.costShare)}
|
||||
</td>
|
||||
<td className="py-2 text-right text-muted-foreground tabular-nums">
|
||||
{formatTokens(model.totalTokens)}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border text-left text-xs text-muted-foreground">
|
||||
<th className="py-2 font-normal">Day</th>
|
||||
{PROVIDER_ORDER.map((provider) => (
|
||||
<th key={provider} className="py-2 text-right font-normal">
|
||||
{PROVIDER_LABEL[provider]}
|
||||
</th>
|
||||
))}
|
||||
<td className="py-2 text-right text-foreground tabular-nums">
|
||||
{formatUsd(day.costUsd)}
|
||||
</td>
|
||||
<td className="py-2 text-right text-muted-foreground tabular-nums">
|
||||
{formatTokens(day.totalTokens)}
|
||||
</td>
|
||||
<th className="py-2 text-right font-normal">Total</th>
|
||||
<th className="py-2 text-right font-normal">Tokens</th>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</thead>
|
||||
<tbody>
|
||||
{recentDays.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={5} className="py-6 text-center text-muted-foreground">
|
||||
No activity in this window.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
recentDays.map((day) => (
|
||||
<tr key={day.day} className="border-b border-border/50">
|
||||
<td className="py-2 text-foreground">{formatDayShort(day.day)}</td>
|
||||
{PROVIDER_ORDER.map((provider) => (
|
||||
<td
|
||||
key={provider}
|
||||
className="py-2 text-right text-muted-foreground tabular-nums"
|
||||
>
|
||||
{formatUsd(day.byProvider.get(provider)?.costUsd ?? 0)}
|
||||
</td>
|
||||
))}
|
||||
<td className="py-2 text-right text-foreground tabular-nums">
|
||||
{formatUsd(day.costUsd)}
|
||||
</td>
|
||||
<td className="py-2 text-right text-muted-foreground tabular-nums">
|
||||
{formatTokens(day.totalTokens)}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</SidebarInset>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -129,4 +129,25 @@ describe("collectComposerInlineTokens", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("still collects a file link whose label is at the length cap", () => {
|
||||
const label = `${"a".repeat(508)}.tsx`;
|
||||
const tokens = collectComposerInlineTokens(`see [${label}](src/${label}) ok`);
|
||||
|
||||
expect(tokens).toHaveLength(1);
|
||||
expect(tokens[0]?.value).toBe(`src/${label}`);
|
||||
});
|
||||
|
||||
it("leaves a file link past the label cap as plain text", () => {
|
||||
const label = `${"a".repeat(509)}.tsx`;
|
||||
expect(collectComposerInlineTokens(`see [${label}](src/${label}) ok`)).toEqual([]);
|
||||
});
|
||||
|
||||
it("stays fast on unterminated bracket runs", () => {
|
||||
// Unbounded, the label body rescanned the rest of the text from every
|
||||
// whitespace: this input took seconds.
|
||||
const started = performance.now();
|
||||
expect(collectComposerInlineTokens(" [[".repeat(40_000))).toEqual([]);
|
||||
expect(performance.now() - started).toBeLessThan(1_000);
|
||||
});
|
||||
});
|
||||
@@ -20,7 +20,21 @@ export interface CollectComposerInlineTokensOptions {
|
||||
|
||||
const SKILL_TOKEN_REGEX = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s)/g;
|
||||
const MENTION_TOKEN_REGEX = /(^|\s)@(?:"((?:\\.|[^"\\])*)"|([^\s@"]+))(?=\s)/g;
|
||||
const FILE_LINK_TOKEN_REGEX = /(^|\s)\[((?:\\.|[^\]\\])*)\]\(([^)\s]+)\)(?=\s)/g;
|
||||
/**
|
||||
* The label body is bounded rather than `*`. Unbounded, every whitespace in
|
||||
* the composer is a candidate start: the engine scans the rest of the text for
|
||||
* a closing `]`, fails, and rescans from the next whitespace — quadratic on
|
||||
* input like " [[[[[…". A cap makes each attempt constant-bounded.
|
||||
*
|
||||
* Only a basename ever survives the `label !== basename` check below, so this
|
||||
* cannot reject a link a user could meaningfully write; the longest filename
|
||||
* any common filesystem allows is 255.
|
||||
*/
|
||||
const MAX_FILE_LINK_LABEL_LENGTH = 512;
|
||||
const FILE_LINK_TOKEN_REGEX = new RegExp(
|
||||
`(^|\\s)\\[((?:\\\\.|[^\\]\\\\]){0,${MAX_FILE_LINK_LABEL_LENGTH}})\\]\\(([^)\\s]+)\\)(?=\\s)`,
|
||||
"g",
|
||||
);
|
||||
const URI_SCHEME_REGEX = /^[A-Za-z][A-Za-z0-9+.-]*:/;
|
||||
const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/;
|
||||
// Autocomplete emits canonical file links, so ambiguous bare @scope/package text stays a package.
|
||||
|
||||
Reference in new issue
Block a user