AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(web): ai usage page, hidden until launch (#16988)
Louai Boumedieneb2080e13d89b
diff --git a/brain/knowledge/ai-intelligence/ai-usage-page.md b/brain/knowledge/ai-intelligence/ai-usage-page.mdnew file mode 100644index 00000000000..9c1a7e99c8f--- /dev/null+++ b/brain/knowledge/ai-intelligence/ai-usage-page.md@@ -0,0 +1,56 @@+---+icon: 📊+---++# AI Usage Page++The AI Center page (`/platform/ai/usage`) that answers one question: **where is my AI money going?** These choices came from a grill session on 2026-10-20 and shape every screen. Cloud and self-hosted Enterprise only — the read API does not exist on Community — and the page stays **hidden until launch**: reachable by URL, no sidebar entry and no global-search entry, the same way `/platform/ai/tiers` ships on main.++## Rules+- **Served by Autumn-copied data, not a live query.** The three endpoints read from our own Postgres copy of Autumn's usage, not Autumn itself — see [decision 000053](../decisions/000053-ai-usage-is-copied-from-autumn-into-our-postgres.md) for the why and its gotchas (ids Autumn drops as null, the copy's paging deadline). A platform with no billing connection has `trackingSince: null` forever.+- **One dollar unit.** Credits are converted at their dollar value; credits only appear as a note ("Includes 6,479 credits"). Never two units side by side.+- **Three scopes, one page.** A scope select whose options each carry an icon and a one-line description, in this order: **All** · **Production** (the default) · **Testing** (flow builder Test step and agent builder). No amounts on it. The whole page follows it. No separate testing section, never a toggle switch.+- **Controls sit in the header, right of the title**, on every usage page: scope select and period select (labels only, no date ranges), both styled like outline buttons. No export on the page.+- **Every row has two lines, so all cards share one row height.** Line two is the parent (a flow's project, a model's or key's provider), a project's flow and agent counts, or "Billed on your plan" for credits. Every key row keeps the same right-hand button slot, so the bars line up: external dashboard, or billing for credits.+- **No project spend limits.** Dropped on 2026-10-21 to keep the feature simple to build and maintain: no cap, no limits card, no Set limit dialog.+- **Credits are always "Activepieces credits" with the Activepieces logo**, wherever the analytics mention them.+- **See all is a list card, not a data table.** Search sits inside the card. Column headers are quiet text that sorts on click, with an arrow only on the active column. Numbers are right-aligned, and the name column takes the free width. The share bar sits under the name. Change, calls and tokens hide on small screens. Pagination is page by page: "1–25 of 134" on the left, previous / "Page 1 of 6" / next on the right, back to page 1 on search or sort. A "Show more" button was tried and dropped.+- **Exact vs estimated stays out of the headline.** It shows only on a key's detail page (reported by provider vs estimated from list prices, plus the provider dashboard link), and as one footnote on the overview.+- **Overview, then drill down.** Every item opens its own detail page (`/platform/ai/usage/:dimension/:id`), and every card has See all (`/platform/ai/usage/:dimension`). Period and scope ride in the URL.+- **Served by three endpoints, one cached SQL each:** `/v1/ai-usage/overview`, `/items?dimension`, `/items/:dimension/:id`. Spend is the `spendUsd` column frozen at write (managed = what we bill, own key = reported cost or list-price estimate). Storage is our own `ai_usage_5m` (3 days) + `ai_usage_daily` (13 months); Autumn is the billing truth only, not the analytics store.+- **Costs are marked as estimates where the money is, not in the subtitle.** A quiet "Estimated" link sits next to the hero's Spend label (hidden for calls and tokens, which are exact) and opens a "Why these numbers are estimates" popover: providers mostly return tokens, not cost; discounts, caching, batch rates and price changes shift the real bill; reported costs are used as is; Activepieces credits are exact; the provider dashboard is the billing truth. Putting the caveat first in the page header made the whole page read as untrustworthy (dropped 2026-10-21).+- **Empty overview is the real page at zero, not a splash.** Tiles read $0.00 and 0, the chart is a flat line, the donut is an empty grey ring, and cards show their small empty state. One slim note bar on top says why: never used → "No AI spend yet. It shows up a few minutes after the first AI step, agent run or chat message."; empty only for these filters → names the scope and period and offers "Show last 90 days" and "Include testing" / "Include production". A third state exists for self-hosted Enterprise with no billing connection (`trackingSince === null`): "AI usage isn't available on this install", with a one-line why — usage data comes from the billing connection, which the install does not have. List and detail pages use a compact left-aligned card with the same copy and buttons. Never link to provider setup from here. A centred splash and a ghost-preview panel were tried and dropped. The read API's has-any-usage flag (`history.hasAnyUsage`) tells never-used apart from filtered-empty (`usage-empty.tsx`).+- **Loading looks like the page.** Every surface is the real white card with grey bars inside it in the shape of its content: tiles, the hero with one block for the chart, the donut, and the list rows with their share bars. Every usage page has its own: overview, see-all list (search, header, rows), and detail (tiles, hero, donut for projects and agents, one card per related list). Never draw bare grey blocks in place of cards (`usage-skeletons.tsx`).+- **The title is the breadcrumb.** List: "AI usage / Users". Detail: "AI usage / Users / Maya Chen", whatever page you came from, so one click reaches the list. There is no back link above the title and no type badge; the period and scope carry over in every crumb.+- **One detail template.** Header + the same chart + top 5 of the *other* dimensions + one extra card per type: project → spend with its flow and agent counts, flow → runs and cost per run, key → reported vs estimated, model → list price. A flow detail stops at flow level; there is no per-step split. A detail page with zero calls and zero previous spend shows the empty card but keeps the item's name in the breadcrumb.++- **"Previous period" means the same span right before**, except month views: "This month" and "Last month" compare with the same days of the month before (Oct 1–20 vs Sep 1–20). The chart legend reads its ranges straight from the read API's `ranges` field (not re-derived from chart point labels), since that is the only place the month-truncation rule is computed correctly.++- **Never compare against a period that isn't fully tracked.** If tracking started after the previous period began, every change % (hero, cards, lists) is hidden and the hero says so; a partial comparison would show fake growth like +400%. If tracking started inside the current period, the chart starts at that date and a note says "covers 25 of 90 days".++- **Every bar says what it is a share of.** Overview bars are a share of all AI spend in the period; detail-page bars are a share of that item's spend. Each bar shows its % and a tooltip that names the whole.++## Data hierarchy+- **Root: the platform**, which is the bill. Scope (Production / Testing / All) and period filter the whole page; they are not levels.+- **Tree 1, where the money is spent:** platform → project → flows · agents · chat by user. Project is the parent because project admins and ownership live there.+- **Tree 2, what it is spent on:** platform → provider → key → model. Keys are platform-owned and shared across projects, so they never sit under a project.+- **Side views, not levels:** user (who; only chat and agent runs have one) and source (what kind of work, an overlay on tree 1).+- **Detail pages pivot to the other tree:** a flow shows its models and keys, and a key shows its projects and flows.+- **A Run Agent step counts under both its flow and its agent**, marked Shared, so flows + agents can add up to more than the project total. Decided 2026-10-20. A two-tree overview layout was tried as "Usage v2" and dropped the same day: the overview keeps flat top-5 cards, and the trees only shape the detail-page pivot.++## Page anatomy+1. Tiles: a pace tile that follows the period (1h–24h → daily run rate; 7–90 days and last month → average per day; this month → month-end forecast with the date and daily pace it is based on), AI calls, tokens. Never label a projection as an average. The pace tile's average-per-day and forecast are computed client-side from the totals, the history's `currentCoverage` and the exact `ranges` timestamps — the history's `coveredDays`/`periodDays` are whole-day counts for the tracking-coverage note only, too coarse for sub-day periods.+2. Hero: total for the period, change vs the previous period, line chart (this period solid, previous dashed), metric switch Spend · Calls · Tokens.+3. Bento of cards in three full rows, broad to narrow: spend by source (donut, two columns) · projects / flows · agents · users / providers & keys · models, half the width each. What kind of work spends, then which team, then which flow, agent or person, then which key or model pays. Card rows stay quiet: name and parent on the left, the amount on the right, a thin share bar underneath. The share % is only in the bar's hover tooltip. A bar-behind-the-row layout was tried and dropped on 2026-10-20. Change % lives on the hero, the see-all list and the detail page, not on card rows. There is no "biggest changes" card.+4. The cost footnote.++## Gotchas+- **There is no list filtered by a parent item.** `/v1/ai-usage/items` only lists a whole dimension for the platform, so a related card on a detail page links to the platform-wide list and says so ("All flows on the platform"). A real "this project's flows" list needs a parent filter on the read API first.+- An item's `name` is `null` for a deleted entity, and also for three sentinel ids that are never real rows: `no-project` (platform-level chat with no project), `activepieces-credits` (the managed-credits "key"), and `unknown-<provider>` (a key that was deleted but still has usage). The UI tells these apart by id, not by a flag — see `usageAdapters.itemDisplayName` in `usage-tab/usage-adapters.ts`.+- A key or model item's `parent` field is never set by the read API (name lookup has no parent column for keys, and models are not looked up by name at all) — their subtitle is the provider's display name instead, reused from `SUPPORTED_AI_PROVIDERS` in `packages/web/src/features/agents/ai-providers.ts`.+- A model's `name` is always the raw `modelId`, never `null` — only project/flow/agent/user/key can show a "Deleted …" name.++## Key files+- `packages/web/src/app/routes/platform/setup/ai/usage-tab` — the page, cards and the API-to-view adapters (`usage-adapters.ts`, `usage-format.ts`).+- `packages/web/src/features/ai-usage` — the read-API client and the `useUsageOverview` / `useUsageItems` / `useUsageDetail` hooks.+- `packages/server/api/src/app/ai/usage/ai-usage-read.service.ts` — the three cached, grouping-sets queries behind the endpoints.diff --git a/brain/knowledge/ai-intelligence/index.md b/brain/knowledge/ai-intelligence/index.mdindex 197d43e1b00..298ab1c35ec 100644--- a/brain/knowledge/ai-intelligence/index.md+++ b/brain/knowledge/ai-intelligence/index.md@@ -39,6 +39,7 @@ The per-project endpoint that exposes Activepieces tools to an external AI assis- **Model Picker** — the builder's tier / credits / key picker and its options endpoint- **MCP Server** — the per-project endpoint, tool exposure, visibility rules- **AI & MCP** — how the AI and MCP surfaces fit together+- **AI Usage Page** — the `/platform/ai/usage` spend dashboard, hidden until launch, Cloud and EE only- **Shipping Behind a Flag** — merging unfinished AI work, turned on for a test group only## Relateddiff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex f5acf08205f..b6a7a5a4784 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -3585,5 +3585,126 @@"1 min ago": "1 min ago","{count} mins ago": "{count} mins ago","1 hour ago": "1 hour ago",- "{count} hours ago": "{count} hours ago"+ "{count} hours ago": "{count} hours ago",+ "A projection, not money spent": "A projection, not money spent",+ "AI calls": "AI calls",+ "AI usage": "AI usage",+ "AI usage isn't available on this install": "AI usage isn't available on this install",+ "Across {period}": "Across {period}",+ "Activepieces": "Activepieces",+ "Activepieces credits": "Activepieces credits",+ "Activepieces credits are always exact.": "Activepieces credits are always exact.",+ "At the pace of the {period}, for a full day": "At the pace of the {period}, for a full day",+ "Average across the period": "Average across the period",+ "Average per day": "Average per day",+ "Bar chart": "Bar chart",+ "Billed on your plan": "Billed on your plan",+ "Calls": "Calls",+ "Compare these numbers with your provider": "Compare these numbers with your provider",+ "Cost per run": "Cost per run",+ "Cost the provider sent back with each call": "Cost the provider sent back with each call",+ "Credits are billed on your plan": "Credits are billed on your plan",+ "Daily run rate": "Daily run rate",+ "Deleted agent": "Deleted agent",+ "Deleted flow": "Deleted flow",+ "Deleted key": "Deleted key",+ "Deleted model": "Deleted model",+ "Deleted user": "Deleted user",+ "Discounts, cached tokens, batch rates and price changes on your account can make your real bill a few percent different.": "Discounts, cached tokens, batch rates and price changes on your account can make your real bill a few percent different.",+ "Estimated": "Estimated",+ "Flow AI steps": "Flow AI steps",+ "Flow steps, Run Agent steps, agents, chat and knowledge base each get a slice once they use AI.": "Flow steps, Run Agent steps, agents, chat and knowledge base each get a slice once they use AI.",+ "For billing, your provider's own dashboard is the source of truth.": "For billing, your provider's own dashboard is the source of truth.",+ "Include production": "Include production",+ "Include testing": "Include testing",+ "Includes {credits} Activepieces credits": "Includes {credits} Activepieces credits",+ "Input · output": "Input · output",+ "It shows up a few minutes after the first AI step, agent run or chat message.": "It shows up a few minutes after the first AI step, agent run or chat message.",+ "Last 12 hours": "Last 12 hours",+ "Last 24 hours": "Last 24 hours",+ "Last 6 hours": "Last 6 hours",+ "Last 90 days": "Last 90 days",+ "Last hour": "Last hour",+ "Last month": "Last month",+ "Line chart": "Line chart",+ "List price per 1M tokens": "List price per 1M tokens",+ "Live flows, agents and chat": "Live flows, agents and chat",+ "Month-end forecast": "Month-end forecast",+ "Most AI providers send back how many tokens a call used, not what it cost. We multiply those tokens by the model’s list price.": "Most AI providers send back how many tokens a call used, not what it cost. We multiply those tokens by the model’s list price.",+ "No AI spend in this view.": "No AI spend in this view.",+ "No AI spend yet.": "No AI spend yet.",+ "No full previous period to compare yet": "No full previous period to compare yet",+ "No list price, so calls count as unpriced": "No list price, so calls count as unpriced",+ "No project (platform chat)": "No project (platform chat)",+ "No spend for this {type} in this period": "No spend for this {type} in this period",+ "No usage from {items}": "No usage from {items}",+ "No {items} match \"{query}\"": "No {items} match \"{query}\"",+ "No {item} spend in this period": "No {item} spend in this period",+ "Nothing ran in this period. Try a longer period or All.": "Nothing ran in this period. Try a longer period or All.",+ "Nothing used AI in {scope} for {period}.": "Nothing used AI in {scope} for {period}.",+ "Open billing": "Open billing",+ "Open dashboard": "Open dashboard",+ "Open provider dashboard": "Open provider dashboard",+ "Period": "Period",+ "Previous period": "Previous period",+ "Production": "Production",+ "Production and testing together": "Production and testing together",+ "Projected by {date} · {amount} a day so far": "Projected by {date} · {amount} a day so far",+ "Provider dashboard": "Provider dashboard",+ "Providers & keys": "Providers & keys",+ "Real spend, spread evenly": "Real spend, spread evenly",+ "Reported by provider": "Reported by provider",+ "Run Agent steps": "Run Agent steps",+ "Runs that made at least one AI call": "Runs that made at least one AI call",+ "Search {items}": "Search {items}",+ "See all": "See all",+ "See all {items}": "See all {items}",+ "Show last 90 days": "Show last 90 days",+ "Spend": "Spend",+ "Spend by source": "Spend by source",+ "Spend so far this month, divided by the days so far, times the days in the month. It moves as the month goes on.": "Spend so far this month, divided by the days so far, times the days in the month. It moves as the month goes on.",+ "Test runs from the builders": "Test runs from the builders",+ "Testing": "Testing",+ "This month": "This month",+ "This period": "This period",+ "Tokens": "Tokens",+ "Tokens times list price, where the provider sent no cost": "Tokens times list price, where the provider sent no cost",+ "Total spend in this period divided by its number of days.": "Total spend in this period divided by its number of days.",+ "Tracking started {date}, so this covers {covered} of {total} days": "Tracking started {date}, so this covers {covered} of {total} days",+ "Unknown {provider} key": "Unknown {provider} key",+ "Usage data comes from your billing connection, which this install does not have.": "Usage data comes from your billing connection, which this install does not have.",+ "Usage scope": "Usage scope",+ "Usage tracking started after the previous period began, so a change % would be wrong. It shows up once a full previous period is tracked.": "Usage tracking started after the previous period began, so a change % would be wrong. It shows up once a full previous period is tracked.",+ "What a full day would cost if spend kept the pace of this period. Short periods swing a lot, so read it as a rough rate.": "What a full day would cost if spend kept the pace of this period. Short periods swing a lot, so read it as a rough rate.",+ "When a provider does send the exact cost, we use it as is. Open a key to see how much was reported and how much was estimated.": "When a provider does send the exact cost, we use it as is. Open a key to see how much was reported and how much was estimated.",+ "Where your AI spend goes across flows, agents and chat.": "Where your AI spend goes across flows, agents and chat.",+ "Why these numbers are estimates": "Why these numbers are estimates",+ "Your bill": "Your bill",+ "not tracked yet": "not tracked yet",+ "vs previous 12 hours": "vs previous 12 hours",+ "vs previous 24 hours": "vs previous 24 hours",+ "vs previous 30 days": "vs previous 30 days",+ "vs previous 6 hours": "vs previous 6 hours",+ "vs previous 7 days": "vs previous 7 days",+ "vs previous 90 days": "vs previous 90 days",+ "vs previous hour": "vs previous hour",+ "vs same days last month": "vs same days last month",+ "vs the month before": "vs the month before",+ "{amount} across {items}": "{amount} across {items}",+ "{amount} of this comes from Run Agent steps, so it also counts under {other}.": "{amount} of this comes from Run Agent steps, so it also counts under {other}.",+ "{cost} per call on average": "{cost} per call on average",+ "{count, plural, =1 {1 agent} other {# agents}}": "{count, plural, =1 {1 agent} other {# agents}}",+ "{count, plural, =1 {1 key} other {# keys}}": "{count, plural, =1 {1 key} other {# keys}}",+ "{count, plural, =1 {1 model} other {# models}}": "{count, plural, =1 {1 model} other {# models}}",+ "{count, plural, =1 {1 user} other {# users}}": "{count, plural, =1 {1 user} other {# users}}",+ "{flows, plural, =1 {1 flow} other {# flows}} · {agents, plural, =1 {1 agent} other {# agents}}": "{flows, plural, =1 {1 flow} other {# flows}} · {agents, plural, =1 {1 agent} other {# agents}}",+ "{name} spend": "{name} spend",+ "{range}, partly tracked": "{range}, partly tracked",+ "{share} of all AI spend in this period": "{share} of all AI spend in this period",+ "{share} of input served from cache": "{share} of input served from cache",+ "{share} of {whole}": "{share} of {whole}",+ "{shown} of {total}": "{shown} of {total}",+ "Only the top {count} by spend are listed, so search and pages cover these only.": "Only the top {count} by spend are listed, so search and pages cover these only.",+ "What these calls used of your Activepieces credits": "What these calls used of your Activepieces credits",+ "All {items} on the platform": "All {items} on the platform"}diff --git a/packages/web/src/app/routes/platform-routes.tsx b/packages/web/src/app/routes/platform-routes.tsxindex 3c37dee5d29..c800e240d28 100644--- a/packages/web/src/app/routes/platform-routes.tsx+++ b/packages/web/src/app/routes/platform-routes.tsx@@ -111,6 +111,7 @@ const AI_TAB_PATHS = {providers: '',capabilities: 'capabilities',tiers: 'tiers',+ usage: 'usage',};const PIECES_TAB_PATHS = { pieces: '', 'piece-sets': 'piece-sets' };@@ -207,6 +208,54 @@ export const platformRoutes = [</PlatformLayout>),},+ {+ path: '/platform/ai/usage',+ element: (+ <PlatformLayout>+ <PageTitle title="AI Usage">+ <LegacyTabRedirect basePath="/platform/ai" tabPaths={AI_TAB_PATHS}>+ <PlanFeatureSample feature="aiProviders">+ <SuspenseWrapper>+ <AIProvidersPage section="usage" />+ </SuspenseWrapper>+ </PlanFeatureSample>+ </LegacyTabRedirect>+ </PageTitle>+ </PlatformLayout>+ ),+ },+ {+ path: '/platform/ai/usage/:dimension',+ element: (+ <PlatformLayout>+ <PageTitle title="AI Usage">+ <LegacyTabRedirect basePath="/platform/ai" tabPaths={AI_TAB_PATHS}>+ <PlanFeatureSample feature="aiProviders">+ <SuspenseWrapper>+ <AIProvidersPage section="usage-list" />+ </SuspenseWrapper>+ </PlanFeatureSample>+ </LegacyTabRedirect>+ </PageTitle>+ </PlatformLayout>+ ),+ },+ {+ path: '/platform/ai/usage/:dimension/:id',+ element: (+ <PlatformLayout>+ <PageTitle title="AI Usage">+ <LegacyTabRedirect basePath="/platform/ai" tabPaths={AI_TAB_PATHS}>+ <PlanFeatureSample feature="aiProviders">+ <SuspenseWrapper>+ <AIProvidersPage section="usage-detail" />+ </SuspenseWrapper>+ </PlanFeatureSample>+ </LegacyTabRedirect>+ </PageTitle>+ </PlatformLayout>+ ),+ },{path: '/platform/mcp',element: (diff --git a/packages/web/src/app/routes/platform/setup/ai/index.tsx b/packages/web/src/app/routes/platform/setup/ai/index.tsxindex ba1480e702f..42a9749a8e5 100644--- a/packages/web/src/app/routes/platform/setup/ai/index.tsx+++ b/packages/web/src/app/routes/platform/setup/ai/index.tsx@@ -7,6 +7,9 @@ import { flagsHooks } from '@/hooks/flags-hooks';import { CapabilitiesTab } from './capabilities-tab';import { ProvidersTab } from './providers-tab';import { TiersTab } from './tiers-tab';+import { UsageTab } from './usage-tab';+import { UsageDetailPage } from './usage-tab/usage-detail-page';+import { UsageListPage } from './usage-tab/usage-list-page';export default function AIProvidersPage({ section }: AIProvidersPageProps) {return <AICenter section={section} />;@@ -15,7 +18,13 @@ export default function AIProvidersPage({ section }: AIProvidersPageProps) {function AICenter({ section }: { section: AISection }) {const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);- if (section === 'capabilities' && edition === ApEdition.COMMUNITY) {+ if (+ (section === 'capabilities' ||+ section === 'usage' ||+ section === 'usage-list' ||+ section === 'usage-detail') &&+ edition === ApEdition.COMMUNITY+ ) {return <Navigate to="/platform/ai" replace />;}@@ -25,6 +34,12 @@ function AICenter({ section }: { section: AISection }) {<ProvidersTab />) : section === 'tiers' ? (<TiersTab />+ ) : section === 'usage' ? (+ <UsageTab />+ ) : section === 'usage-list' ? (+ <UsageListPage />+ ) : section === 'usage-detail' ? (+ <UsageDetailPage />) : (<CapabilitiesTab />)}@@ -32,7 +47,13 @@ function AICenter({ section }: { section: AISection }) {);}-type AISection = 'providers' | 'capabilities' | 'tiers';+type AISection =+ | 'providers'+ | 'capabilities'+ | 'tiers'+ | 'usage'+ | 'usage-list'+ | 'usage-detail';type AIProvidersPageProps = {section: AISection;diff --git a/packages/web/src/app/routes/platform/setup/ai/usage-tab/index.tsx b/packages/web/src/app/routes/platform/setup/ai/usage-tab/index.tsxnew file mode 100644index 00000000000..e39cfd7e04c--- /dev/null+++ b/packages/web/src/app/routes/platform/setup/ai/usage-tab/index.tsx@@ -0,0 +1,256 @@+import { isNil } from '@activepieces/core-utils';+import {+ AiUsageHistory,+ AiUsageOverview,+ AiUsagePeriod,+ AiUsageRanges,+ AiUsageTotals,+} from '@activepieces/shared';+import { t } from 'i18next';+import { CalendarRange, Gauge, Hash, TrendingUp, Type } from 'lucide-react';++import { AdminPageHeader, StatCard, StatGrid } from '@/app/components/admin';+import { DataFetchErrorState } from '@/components/custom/data-fetch-error-state';+import { aiUsageHooks } from '@/features/ai-usage';++import { usageAdapters } from './usage-adapters';+import { UsageEmptyNote } from './usage-empty';+import { usageFormat } from './usage-format';+import {+ UsageHeaderControls,+ UsageView,+ useUsageView,+} from './usage-header-controls';+import { UsageHero } from './usage-hero';+import { UsageOverviewSkeleton } from './usage-skeletons';+import { UsageSourceDonut } from './usage-source-donut';+import { UsageTopList } from './usage-top-list';++export function UsageTab() {+ const view = useUsageView();+ const { data, isLoading, isError, refetch } = aiUsageHooks.useUsageOverview({+ period: view.period,+ scope: view.scope,+ });+ return (+ <>+ <AdminPageHeader+ title={t('AI usage')}+ description={t(+ 'Where your AI spend goes across flows, agents and chat.',+ )}+ >+ <UsageHeaderControls view={view} />+ </AdminPageHeader>+ <UsageBody+ view={view}+ data={data}+ isLoading={isLoading}+ isError={isError}+ onRetry={refetch}+ />+ </>+ );+}++function UsageBody({+ view,+ data,+ isLoading,+ isError,+ onRetry,+}: {+ view: UsageView;+ data: AiUsageOverview | undefined;+ isLoading: boolean;+ isError: boolean;+ onRetry: () => unknown;+}) {+ if (isError) {+ return <DataFetchErrorState entity={t('AI usage')} onRetry={onRetry} />;+ }+ if (isLoading || isNil(data)) {+ return <UsageOverviewSkeleton />;+ }+ const { totals, history, ranges, top } = data;+ return (+ <>+ {totals.calls === 0 && <UsageEmptyNote view={view} history={history} />}+ <StatGrid columns={3}>+ <PaceTile+ view={view}+ totals={totals}+ ranges={ranges}+ history={history}+ />+ <StatCard+ label={t('AI calls')}+ icon={<Hash />}+ value={usageFormat.whole(totals.calls)}+ hint={t('{cost} per call on average', {+ cost: usageFormat.usd(+ totals.calls === 0 ? 0 : totals.spendUsd / totals.calls,+ ),+ })}+ />+ <StatCard+ label={t('Tokens')}+ icon={<Type />}+ value={usageFormat.compact(totals.tokens)}+ hint={+ totals.tokens === 0+ ? undefined+ : t('{share} of input served from cache', {+ share: usageFormat.percent(totals.cacheShare),+ })+ }+ />+ </StatGrid>++ <UsageHero+ series={usageAdapters.seriesToPoints({ series: data.series })}+ period={view.period}+ ranges={ranges}+ history={history}+ note={usageAdapters.creditsNote({+ managedCredits: totals.managedCredits,+ })}+ />++ <div className="grid grid-cols-1 gap-4 lg:grid-cols-12">+ <UsageSourceDonut className="lg:col-span-8" sources={data.bySource} />+ <UsageTopList+ className="lg:col-span-4"+ dimension="project"+ items={top.project}+ totalUsd={totals.spendUsd}+ search={view.search}+ />+ <UsageTopList+ className="lg:col-span-4"+ dimension="flow"+ items={top.flow}+ totalUsd={totals.spendUsd}+ search={view.search}+ />+ <UsageTopList+ className="lg:col-span-4"+ dimension="agent"+ items={top.agent}+ totalUsd={totals.spendUsd}+ search={view.search}+ />+ <UsageTopList+ className="lg:col-span-4"+ dimension="user"+ items={top.user}+ totalUsd={totals.spendUsd}+ search={view.search}+ />+ <UsageTopList+ className="lg:col-span-6"+ dimension="key"+ items={top.key}+ totalUsd={totals.spendUsd}+ search={view.search}+ />+ <UsageTopList+ className="lg:col-span-6"+ dimension="model"+ items={top.model}+ totalUsd={totals.spendUsd}+ search={view.search}+ />+ </div>+ </>+ );+}++function PaceTile({+ view,+ totals,+ ranges,+ history,+}: {+ view: UsageView;+ totals: AiUsageTotals;+ ranges: AiUsageRanges;+ history: AiUsageHistory;+}) {+ const pace = usageAdapters.paceOf({+ totals,+ ranges,+ history,+ period: view.period,+ });+ if (view.period === 'this-month' && pace.forecastUsd !== undefined) {+ return (+ <StatCard+ label={t('Month-end forecast')}+ icon={<TrendingUp />}+ info={+ <PaceInfo+ title={t('A projection, not money spent')}+ body={t(+ 'Spend so far this month, divided by the days so far, times the days in the month. It moves as the month goes on.',+ )}+ />+ }+ value={usageFormat.usd(pace.forecastUsd)}+ hint={t('Projected by {date} · {amount} a day so far', {+ date: usageAdapters.monthEndDateLabel({ iso: ranges.current.start }),+ amount: usageFormat.usd(pace.avgPerDayUsd),+ })}+ />+ );+ }+ if (SHORT_PERIODS.includes(view.period)) {+ return (+ <StatCard+ label={t('Daily run rate')}+ icon={<Gauge />}+ info={+ <PaceInfo+ title={t('A projection, not money spent')}+ body={t(+ 'What a full day would cost if spend kept the pace of this period. Short periods swing a lot, so read it as a rough rate.',+ )}+ />+ }+ value={usageFormat.usd(pace.avgPerDayUsd)}+ hint={t('At the pace of the {period}, for a full day', {+ period: usageFormat+ .periodLabel({ period: view.period })+ .toLowerCase(),+ })}+ />+ );+ }+ return (+ <StatCard+ label={t('Average per day')}+ icon={<CalendarRange />}+ info={+ <PaceInfo+ title={t('Real spend, spread evenly')}+ body={t('Total spend in this period divided by its number of days.')}+ />+ }+ value={usageFormat.usd(pace.avgPerDayUsd)}+ hint={t('Across {period}', {+ period: usageFormat.periodLabel({ period: view.period }).toLowerCase(),+ })}+ />+ );+}++function PaceInfo({ title, body }: { title: string; body: string }) {+ return (+ <span className="flex flex-col gap-1">+ <span className="font-medium">{title}</span>+ <span className="opacity-80">{body}</span>+ </span>+ );+}++const SHORT_PERIODS: AiUsagePeriod[] = ['1h', '6h', '12h', '24h'];diff --git a/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-adapters.ts b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-adapters.tsnew file mode 100644index 00000000000..a4e1c91320b--- /dev/null+++ b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-adapters.ts@@ -0,0 +1,286 @@+import { AIProviderName, isNil } from '@activepieces/core-utils';+import {+ AI_USAGE_CREDITS_KEY_ID,+ AI_USAGE_NO_PROJECT_ID,+ AI_USAGE_UNKNOWN_KEY_PREFIX,+ AiUsageDimension,+ AiUsageHistory,+ AiUsageItem,+ AiUsagePeriod,+ AiUsageRanges,+ AiUsageSeriesPoint,+ AiUsageTotals,+ ApEdition,+} from '@activepieces/shared';+import { t } from 'i18next';++import { SUPPORTED_AI_PROVIDERS } from '@/features/agents';++import { usageFormat } from './usage-format';+import { UsageMetric, UsagePoint } from './usage-types';++function seriesToPoints({+ series,+}: {+ series: AiUsageSeriesPoint[];+}): Record<UsageMetric, UsagePoint[]> {+ const pointsFor = (metric: UsageMetric): UsagePoint[] =>+ series.map((point) => ({+ label: point.label,+ current: valueOf({ point, metric, previous: false }),+ previous: valueOf({ point, metric, previous: true }),+ }));+ return {+ spend: pointsFor('spend'),+ calls: pointsFor('calls'),+ tokens: pointsFor('tokens'),+ };+}++function valueOf({+ point,+ metric,+ previous,+}: {+ point: AiUsageSeriesPoint;+ metric: UsageMetric;+ previous: boolean;+}): number | null {+ switch (metric) {+ case 'spend':+ return previous ? point.previousSpendUsd : point.spendUsd;+ case 'calls':+ return previous ? point.previousCalls : point.calls;+ case 'tokens':+ return previous ? point.previousTokens : point.tokens;+ }+}++function creditsNote({+ managedCredits,+}: {+ managedCredits: number;+}): string | undefined {+ return managedCredits > 0+ ? t('Includes {credits} Activepieces credits', {+ credits: usageFormat.whole(managedCredits),+ })+ : undefined;+}++function elapsedDaysOf({+ ranges,+ history,+}: {+ ranges: AiUsageRanges;+ history: AiUsageHistory;+}): number {+ const start = new Date(ranges.current.start).getTime();+ const observedEnd = Math.min(+ new Date(ranges.current.end).getTime(),+ Date.now(),+ );+ const elapsedMs = Math.max(0, observedEnd - start) * history.currentCoverage;+ return Math.max(elapsedMs / DAY_MS, MIN_ELAPSED_DAYS);+}++function paceOf({+ totals,+ ranges,+ history,+ period,+}: {+ totals: AiUsageTotals;+ ranges: AiUsageRanges;+ history: AiUsageHistory;+ period: AiUsagePeriod;+}): { avgPerDayUsd: number; forecastUsd?: number } {+ const avgPerDayUsd = totals.spendUsd / elapsedDaysOf({ ranges, history });+ if (period !== 'this-month') {+ return { avgPerDayUsd };+ }+ return {+ avgPerDayUsd,+ forecastUsd: avgPerDayUsd * daysInMonthOf({ iso: ranges.current.start }),+ };+}++function daysInMonthOf({ iso }: { iso: string }): number {+ const date = new Date(iso);+ return new Date(+ Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0),+ ).getUTCDate();+}++function monthEndDateLabel({ iso }: { iso: string }): string {+ const date = new Date(iso);+ const end = new Date(+ Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0),+ );+ return usageFormat.pointLabel({ label: end.toISOString().slice(0, 10) });+}++function legendRangeLabel({+ iso,+ period,+}: {+ iso: string;+ period: AiUsagePeriod;+}): string {+ return SUB_DAY_PERIODS.includes(period)+ ? usageFormat.pointLabel({ label: iso })+ : usageFormat.pointLabel({ label: iso.slice(0, 10) });+}++function legendRanges({+ ranges,+ period,+}: {+ ranges: AiUsageRanges;+ period: AiUsagePeriod;+}): { current: string; previous: string } {+ const inclusiveEnd = (iso: string): string =>+ SUB_DAY_PERIODS.includes(period)+ ? iso+ : new Date(new Date(iso).getTime() - DAY_MS).toISOString();+ return {+ current: `${legendRangeLabel({+ iso: ranges.current.start,+ period,+ })} – ${legendRangeLabel({+ iso: inclusiveEnd(ranges.current.end),+ period,+ })}`,+ previous: `${legendRangeLabel({+ iso: ranges.previous.start,+ period,+ })} – ${legendRangeLabel({+ iso: inclusiveEnd(ranges.previous.end),+ period,+ })}`,+ };+}++function providerDisplayName({+ provider,+}: {+ provider?: AIProviderName;+}): string {+ if (isNil(provider)) {+ return t('Unknown');+ }+ const info = SUPPORTED_AI_PROVIDERS.find(+ (candidate) => candidate.provider === provider,+ );+ return info?.name ?? provider;+}++function itemDisplayName({ item }: { item: AiUsageItem }): string {+ if (!isNil(item.name)) {+ return item.name;+ }+ if (item.dimension === 'project' && item.id === AI_USAGE_NO_PROJECT_ID) {+ return t('No project (platform chat)');+ }+ if (item.dimension === 'key' && item.id === AI_USAGE_CREDITS_KEY_ID) {+ return t('Activepieces credits');+ }+ if (+ item.dimension === 'key' &&+ item.id.startsWith(AI_USAGE_UNKNOWN_KEY_PREFIX)+ ) {+ return t('Unknown {provider} key', {+ provider: providerDisplayName({ provider: item.provider }),+ });+ }+ return deletedLabel({ dimension: item.dimension });+}++function deletedLabel({ dimension }: { dimension: AiUsageDimension }): string {+ switch (dimension) {+ case 'project':+ return t('Deleted project');+ case 'flow':+ return t('Deleted flow');+ case 'agent':+ return t('Deleted agent');+ case 'user':+ return t('Deleted user');+ case 'key':+ return t('Deleted key');+ case 'model':+ return t('Deleted model');+ }+}++function itemSubtitle({ item }: { item: AiUsageItem }): string {+ if (item.provider === AIProviderName.ACTIVEPIECES) {+ return t('Billed on your plan');+ }+ if (item.dimension === 'project') {+ return t(+ '{flows, plural, =1 {1 flow} other {# flows}} · {agents, plural, =1 {1 agent} other {# agents}}',+ { flows: item.flowCount ?? 0, agents: item.agentCount ?? 0 },+ );+ }+ if (item.dimension === 'key' || item.dimension === 'model') {+ return providerDisplayName({ provider: item.provider });+ }+ return item.parent ?? '';+}++function dashboardUrlOf({+ item,+ edition,+}: {+ item: AiUsageItem;+ edition: ApEdition | null;+}): string | undefined {+ if (item.dimension !== 'key') {+ return undefined;+ }+ if (item.id === AI_USAGE_CREDITS_KEY_ID) {+ return isNil(edition) || edition === ApEdition.COMMUNITY+ ? undefined+ : '/platform/billing';+ }+ const info = SUPPORTED_AI_PROVIDERS.find(+ (candidate) => candidate.provider === item.provider,+ );+ return info?.dashboardUrl;+}++function hasSharedSpend({ item }: { item: AiUsageItem }): boolean {+ return !isNil(item.sharedUsd) && item.sharedUsd > 0;+}++function sharedBadgeText({ item }: { item: AiUsageItem }): string {+ const other = item.dimension === 'flow' ? t('Agents') : t('Flows');+ return t(+ '{amount} of this comes from Run Agent steps, so it also counts under {other}.',+ { amount: usageFormat.usd(item.sharedUsd ?? 0), other },+ );+}++function isDetailEmpty({ item }: { item: AiUsageItem }): boolean {+ return item.calls === 0 && item.previousSpendUsd === 0;+}++const DAY_MS = 24 * 60 * 60 * 1000;+const MIN_ELAPSED_DAYS = 1 / (24 * 60);+const SUB_DAY_PERIODS: AiUsagePeriod[] = ['1h', '6h', '12h', '24h'];++export const usageAdapters = {+ seriesToPoints,+ creditsNote,+ paceOf,+ monthEndDateLabel,+ legendRanges,+ providerDisplayName,+ itemDisplayName,+ itemSubtitle,+ dashboardUrlOf,+ hasSharedSpend,+ sharedBadgeText,+ isDetailEmpty,+};diff --git a/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-bits.tsx b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-bits.tsxnew file mode 100644index 00000000000..6a8185b7a86--- /dev/null+++ b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-bits.tsx@@ -0,0 +1,203 @@+import { AIProviderName, isNil } from '@activepieces/core-utils';+import {+ AiUsageDimension,+ AiUsageItem,+ DEFAULT_BRAND_LOGOS,+} from '@activepieces/shared';+import { t } from 'i18next';+import {+ ArrowDownRight,+ ArrowUpRight,+ Bot,+ Cpu,+ KeyRound,+ LayoutGrid,+ LucideIcon,+ User,+ Workflow,+} from 'lucide-react';+import { Fragment } from 'react';+import { Link } from 'react-router-dom';++import { LogoPlate } from '@/components/custom/logo-plate';+import {+ Breadcrumb,+ BreadcrumbItem,+ BreadcrumbLink,+ BreadcrumbList,+ BreadcrumbSeparator,+} from '@/components/ui/breadcrumb';+import { SUPPORTED_AI_PROVIDERS } from '@/features/agents';+import { cn } from '@/lib/utils';++import { ProviderLogo } from '../providers-tab/provider-logo';++import { usageFormat } from './usage-format';++export function DeltaChip({+ value,+ size = 'sm',+}: {+ value: number | null;+ size?: 'sm' | 'xs';+}) {+ if (isNil(value)) {+ return (+ <span+ className={cn(+ 'inline-flex shrink-0 items-center rounded-md text-xs font-medium text-warning-11',+ size === 'sm' && 'bg-warning-3 px-1.5 py-0.5',+ )}+ >+ {t('New')}+ </span>+ );+ }+ const flat = Math.abs(value) < FLAT_CHANGE;+ const Icon = value > 0 ? ArrowUpRight : ArrowDownRight;+ return (+ <span+ className={cn(+ 'inline-flex shrink-0 items-center gap-0.5 rounded-md font-medium tabular-nums',+ size === 'sm' ? 'px-1.5 py-0.5 text-xs' : 'text-xs',+ flat+ ? 'text-gray-11'+ : value > 0+ ? 'text-warning-11'+ : 'text-success-11',+ size === 'sm' &&+ (flat ? 'bg-gray-3' : value > 0 ? 'bg-warning-3' : 'bg-success-3'),+ )}+ >+ {!flat && <Icon className="size-3" />}+ {flat ? '0%' : usageFormat.signedPercent(value)}+ </span>+ );+}++export function ItemIcon({ item }: { item: AiUsageItem }) {+ const info = SUPPORTED_AI_PROVIDERS.find(+ (provider) => provider.provider === item.provider,+ );+ if (+ (item.dimension === 'key' || item.dimension === 'model') &&+ !isNil(info)+ ) {+ return <ProviderLogo info={info} size="sm" />;+ }+ if (item.provider === AIProviderName.ACTIVEPIECES) {+ return (+ <LogoPlate+ src={DEFAULT_BRAND_LOGOS.logoIconUrl}+ alt={t('Activepieces')}+ className="size-4"+ />+ );+ }+ const Icon = dimensionIcon({ dimension: item.dimension });+ return (+ <span className="flex size-4 shrink-0 items-center justify-center text-gray-11">+ <Icon className="size-4" />+ </span>+ );+}++export function UsageEmptyState({+ dimension,+ label,+}: {+ dimension: AiUsageDimension;+ label?: string;+}) {+ const Icon = DIMENSION_ICONS[dimension];+ return (+ <div className="flex min-h-36 flex-1 flex-col items-center justify-center gap-2 text-center">+ <span className="flex size-9 items-center justify-center rounded-lg bg-gray-3 text-gray-11">+ <Icon className="size-4" />+ </span>+ <p className="text-sm font-medium text-gray-12">+ {t('No usage from {items}', {+ items: (+ label ?? usageFormat.dimensionLabel({ dimension })+ ).toLowerCase(),+ })}+ </p>+ <p className="max-w-56 text-xs text-gray-11">+ {t('Nothing ran in this period. Try a longer period or All.')}+ </p>+ </div>+ );+}++export function UsageTrail({+ crumbs,+ current,+}: {+ crumbs: { label: string; to: string }[];+ current: string;+}) {+ return (+ <Breadcrumb>+ <BreadcrumbList className="gap-2 text-2xl font-semibold tracking-tight sm:gap-2">+ {crumbs.map((crumb) => (+ <Fragment key={crumb.to}>+ <BreadcrumbItem>+ <BreadcrumbLink+ asChild+ className="rounded-md text-gray-11 hover:text-gray-12 focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-gray-8/50"+ >+ <Link to={crumb.to}>{crumb.label}</Link>+ </BreadcrumbLink>+ </BreadcrumbItem>+ <BreadcrumbSeparator className="font-normal text-gray-8">+ /+ </BreadcrumbSeparator>+ </Fragment>+ ))}+ <BreadcrumbItem className="min-w-0">+ <h1 aria-current="page" className="min-w-0 break-words text-gray-12">+ {current}+ </h1>+ </BreadcrumbItem>+ </BreadcrumbList>+ </Breadcrumb>+ );+}++export function relatedSpan({+ index,+ count,+}: {+ index: number;+ count: number;+}): string {+ if (count % 3 === 0) {+ return 'lg:col-span-4';+ }+ if (count % 3 === 2) {+ return index >= count - 2 ? 'lg:col-span-6' : 'lg:col-span-4';+ }+ return 'lg:col-span-6';+}++export function dimensionIcon({+ dimension,+}: {+ dimension: AiUsageDimension;+}): LucideIcon {+ return DIMENSION_ICONS[dimension];+}++const FLAT_CHANGE = 0.005;++const DIMENSION_ICONS: Record<AiUsageDimension, LucideIcon> = {+ project: LayoutGrid,+ flow: Workflow,+ agent: Bot,+ user: User,+ key: KeyRound,+ model: Cpu,+};++export const USAGE_LIST_GRID =+ 'grid grid-cols-[minmax(0,1fr)_6rem_1rem] items-center gap-4 md:grid-cols-[minmax(0,1fr)_5rem_5rem_5rem_6rem_1rem]';diff --git a/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-detail-page.tsx b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-detail-page.tsxnew file mode 100644index 00000000000..525e7aff37f--- /dev/null+++ b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-detail-page.tsx@@ -0,0 +1,339 @@+import { isNil } from '@activepieces/core-utils';+import {+ AI_USAGE_CREDITS_KEY_ID,+ AI_USAGE_DIMENSIONS,+ AiUsageDetail,+ AiUsageDimension,+ ApEdition,+ ApFlagId,+} from '@activepieces/shared';+import { t } from 'i18next';+import {+ Calculator,+ CircleDollarSign,+ ExternalLink,+ Gauge,+ Hash,+ Play,+ Receipt,+ Type,+} from 'lucide-react';+import { ReactNode } from 'react';+import { Link, Navigate, useParams } from 'react-router-dom';++import { AdminPageHeader, StatCard, StatGrid } from '@/app/components/admin';+import { DataFetchErrorState } from '@/components/custom/data-fetch-error-state';+import { Button } from '@/components/ui/button';+import { aiUsageHooks } from '@/features/ai-usage';+import { flagsHooks } from '@/hooks/flags-hooks';++import { usageAdapters } from './usage-adapters';+import { relatedSpan, UsageTrail } from './usage-bits';+import { UsageEmpty } from './usage-empty';+import { usageFormat } from './usage-format';+import {+ UsageHeaderControls,+ UsageView,+ useUsageView,+} from './usage-header-controls';+import { UsageHero } from './usage-hero';+import { UsageDetailSkeleton } from './usage-skeletons';+import { UsageSourceDonut } from './usage-source-donut';+import { UsageTopList } from './usage-top-list';++export function UsageDetailPage() {+ const { dimension: param, id } = useParams();+ const dimension = AI_USAGE_DIMENSIONS.find((item) => item === param);+ const view = useUsageView();+ const { data, isLoading, isError, refetch } = aiUsageHooks.useUsageDetail({+ dimension,+ id,+ period: view.period,+ scope: view.scope,+ });+ if (isNil(dimension)) {+ return <Navigate to={`/platform/ai/usage${view.search}`} replace />;+ }+ const overviewLink = `/platform/ai/usage${view.search}`;++ return (+ <>+ <AdminPageHeader+ title={+ <UsageTrail+ crumbs={[+ { label: t('AI usage'), to: overviewLink },+ {+ label: usageFormat.dimensionLabel({ dimension }),+ to: `/platform/ai/usage/${dimension}${view.search}`,+ },+ ]}+ current={+ data+ ? usageAdapters.itemDisplayName({ item: data.item })+ : usageFormat.dimensionBadge({ dimension })+ }+ />+ }+ description={+ data ? usageAdapters.itemSubtitle({ item: data.item }) : undefined+ }+ >+ <UsageHeaderControls view={view} />+ </AdminPageHeader>+ <DetailBody+ view={view}+ dimension={dimension}+ data={data}+ isLoading={isLoading}+ isError={isError}+ onRetry={refetch}+ />+ </>+ );+}++function DetailBody({+ view,+ dimension,+ data,+ isLoading,+ isError,+ onRetry,+}: {+ view: UsageView;+ dimension: AiUsageDimension;+ data: AiUsageDetail | undefined;+ isLoading: boolean;+ isError: boolean;+ onRetry: () => unknown;+}) {+ if (isError) {+ return <DataFetchErrorState entity={t('AI usage')} onRetry={onRetry} />;+ }+ if (isLoading || isNil(data)) {+ return <UsageDetailSkeleton dimension={dimension} />;+ }+ if (usageAdapters.isDetailEmpty({ item: data.item })) {+ return (+ <UsageEmpty+ view={view}+ history={data.history}+ title={t('No spend for this {type} in this period', {+ type: usageFormat.dimensionBadge({ dimension }).toLowerCase(),+ })}+ extraAction={+ <Button variant="ghost" size="sm" asChild>+ <Link to={`/platform/ai/usage/${dimension}${view.search}`}>+ {t('See all {items}', {+ items: usageFormat.dimensionLabel({ dimension }).toLowerCase(),+ })}+ </Link>+ </Button>+ }+ />+ );+ }+ const related = Object.entries(data.related).flatMap(([key, items]) => {+ const other = AI_USAGE_DIMENSIONS.find((item) => item === key);+ return isNil(other) || isNil(items) ? [] : [{ dimension: other, items }];+ });+ const relatedTotal = data.item.spendUsd;++ return (+ <>+ <DetailTiles dimension={dimension} detail={data} />+ <UsageHero+ series={usageAdapters.seriesToPoints({ series: data.series })}+ period={view.period}+ ranges={data.ranges}+ history={data.history}+ />+ {data.bySource && <UsageSourceDonut sources={data.bySource} />}+ {related.length > 0 && (+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-12">+ {related.map((group, index) => (+ <UsageTopList+ key={group.dimension}+ className={relatedSpan({ index, count: related.length })}+ dimension={group.dimension}+ items={group.items}+ totalUsd={relatedTotal}+ search={view.search}+ shareOf={t('{name} spend', {+ name: usageAdapters.itemDisplayName({ item: data.item }),+ })}+ seeAllLabel={t('All {items} on the platform', {+ items: usageFormat+ .dimensionLabel({ dimension: group.dimension })+ .toLowerCase(),+ })}+ />+ ))}+ </div>+ )}+ </>+ );+}++function DetailTiles({+ dimension,+ detail,+}: {+ dimension: AiUsageDimension;+ detail: AiUsageDetail;+}) {+ const { item } = detail;+ const perCall = item.calls === 0 ? 0 : item.spendUsd / item.calls;+ const calls = (+ <StatCard+ key="calls"+ label={t('AI calls')}+ icon={<Hash />}+ value={usageFormat.whole(item.calls)}+ hint={t('{cost} per call on average', { cost: usageFormat.usd(perCall) })}+ />+ );+ const tokens = (+ <StatCard+ key="tokens"+ label={t('Tokens')}+ icon={<Type />}+ value={usageFormat.compact(item.tokens)}+ />+ );+ const tilesByType: Record<AiUsageDimension, ReactNode[]> = {+ project: [+ <StatCard+ key="spend"+ label={t('Spend')}+ icon={<CircleDollarSign />}+ value={usageFormat.usd(item.spendUsd)}+ hint={usageAdapters.itemSubtitle({ item })}+ />,+ calls,+ tokens,+ ],+ flow: [+ <StatCard+ key="runs"+ label={t('Runs')}+ icon={<Play />}+ value={usageFormat.whole(detail.runs ?? 0)}+ hint={t('Runs that made at least one AI call')}+ />,+ <StatCard+ key="per-run"+ label={t('Cost per run')}+ icon={<Calculator />}+ value={usageFormat.usd(+ isNil(detail.runs) || detail.runs === 0+ ? 0+ : item.spendUsd / detail.runs,+ )}+ hint={t('Average across the period')}+ />,+ calls,+ ],+ agent: [+ calls,+ tokens,+ <StatCard+ key="spend"+ label={t('Spend')}+ icon={<CircleDollarSign />}+ value={usageFormat.usd(item.spendUsd)}+ />,+ ],+ user: [+ calls,+ tokens,+ <StatCard+ key="spend"+ label={t('Spend')}+ icon={<CircleDollarSign />}+ value={usageFormat.usd(item.spendUsd)}+ />,+ ],+ key: [+ item.id === AI_USAGE_CREDITS_KEY_ID ? (+ <StatCard+ key="reported"+ label={t('Billed on your plan')}+ icon={<Receipt />}+ value={usageFormat.usd(detail.reportedUsd ?? 0)}+ hint={t('What these calls used of your Activepieces credits')}+ />+ ) : (+ <StatCard+ key="reported"+ label={t('Reported by provider')}+ icon={<Receipt />}+ value={usageFormat.usd(detail.reportedUsd ?? 0)}+ hint={t('Cost the provider sent back with each call')}+ />+ ),+ <StatCard+ key="estimated"+ label={t('Estimated')}+ icon={<Calculator />}+ value={usageFormat.usd(detail.estimatedUsd ?? 0)}+ hint={t('Tokens times list price, where the provider sent no cost')}+ />,+ <DashboardTile key="dashboard" item={item} />,+ ],+ model: [+ <StatCard+ key="price"+ label={t('List price per 1M tokens')}+ icon={<Gauge />}+ value={+ isNil(item.inputPrice) || isNil(item.outputPrice)+ ? t('Unknown')+ : `${usageFormat.usd(item.inputPrice)} · ${usageFormat.usd(+ item.outputPrice,+ )}`+ }+ hint={+ isNil(item.inputPrice)+ ? t('No list price, so calls count as unpriced')+ : t('Input · output')+ }+ />,+ calls,+ tokens,+ ],+ };+ return <StatGrid columns={3}>{tilesByType[dimension]}</StatGrid>;+}++function DashboardTile({ item }: { item: AiUsageDetail['item'] }) {+ const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);+ const url = usageAdapters.dashboardUrlOf({ item, edition });+ const internal = !isNil(url) && url.startsWith('/');+ return (+ <StatCard+ label={t('Provider dashboard')}+ icon={<ExternalLink />}+ value={internal ? t('Activepieces credits') : t('Your bill')}+ hint={+ internal+ ? t('Credits are billed on your plan')+ : t('Compare these numbers with your provider')+ }+ >+ {!isNil(url) && (+ <Button variant="outline" size="xs" className="w-fit" asChild>+ {internal ? (+ <Link to={url}>{t('Open billing')}</Link>+ ) : (+ <a href={url} target="_blank" rel="noreferrer">+ {t('Open dashboard')}+ <ExternalLink className="size-3.5" />+ </a>+ )}+ </Button>+ )}+ </StatCard>+ );+}diff --git a/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-empty.tsx b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-empty.tsxnew file mode 100644index 00000000000..38748b2e99c--- /dev/null+++ b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-empty.tsx@@ -0,0 +1,165 @@+import { isNil } from '@activepieces/core-utils';+import { AiUsageHistory, ApEdition, ApFlagId } from '@activepieces/shared';+import { t } from 'i18next';+import { ChartLine, Info } from 'lucide-react';+import { ReactNode } from 'react';++import { adminSurface } from '@/app/components/admin';+import { Button } from '@/components/ui/button';+import { flagsHooks } from '@/hooks/flags-hooks';+import { cn } from '@/lib/utils';++import { usageFormat } from './usage-format';+import { UsageView } from './usage-header-controls';++export function UsageEmptyNote({+ view,+ history,+}: {+ view: UsageView;+ history: AiUsageHistory;+}) {+ const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);+ const state = stateOf({ edition, history });+ return (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 rounded-xl border border-gray-6 bg-gray-1 px-4 py-3">+ <Info className="size-4 shrink-0 text-gray-11" />+ <p className="min-w-0 flex-1 text-sm text-gray-11">+ <span className="font-medium text-gray-12">+ {headlineOf({ state })}+ </span>{' '}+ {reasonOf({ state, view })}+ </p>+ <EmptyActions state={state} view={view} />+ </div>+ );+}++export function UsageEmpty({+ view,+ history,+ title,+ extraAction,+}: UsageEmptyProps) {+ const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);+ const state = stateOf({ edition, history });+ return (+ <section className={cn(adminSurface.card, 'flex items-start gap-4 p-5')}>+ <span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-gray-3 text-gray-11">+ <ChartLine className="size-4" />+ </span>+ <div className="flex min-w-0 flex-1 flex-col gap-3">+ <div className="flex flex-col gap-1">+ <h2 className="text-sm font-medium text-gray-12">+ {state === 'filtered' ? title : headlineOf({ state })}+ </h2>+ <p className="text-sm text-gray-11">{reasonOf({ state, view })}</p>+ </div>+ <EmptyActions state={state} view={view} extraAction={extraAction} />+ </div>+ </section>+ );+}++function EmptyActions({+ state,+ view,+ extraAction,+}: {+ state: UsageEmptyState;+ view: UsageView;+ extraAction?: ReactNode;+}) {+ if (state !== 'filtered') {+ return null;+ }+ const widerPeriod = view.period !== LONGEST_PERIOD;+ const widerScope = view.scope !== 'all';+ if (!widerPeriod && !widerScope && !extraAction) {+ return null;+ }+ return (+ <div className="flex flex-wrap items-center gap-2">+ {widerPeriod && (+ <Button+ variant="outline"+ size="sm"+ onClick={() => view.setPeriod(LONGEST_PERIOD)}+ >+ {t('Show last 90 days')}+ </Button>+ )}+ {widerScope && (+ <Button+ variant="outline"+ size="sm"+ onClick={() => view.setScope('all')}+ >+ {view.scope === 'production'+ ? t('Include testing')+ : t('Include production')}+ </Button>+ )}+ {extraAction}+ </div>+ );+}++function headlineOf({ state }: { state: UsageEmptyState }): string {+ switch (state) {+ case 'unavailable':+ return t("AI usage isn't available on this install");+ case 'never-used':+ return t('No AI spend yet.');+ case 'filtered':+ return t('No AI spend in this view.');+ }+}++function reasonOf({+ state,+ view,+}: {+ state: UsageEmptyState;+ view: UsageView;+}): string {+ switch (state) {+ case 'unavailable':+ return t(+ 'Usage data comes from your billing connection, which this install does not have.',+ );+ case 'never-used':+ return t(+ 'It shows up a few minutes after the first AI step, agent run or chat message.',+ );+ case 'filtered':+ return t('Nothing used AI in {scope} for {period}.', {+ scope: usageFormat.scopeLabel({ scope: view.scope }),+ period: usageFormat.periodLabel({ period: view.period }).toLowerCase(),+ });+ }+}++function stateOf({+ edition,+ history,+}: {+ edition: ApEdition | null;+ history: AiUsageHistory;+}): UsageEmptyState {+ if (edition === ApEdition.ENTERPRISE && isNil(history.trackingSince)) {+ return 'unavailable';+ }+ return history.hasAnyUsage ? 'filtered' : 'never-used';+}++const LONGEST_PERIOD = '90d';++type UsageEmptyState = 'unavailable' | 'never-used' | 'filtered';++type UsageEmptyProps = {+ view: UsageView;+ history: AiUsageHistory;+ title: string;+ extraAction?: ReactNode;+};diff --git a/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-estimate-note.tsx b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-estimate-note.tsxnew file mode 100644index 00000000000..cfefc431d7a--- /dev/null+++ b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-estimate-note.tsx@@ -0,0 +1,54 @@+import { t } from 'i18next';+import { Info } from 'lucide-react';++import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/components/ui/popover';++export function UsageEstimateNote() {+ return (+ <Popover>+ <PopoverTrigger asChild>+ <button+ type="button"+ className="inline-flex cursor-pointer items-center gap-1 rounded-sm text-xs text-gray-11 underline decoration-gray-8 decoration-dotted underline-offset-4 transition-colors hover:text-gray-12 hover:decoration-gray-12 focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-gray-8/50"+ >+ <Info className="size-3" />+ {t('Estimated')}+ </button>+ </PopoverTrigger>+ <PopoverContent align="start" sideOffset={8} className="w-96">+ <div className="flex flex-col gap-3 text-sm">+ <p className="font-medium text-gray-12">+ {t('Why these numbers are estimates')}+ </p>+ <ul className="flex list-disc flex-col gap-2 pl-4 text-gray-11">+ <li>+ {t(+ 'Most AI providers send back how many tokens a call used, not what it cost. We multiply those tokens by the model’s list price.',+ )}+ </li>+ <li>+ {t(+ 'Discounts, cached tokens, batch rates and price changes on your account can make your real bill a few percent different.',+ )}+ </li>+ <li>+ {t(+ 'When a provider does send the exact cost, we use it as is. Open a key to see how much was reported and how much was estimated.',+ )}+ </li>+ <li>{t('Activepieces credits are always exact.')}</li>+ </ul>+ <p className="border-t border-gray-6 pt-3 text-xs text-gray-11">+ {t(+ "For billing, your provider's own dashboard is the source of truth.",+ )}+ </p>+ </div>+ </PopoverContent>+ </Popover>+ );+}diff --git a/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-format.ts b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-format.tsnew file mode 100644index 00000000000..3d0563c15b8--- /dev/null+++ b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-format.ts@@ -0,0 +1,251 @@+import {+ AiUsageDimension,+ AiUsagePeriod,+ AiUsageScope,+ AiUsageSource,+} from '@activepieces/shared';+import { t } from 'i18next';++import { UsageMetric } from './usage-types';++function usd(value: number): string {+ if (value > 0 && value < 0.01) {+ return '<$0.01';+ }+ return USD.format(value);+}++function compact(value: number): string {+ return COMPACT.format(value);+}++function whole(value: number): string {+ return WHOLE.format(Math.round(value));+}++function percent(value: number): string {+ return `${Math.round(value * 100)}%`;+}++function change({+ current,+ previous,+}: {+ current: number;+ previous: number;+}): number | null {+ if (previous === 0) {+ return current === 0 ? 0 : null;+ }+ return (current - previous) / previous;+}++function signedPercent(value: number): string {+ const rounded = Math.round(value * 100);+ return rounded > 0 ? `+${rounded}%` : `${rounded}%`;+}++function metricValue({+ metric,+ value,+}: {+ metric: UsageMetric;+ value: number;+}): string {+ return metric === 'spend' ? usd(value) : compact(value);+}++function pointLabel({ label }: { label: string }): string {+ if (!label.includes('T')) {+ return new Date(`${label}T00:00:00Z`).toLocaleDateString('en-US', {+ month: 'short',+ day: 'numeric',+ timeZone: 'UTC',+ });+ }+ return new Date(label).toLocaleTimeString('en-US', {+ hour: '2-digit',+ minute: '2-digit',+ hour12: false,+ timeZone: 'UTC',+ });+}++function periodLabel({ period }: { period: AiUsagePeriod }): string {+ switch (period) {+ case '1h':+ return t('Last hour');+ case '6h':+ return t('Last 6 hours');+ case '12h':+ return t('Last 12 hours');+ case '24h':+ return t('Last 24 hours');+ case '7d':+ return t('Last 7 days');+ case '30d':+ return t('Last 30 days');+ case '90d':+ return t('Last 90 days');+ case 'this-month':+ return t('This month');+ case 'last-month':+ return t('Last month');+ }+}++function previousLabel({ period }: { period: AiUsagePeriod }): string {+ switch (period) {+ case '1h':+ return t('vs previous hour');+ case '6h':+ return t('vs previous 6 hours');+ case '12h':+ return t('vs previous 12 hours');+ case '24h':+ return t('vs previous 24 hours');+ case '7d':+ return t('vs previous 7 days');+ case '30d':+ return t('vs previous 30 days');+ case '90d':+ return t('vs previous 90 days');+ case 'this-month':+ return t('vs same days last month');+ case 'last-month':+ return t('vs the month before');+ }+}++function dimensionLabel({+ dimension,+}: {+ dimension: AiUsageDimension;+}): string {+ switch (dimension) {+ case 'project':+ return t('Projects');+ case 'flow':+ return t('Flows');+ case 'agent':+ return t('Agents');+ case 'user':+ return t('Users');+ case 'key':+ return t('Providers & keys');+ case 'model':+ return t('Models');+ }+}++function dimensionBadge({+ dimension,+}: {+ dimension: AiUsageDimension;+}): string {+ switch (dimension) {+ case 'project':+ return t('Project');+ case 'flow':+ return t('Flow');+ case 'agent':+ return t('Agent');+ case 'user':+ return t('User');+ case 'key':+ return t('Key');+ case 'model':+ return t('Model');+ }+}++function sourceLabel({ source }: { source: AiUsageSource }): string {+ switch (source) {+ case 'flow-steps':+ return t('Flow AI steps');+ case 'agent-steps':+ return t('Run Agent steps');+ case 'agents':+ return t('Agents');+ case 'chat':+ return t('Chat');+ case 'knowledge-base':+ return t('Knowledge base');+ }+}++function metricLabel({ metric }: { metric: UsageMetric }): string {+ switch (metric) {+ case 'spend':+ return t('Spend');+ case 'calls':+ return t('Calls');+ case 'tokens':+ return t('Tokens');+ }+}++function scopeLabel({ scope }: { scope: AiUsageScope }): string {+ switch (scope) {+ case 'production':+ return t('Production');+ case 'testing':+ return t('Testing');+ case 'all':+ return t('All');+ }+}++function itemCountLabel({+ dimension,+ count,+}: {+ dimension: AiUsageDimension;+ count: number;+}): string {+ switch (dimension) {+ case 'project':+ return t('{count, plural, =1 {1 project} other {# projects}}', { count });+ case 'flow':+ return t('{count, plural, =1 {1 flow} other {# flows}}', { count });+ case 'agent':+ return t('{count, plural, =1 {1 agent} other {# agents}}', { count });+ case 'user':+ return t('{count, plural, =1 {1 user} other {# users}}', { count });+ case 'key':+ return t('{count, plural, =1 {1 key} other {# keys}}', { count });+ case 'model':+ return t('{count, plural, =1 {1 model} other {# models}}', { count });+ }+}++const USD = new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: 'USD',+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+});+const COMPACT = new Intl.NumberFormat('en-US', {+ notation: 'compact',+ maximumFractionDigits: 1,+});+const WHOLE = new Intl.NumberFormat('en-US');++export const usageFormat = {+ usd,+ compact,+ whole,+ percent,+ change,+ signedPercent,+ metricValue,+ pointLabel,+ periodLabel,+ previousLabel,+ dimensionLabel,+ dimensionBadge,+ sourceLabel,+ metricLabel,+ scopeLabel,+ itemCountLabel,+};diff --git a/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-header-controls.tsx b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-header-controls.tsxnew file mode 100644index 00000000000..391b13f3501--- /dev/null+++ b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-header-controls.tsx@@ -0,0 +1,189 @@+import {+ AI_USAGE_PERIODS,+ AI_USAGE_SCOPES,+ AiUsagePeriod,+ AiUsageScope,+} from '@activepieces/shared';+import { t } from 'i18next';+import {+ Activity,+ CalendarClock,+ FlaskConical,+ Layers,+ LucideIcon,+} from 'lucide-react';+import { useSearchParams } from 'react-router-dom';++import {+ Select,+ SelectContent,+ SelectItem,+ SelectSeparator,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';++import { usageFormat } from './usage-format';++export function useUsageView(): UsageView {+ const [searchParams, setSearchParams] = useSearchParams();+ const period =+ AI_USAGE_PERIODS.find((item) => item === searchParams.get('period')) ??+ DEFAULT_PERIOD;+ const scope =+ AI_USAGE_SCOPES.find((item) => item === searchParams.get('scope')) ??+ DEFAULT_SCOPE;+ const update = ({+ key,+ value,+ fallback,+ }: {+ key: string;+ value: string;+ fallback: string;+ }): void => {+ const next = new URLSearchParams(searchParams);+ if (value === fallback) {+ next.delete(key);+ } else {+ next.set(key, value);+ }+ setSearchParams(next, { replace: true });+ };+ return {+ period,+ scope,+ search:+ searchParams.toString().length === 0 ? '' : `?${searchParams.toString()}`,+ setPeriod: (value) =>+ update({ key: 'period', value, fallback: DEFAULT_PERIOD }),+ setScope: (value) =>+ update({ key: 'scope', value, fallback: DEFAULT_SCOPE }),+ };+}++export function UsageHeaderControls({ view }: { view: UsageView }) {+ return (+ <>+ <ScopeSelect view={view} />+ <PeriodSelect view={view} />+ </>+ );+}++function ScopeSelect({ view }: { view: UsageView }) {+ return (+ <Select+ value={view.scope}+ onValueChange={(value) =>+ view.setScope(+ AI_USAGE_SCOPES.find((item) => item === value) ?? DEFAULT_SCOPE,+ )+ }+ >+ <SelectTrigger+ size="sm"+ className={TRIGGER_CLASS}+ aria-label={t('Usage scope')}+ >+ <ScopeIcon scope={view.scope} />+ <SelectValue>+ {usageFormat.scopeLabel({ scope: view.scope })}+ </SelectValue>+ </SelectTrigger>+ <SelectContent side="bottom" align="end" className="w-64">+ {AI_USAGE_SCOPES.map((scope) => (+ <SelectItem+ key={scope}+ value={scope}+ className="cursor-pointer items-start *:[span]:last:items-start"+ >+ <span className="flex pt-0.5">+ <ScopeIcon scope={scope} />+ </span>+ <span className="flex flex-col">+ <span className="text-gray-12">+ {usageFormat.scopeLabel({ scope })}+ </span>+ <span className="text-xs text-gray-11">+ {scopeHint({ scope })}+ </span>+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}++function ScopeIcon({ scope }: { scope: AiUsageScope }) {+ const Icon = SCOPE_ICONS[scope];+ return <Icon className="size-4 text-gray-11" />;+}++function PeriodSelect({ view }: { view: UsageView }) {+ return (+ <Select+ value={view.period}+ onValueChange={(value) =>+ view.setPeriod(+ AI_USAGE_PERIODS.find((item) => item === value) ?? DEFAULT_PERIOD,+ )+ }+ >+ <SelectTrigger+ size="sm"+ className={TRIGGER_CLASS}+ aria-label={t('Period')}+ >+ <CalendarClock className="size-4" />+ <SelectValue />+ </SelectTrigger>+ <SelectContent side="bottom" align="end">+ {AI_USAGE_PERIODS.map((period) => (+ <PeriodOption key={period} period={period} />+ ))}+ </SelectContent>+ </Select>+ );+}++function PeriodOption({ period }: { period: AiUsagePeriod }) {+ return (+ <>+ {(period === '7d' || period === 'this-month') && <SelectSeparator />}+ <SelectItem value={period} className="cursor-pointer">+ {usageFormat.periodLabel({ period })}+ </SelectItem>+ </>+ );+}++function scopeHint({ scope }: { scope: AiUsageScope }): string {+ switch (scope) {+ case 'production':+ return t('Live flows, agents and chat');+ case 'testing':+ return t('Test runs from the builders');+ case 'all':+ return t('Production and testing together');+ }+}++const TRIGGER_CLASS =+ 'w-auto cursor-pointer gap-1.5 border-gray-6 bg-gray-1 px-2.5 shadow-none hover:bg-gray-4 hover:text-gray-12';+const SCOPE_ICONS: Record<AiUsageScope, LucideIcon> = {+ all: Layers,+ production: Activity,+ testing: FlaskConical,+};+const DEFAULT_PERIOD: AiUsagePeriod = 'this-month';+const DEFAULT_SCOPE: AiUsageScope = 'production';++export type UsageView = {+ period: AiUsagePeriod;+ scope: AiUsageScope;+ search: string;+ setPeriod: (period: AiUsagePeriod) => void;+ setScope: (scope: AiUsageScope) => void;+};diff --git a/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-hero.tsx b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-hero.tsxnew file mode 100644index 00000000000..754189780ff--- /dev/null+++ b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-hero.tsx@@ -0,0 +1,457 @@+import { isNil } from '@activepieces/core-utils';+import {+ AiUsageHistory,+ AiUsagePeriod,+ AiUsageRanges,+} from '@activepieces/shared';+import { t } from 'i18next';+import { ChartColumn, ChartLine, Info } from 'lucide-react';+import { ReactNode, useId, useState } from 'react';+import {+ Area,+ Bar,+ CartesianGrid,+ ComposedChart,+ Line,+ XAxis,+ YAxis,+} from 'recharts';++import { adminSurface } from '@/app/components/admin';+import {+ ChartConfig,+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+} from '@/components/ui/chart';+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@/components/ui/tooltip';+import { cn } from '@/lib/utils';++import { usageAdapters } from './usage-adapters';+import { DeltaChip } from './usage-bits';+import { UsageEstimateNote } from './usage-estimate-note';+import { usageFormat } from './usage-format';+import { USAGE_METRICS, UsageMetric, UsagePoint } from './usage-types';++export function UsageHero({+ series,+ period,+ ranges,+ note,+ history,+ height = 280,+}: UsageHeroProps) {+ const [metric, setMetric] = useState<UsageMetric>('spend');+ const [chartType, setChartType] = useState<UsageChartType>('line');+ const points = series[metric];+ const current = points.reduce((sum, point) => sum + (point.current ?? 0), 0);+ const previous = points.reduce(+ (sum, point) => sum + (point.previous ?? 0),+ 0,+ );+ const comparable = history?.comparable ?? true;+ const partial = !isNil(history) && history.currentCoverage < 1;++ return (+ <section className={cn(adminSurface.card, 'flex flex-col gap-5 p-5')}>+ <div className="flex flex-wrap items-start justify-between gap-4">+ <div className="flex flex-col gap-1">+ <div className="flex items-center gap-2">+ <span className="text-sm text-gray-11">+ {usageFormat.metricLabel({ metric })}+ </span>+ {metric === 'spend' && <UsageEstimateNote />}+ </div>+ <div className="flex flex-wrap items-center gap-3">+ <span className="text-4xl font-semibold tracking-tight tabular-nums text-gray-12">+ {usageFormat.metricValue({ metric, value: current })}+ </span>+ {current === 0 && previous === 0 ? null : comparable ? (+ <>+ <DeltaChip value={usageFormat.change({ current, previous })} />+ <span className="text-sm text-gray-11">+ {usageFormat.previousLabel({ period })}+ </span>+ </>+ ) : (+ <NoComparison />+ )}+ </div>+ {metric === 'spend' && note && (+ <span className="text-xs text-gray-11">{note}</span>+ )}+ {partial && history && (+ <span className="text-xs text-warning-11">+ {t(+ 'Tracking started {date}, so this covers {covered} of {total} days',+ {+ date: history.trackingSince+ ? usageFormat.pointLabel({+ label: history.trackingSince.slice(0, 10),+ })+ : '',+ covered: Math.round(history.coveredDays),+ total: Math.round(history.periodDays),+ },+ )}+ </span>+ )}+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <Tabs+ value={metric}+ onValueChange={(value) =>+ setMetric(USAGE_METRICS.find((item) => item === value) ?? 'spend')+ }+ >+ <TabsList size="sm">+ {USAGE_METRICS.map((item) => (+ <TabsTrigger key={item} value={item} size="sm">+ {usageFormat.metricLabel({ metric: item })}+ </TabsTrigger>+ ))}+ </TabsList>+ </Tabs>+ <Tabs+ value={chartType}+ onValueChange={(value) =>+ setChartType(CHART_TYPES.find((item) => item === value) ?? 'line')+ }+ >+ <TabsList size="sm">+ <TabsTrigger value="line" size="sm" aria-label={t('Line chart')}>+ <ChartLine className="size-4" />+ </TabsTrigger>+ <TabsTrigger value="bar" size="sm" aria-label={t('Bar chart')}>+ <ChartColumn className="size-4" />+ </TabsTrigger>+ </TabsList>+ </Tabs>+ </div>+ </div>+ <div className="flex flex-col gap-3">+ <ChartLegend+ points={points}+ ranges={ranges}+ period={period}+ chartType={chartType}+ comparable={comparable}+ />+ <UsageLineChart+ points={points}+ metric={metric}+ height={height}+ chartType={chartType}+ />+ </div>+ </section>+ );+}++export function UsageLineChart({+ points,+ metric,+ height,+ compact = false,+ chartType = 'line',+}: UsageLineChartProps) {+ const gradientId = useId().replaceAll(':', '');+ const config = {+ current: { label: t('This period'), color: 'var(--accent-9)' },+ previous: { label: t('Previous period'), color: 'var(--gray-8)' },+ } satisfies ChartConfig;++ return (+ <ChartContainer+ config={config}+ className="aspect-auto w-full"+ style={{ height }}+ >+ <ComposedChart+ data={points}+ margin={{ left: 0, right: 8, top: 8, bottom: 0 }}+ >+ <defs>+ <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">+ <stop+ offset="0%"+ stopColor={config.current.color}+ stopOpacity={0.22}+ />+ <stop+ offset="100%"+ stopColor={config.current.color}+ stopOpacity={0}+ />+ </linearGradient>+ </defs>+ {!compact && (+ <CartesianGrid+ vertical={false}+ strokeDasharray="3 3"+ stroke="var(--gray-5)"+ />+ )}+ <XAxis+ dataKey="label"+ hide={compact}+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ minTickGap={28}+ tick={{ fill: 'var(--gray-11)', fontSize: 12 }}+ tickFormatter={(label: string) => usageFormat.pointLabel({ label })}+ />+ <YAxis+ hide={compact}+ tickLine={false}+ axisLine={false}+ width={Y_AXIS_WIDTH}+ tick={(props: AxisTickProps) => (+ <YAxisTick+ y={props.y}+ value={props.payload?.value}+ metric={metric}+ />+ )}+ />+ <ChartTooltip+ cursor={+ chartType === 'bar'+ ? { fill: 'var(--gray-3)' }+ : { stroke: 'var(--gray-8)', strokeWidth: 1 }+ }+ content={+ <ChartTooltipContent+ indicator="line"+ labelFormatter={(label) =>+ usageFormat.pointLabel({ label: String(label) })+ }+ formatter={(value, name) =>+ value === null || value === undefined ? null : (+ <TooltipRow+ label={+ String(name) === 'previous'+ ? config.previous.label+ : config.current.label+ }+ value={usageFormat.metricValue({+ metric,+ value: Number(value),+ })}+ />+ )+ }+ />+ }+ />+ {chartType === 'bar' && (+ <Bar+ dataKey="current"+ fill={config.current.color}+ radius={[3, 3, 0, 0]}+ maxBarSize={28}+ />+ )}+ {chartType === 'bar' && (+ <Bar+ dataKey="previous"+ fill={PREVIOUS_BAR_COLOR}+ radius={[3, 3, 0, 0]}+ maxBarSize={28}+ />+ )}+ {chartType === 'line' && (+ <Line+ dataKey="previous"+ type="monotone"+ stroke={config.previous.color}+ strokeWidth={1.5}+ strokeDasharray="4 4"+ dot={false}+ activeDot={false}+ />+ )}+ {chartType === 'line' && (+ <Area+ dataKey="current"+ type="monotone"+ stroke={config.current.color}+ strokeWidth={2}+ fill={`url(#${gradientId})`}+ dot={false}+ activeDot={{ r: 4, strokeWidth: 0, fill: config.current.color }}+ />+ )}+ </ComposedChart>+ </ChartContainer>+ );+}++function YAxisTick({+ y,+ value,+ metric,+}: {+ y?: number;+ value?: number;+ metric: UsageMetric;+}) {+ return (+ <text+ x={0}+ y={y}+ dominantBaseline="middle"+ fill="var(--gray-11)"+ fontSize={12}+ >+ {usageFormat.metricValue({ metric, value: value ?? 0 })}+ </text>+ );+}++function NoComparison() {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="flex cursor-default items-center gap-1.5 text-sm text-gray-11">+ {t('No full previous period to compare yet')}+ <Info className="size-3.5" />+ </span>+ </TooltipTrigger>+ <TooltipContent side="top" sideOffset={6} className="max-w-xs">+ {t(+ 'Usage tracking started after the previous period began, so a change % would be wrong. It shows up once a full previous period is tracked.',+ )}+ </TooltipContent>+ </Tooltip>+ );+}++function ChartLegend({+ points,+ ranges,+ period,+ chartType,+ comparable,+}: {+ points: UsagePoint[];+ ranges: AiUsageRanges;+ period: AiUsagePeriod;+ chartType: UsageChartType;+ comparable: boolean;+}) {+ const hasPrevious = points.some((point) => point.previous !== null);+ const legend = usageAdapters.legendRanges({ ranges, period });+ return (+ <div className="flex flex-wrap items-center gap-x-5 gap-y-1 text-xs text-gray-11">+ <LegendItem+ previous={false}+ chartType={chartType}+ label={t('This period')}+ range={legend.current}+ />+ <LegendItem+ previous+ chartType={chartType}+ label={t('Previous period')}+ range={+ hasPrevious+ ? comparable+ ? legend.previous+ : t('{range}, partly tracked', { range: legend.previous })+ : t('not tracked yet')+ }+ />+ </div>+ );+}++function LegendItem({+ previous,+ chartType,+ label,+ range,+}: {+ previous: boolean;+ chartType: UsageChartType;+ label: string;+ range?: string;+}) {+ const dashed = previous;+ return (+ <span className="flex items-center gap-2">+ {chartType === 'bar' ? (+ <span+ className="size-2.5 shrink-0 rounded-xs"+ style={{+ backgroundColor: previous ? PREVIOUS_BAR_COLOR : 'var(--accent-9)',+ }}+ />+ ) : (+ <svg+ width="20"+ height="8"+ viewBox="0 0 20 8"+ aria-hidden="true"+ className="shrink-0"+ >+ <line+ x1="1"+ y1="4"+ x2="19"+ y2="4"+ stroke={dashed ? 'var(--gray-8)' : 'var(--accent-9)'}+ strokeWidth={dashed ? 1.5 : 2}+ strokeDasharray={dashed ? '3 3' : undefined}+ strokeLinecap="round"+ />+ </svg>+ )}+ <span className="text-gray-12">{label}</span>+ {range && <span className="tabular-nums">{range}</span>}+ </span>+ );+}++function TooltipRow({ label, value }: { label: string; value: string }) {+ return (+ <span className="flex w-full justify-between gap-4">+ <span className="text-gray-11">{label}</span>+ <span className="font-medium tabular-nums">{value}</span>+ </span>+ );+}++const Y_AXIS_WIDTH = 56;++type AxisTickProps = {+ y?: number;+ payload?: { value?: number };+};+const PREVIOUS_BAR_COLOR = 'var(--gray-6)';+const CHART_TYPES: UsageChartType[] = ['line', 'bar'];++type UsageChartType = 'line' | 'bar';++type UsageHeroProps = {+ series: Record<UsageMetric, UsagePoint[]>;+ ranges: AiUsageRanges;+ history?: AiUsageHistory;+ period: AiUsagePeriod;+ note?: ReactNode;+ height?: number;+};++type UsageLineChartProps = {+ points: UsagePoint[];+ metric: UsageMetric;+ height: number;+ compact?: boolean;+ chartType?: UsageChartType;+};diff --git a/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-list-page.tsx b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-list-page.tsxnew file mode 100644index 00000000000..98cf78c52ea--- /dev/null+++ b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-list-page.tsx@@ -0,0 +1,478 @@+import { isNil } from '@activepieces/core-utils';+import {+ AI_USAGE_DIMENSIONS,+ AiUsageDimension,+ AiUsageHistory,+ AiUsageItem,+} from '@activepieces/shared';+import { t } from 'i18next';+import { ArrowDown, ArrowUp, ChevronLeft, ChevronRight } from 'lucide-react';+import { useRef, useState } from 'react';+import { Link, Navigate, useParams } from 'react-router-dom';++import { AdminPageHeader, adminSurface } from '@/app/components/admin';+import { DataFetchErrorState } from '@/components/custom/data-fetch-error-state';+import { SearchInput } from '@/components/custom/search-input';+import { TextWithTooltip } from '@/components/custom/text-with-tooltip';+import { Button } from '@/components/ui/button';+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@/components/ui/tooltip';+import { aiUsageHooks } from '@/features/ai-usage';+import { cn } from '@/lib/utils';++import { usageAdapters } from './usage-adapters';+import { DeltaChip, ItemIcon, USAGE_LIST_GRID, UsageTrail } from './usage-bits';+import { UsageEmpty } from './usage-empty';+import { usageFormat } from './usage-format';+import {+ UsageHeaderControls,+ UsageView,+ useUsageView,+} from './usage-header-controls';+import { UsageListSkeleton } from './usage-skeletons';+import { SharedBadge } from './usage-top-list';++export function UsageListPage() {+ const { dimension: param } = useParams();+ const dimension = AI_USAGE_DIMENSIONS.find((item) => item === param);+ const view = useUsageView();+ const { data, isLoading, isError, refetch } = aiUsageHooks.useUsageItems({+ dimension,+ period: view.period,+ scope: view.scope,+ });+ if (isNil(dimension)) {+ return <Navigate to={`/platform/ai/usage${view.search}`} replace />;+ }+ const itemsUsd = data?.itemsSpendUsd ?? 0;++ return (+ <>+ <AdminPageHeader+ title={+ <UsageTrail+ crumbs={[+ { label: t('AI usage'), to: `/platform/ai/usage${view.search}` },+ ]}+ current={usageFormat.dimensionLabel({ dimension })}+ />+ }+ description={+ data && data.count > 0+ ? t('{amount} across {items}', {+ amount: usageFormat.usd(itemsUsd),+ items: usageFormat+ .itemCountLabel({ dimension, count: data.count })+ .toLowerCase(),+ })+ : undefined+ }+ >+ <UsageHeaderControls view={view} />+ </AdminPageHeader>+ <UsageListBody+ key={`${dimension}-${view.scope}-${view.period}`}+ view={view}+ dimension={dimension}+ items={data?.items ?? []}+ history={data?.history}+ totalUsd={data?.totalSpendUsd ?? 0}+ truncated={data?.truncated ?? false}+ isLoading={isLoading}+ isError={isError}+ onRetry={refetch}+ />+ </>+ );+}++function UsageListBody({+ view,+ dimension,+ items,+ history,+ totalUsd,+ truncated,+ isLoading,+ isError,+ onRetry,+}: {+ view: UsageView;+ dimension: AiUsageDimension;+ items: AiUsageItem[];+ history: AiUsageHistory | undefined;+ totalUsd: number;+ truncated: boolean;+ isLoading: boolean;+ isError: boolean;+ onRetry: () => unknown;+}) {+ const [query, setQuery] = useState('');+ const [sort, setSort] = useState<UsageSort>(DEFAULT_SORT);+ const [page, setPage] = useState(1);+ const listRef = useRef<HTMLElement>(null);+ const plural = usageFormat.dimensionLabel({ dimension }).toLowerCase();++ if (isError) {+ return <DataFetchErrorState entity={plural} onRetry={onRetry} />;+ }+ if (isLoading || isNil(history)) {+ return <UsageListSkeleton />;+ }+ if (items.length === 0) {+ return (+ <UsageEmpty+ view={view}+ history={history}+ title={t('No {item} spend in this period', {+ item: usageFormat.dimensionBadge({ dimension }).toLowerCase(),+ })}+ />+ );+ }++ const needle = query.trim().toLowerCase();+ const matches = sortItems({+ items: items.filter((item) => {+ const name = usageAdapters.itemDisplayName({ item }).toLowerCase();+ return (+ needle.length === 0 ||+ name.includes(needle) ||+ (item.parent ?? '').toLowerCase().includes(needle) ||+ usageAdapters.itemSubtitle({ item }).toLowerCase().includes(needle)+ );+ }),+ sort,+ });+ const pageCount = Math.max(1, Math.ceil(matches.length / PAGE_SIZE));+ const current = Math.min(page, pageCount);+ const shown = matches.slice((current - 1) * PAGE_SIZE, current * PAGE_SIZE);+ const changeSort = (next: UsageSort): void => {+ setSort(next);+ setPage(1);+ };+ const goTo = (next: number): void => {+ setPage(next);+ listRef.current?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });+ };++ return (+ <section+ ref={listRef}+ className={cn(adminSurface.card, 'flex scroll-mt-4 flex-col')}+ >+ <div className="flex flex-wrap items-center justify-between gap-3 p-3">+ <div className="w-full sm:max-w-xs">+ <SearchInput+ value={query}+ onChange={(value) => {+ setQuery(value);+ setPage(1);+ }}+ placeholder={t('Search {items}', { items: plural })}+ />+ </div>+ <span className="px-1 text-xs tabular-nums text-gray-11">+ {needle.length === 0+ ? usageFormat.itemCountLabel({ dimension, count: items.length })+ : t('{shown} of {total}', {+ shown: usageFormat.whole(matches.length),+ total: usageFormat.itemCountLabel({+ dimension,+ count: items.length,+ }),+ })}+ </span>+ </div>+ {truncated && (+ <p className="px-4 pb-3 text-xs text-gray-11">+ {t(+ 'Only the top {count} by spend are listed, so search and pages cover these only.',+ { count: items.length },+ )}+ </p>+ )}+ <div+ className={cn(+ USAGE_LIST_GRID,+ 'border-y border-gray-6 px-5 py-2 text-xs text-gray-11',+ )}+ >+ <SortHeader+ label={usageFormat.dimensionBadge({ dimension })}+ column="name"+ sort={sort}+ onSort={changeSort}+ />+ <SortHeader+ label={t('Change')}+ column="change"+ sort={sort}+ onSort={changeSort}+ className="hidden md:flex"+ />+ <SortHeader+ label={t('Calls')}+ column="calls"+ sort={sort}+ onSort={changeSort}+ className="hidden md:flex"+ />+ <SortHeader+ label={t('Tokens')}+ column="tokens"+ sort={sort}+ onSort={changeSort}+ className="hidden md:flex"+ />+ <SortHeader+ label={t('Spend')}+ column="spend"+ sort={sort}+ onSort={changeSort}+ />+ <span />+ </div>+ {matches.length === 0 ? (+ <div className="flex flex-col items-center gap-3 px-5 py-12 text-center">+ <p className="text-sm text-gray-11">+ {t('No {items} match "{query}"', { items: plural, query })}+ </p>+ <Button variant="outline" size="sm" onClick={() => setQuery('')}>+ {t('Clear search')}+ </Button>+ </div>+ ) : (+ <ul className="flex flex-col divide-y divide-gray-6">+ {shown.map((item) => (+ <UsageListRow+ key={item.id}+ item={item}+ totalUsd={totalUsd}+ search={view.search}+ />+ ))}+ </ul>+ )}+ {pageCount > 1 && (+ <div className="flex items-center justify-between gap-3 border-t border-gray-6 px-5 py-3">+ <span className="text-xs tabular-nums text-gray-11">+ {t('{from}–{to} of {total}', {+ from: usageFormat.whole((current - 1) * PAGE_SIZE + 1),+ to: usageFormat.whole((current - 1) * PAGE_SIZE + shown.length),+ total: usageFormat.whole(matches.length),+ })}+ </span>+ <div className="flex items-center gap-2">+ <Button+ variant="outline"+ size="icon-sm"+ disabled={current === 1}+ onClick={() => goTo(current - 1)}+ aria-label={t('Previous page')}+ >+ <ChevronLeft className="size-4" />+ </Button>+ <span className="min-w-20 text-center text-xs tabular-nums text-gray-11">+ {t('Page {page} of {pages}', {+ page: usageFormat.whole(current),+ pages: usageFormat.whole(pageCount),+ })}+ </span>+ <Button+ variant="outline"+ size="icon-sm"+ disabled={current === pageCount}+ onClick={() => goTo(current + 1)}+ aria-label={t('Next page')}+ >+ <ChevronRight className="size-4" />+ </Button>+ </div>+ </div>+ )}+ </section>+ );+}++function UsageListRow({+ item,+ totalUsd,+ search,+}: {+ item: AiUsageItem;+ totalUsd: number;+ search: string;+}) {+ const share = totalUsd === 0 ? 0 : item.spendUsd / totalUsd;+ const name = usageAdapters.itemDisplayName({ item });+ return (+ <li>+ <Link+ to={`/platform/ai/usage/${item.dimension}/${item.id}${search}`}+ className={cn(+ USAGE_LIST_GRID,+ 'group px-5 py-3.5 transition-colors hover:bg-gray-2 focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-inset focus-visible:ring-gray-8/50',+ )}+ >+ <div className="flex min-w-0 items-center gap-3">+ <span className="flex size-8 shrink-0 items-center justify-center rounded-lg border border-gray-6 bg-gray-1">+ <ItemIcon item={item} />+ </span>+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <div className="flex min-w-0 items-center gap-2">+ <TextWithTooltip tooltipMessage={name}>+ <p className="truncate text-sm font-medium text-gray-12">+ {name}+ </p>+ </TextWithTooltip>+ {usageAdapters.hasSharedSpend({ item }) && (+ <SharedBadge item={item} />+ )}+ </div>+ <div className="flex min-w-0 items-center gap-2">+ <p className="truncate text-xs text-gray-11">+ {usageAdapters.itemSubtitle({ item })}+ </p>+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="h-1 w-24 shrink-0 overflow-hidden rounded-full bg-gray-3">+ <span+ className="block h-full rounded-full bg-accent-9"+ style={{ width: `${Math.max(share * 100, 2)}%` }}+ />+ </span>+ </TooltipTrigger>+ <TooltipContent side="top" sideOffset={6}>+ {t('{share} of all AI spend in this period', {+ share: usageFormat.percent(share),+ })}+ </TooltipContent>+ </Tooltip>+ </div>+ </div>+ </div>+ <span className="hidden justify-end md:flex">+ {item.comparable ? (+ <DeltaChip+ value={usageFormat.change({+ current: item.spendUsd,+ previous: item.previousSpendUsd,+ })}+ size="xs"+ />+ ) : (+ <span className="text-xs text-gray-9">—</span>+ )}+ </span>+ <span className="hidden text-right text-sm tabular-nums text-gray-11 md:block">+ {usageFormat.whole(item.calls)}+ </span>+ <span className="hidden text-right text-sm tabular-nums text-gray-11 md:block">+ {usageFormat.compact(item.tokens)}+ </span>+ <span className="text-right text-sm font-medium tabular-nums text-gray-12">+ {usageFormat.usd(item.spendUsd)}+ </span>+ <ChevronRight className="size-4 text-gray-9 transition-colors group-hover:text-gray-11" />+ </Link>+ </li>+ );+}++function SortHeader({+ label,+ column,+ sort,+ onSort,+ className,+}: {+ label: string;+ column: UsageSortColumn;+ sort: UsageSort;+ onSort: (sort: UsageSort) => void;+ className?: string;+}) {+ const active = sort.column === column;+ const Arrow = sort.desc ? ArrowDown : ArrowUp;+ return (+ <span+ className={cn(+ 'flex',+ column === 'name' ? 'justify-start' : 'justify-end',+ className,+ )}+ >+ <button+ type="button"+ onClick={() =>+ onSort({+ column,+ desc: active ? !sort.desc : column !== 'name',+ })+ }+ className={cn(+ 'flex cursor-pointer items-center gap-1 rounded-sm transition-colors hover:text-gray-12 focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-gray-8/50',+ active && 'font-medium text-gray-12',+ )}+ >+ {label}+ {active && <Arrow className="size-3" />}+ </button>+ </span>+ );+}++function sortItems({+ items,+ sort,+}: {+ items: AiUsageItem[];+ sort: UsageSort;+}): AiUsageItem[] {+ const direction = sort.desc ? -1 : 1;+ return [...items].sort((a, b) =>+ sort.column === 'name'+ ? direction *+ usageAdapters+ .itemDisplayName({ item: a })+ .localeCompare(usageAdapters.itemDisplayName({ item: b }))+ : direction *+ (sortValue({ item: a, column: sort.column }) -+ sortValue({ item: b, column: sort.column })),+ );+}++function sortValue({+ item,+ column,+}: {+ item: AiUsageItem;+ column: UsageSortColumn;+}): number {+ switch (column) {+ case 'name':+ case 'spend':+ return item.spendUsd;+ case 'change':+ return item.comparable+ ? usageFormat.change({+ current: item.spendUsd,+ previous: item.previousSpendUsd,+ }) ?? Number.POSITIVE_INFINITY+ : Number.NEGATIVE_INFINITY;+ case 'calls':+ return item.calls;+ case 'tokens':+ return item.tokens;+ }+}++const PAGE_SIZE = 25;+const DEFAULT_SORT: UsageSort = { column: 'spend', desc: true };++type UsageSortColumn = 'name' | 'spend' | 'change' | 'calls' | 'tokens';+type UsageSort = { column: UsageSortColumn; desc: boolean };diff --git a/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-skeletons.tsx b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-skeletons.tsxnew file mode 100644index 00000000000..84566fe88a9--- /dev/null+++ b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-skeletons.tsx@@ -0,0 +1,202 @@+import {+ AI_USAGE_RELATED_DIMENSIONS,+ AI_USAGE_SOURCE_DIMENSIONS,+ AiUsageDimension,+} from '@activepieces/shared';++import { adminSurface, StatGrid } from '@/app/components/admin';+import { Skeleton } from '@/components/ui/skeleton';+import { cn } from '@/lib/utils';++import { relatedSpan, USAGE_LIST_GRID } from './usage-bits';++export function UsageOverviewSkeleton() {+ return (+ <>+ <TilesSkeleton />+ <HeroSkeleton />+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-12">+ <DonutCardSkeleton className="lg:col-span-8" />+ <ListCardSkeleton className="lg:col-span-4" />+ <ListCardSkeleton className="lg:col-span-4" />+ <ListCardSkeleton className="lg:col-span-4" />+ <ListCardSkeleton className="lg:col-span-4" />+ <ListCardSkeleton className="lg:col-span-6" />+ <ListCardSkeleton className="lg:col-span-6" />+ </div>+ </>+ );+}++export function UsageDetailSkeleton({+ dimension,+}: {+ dimension: AiUsageDimension;+}) {+ const related = AI_USAGE_RELATED_DIMENSIONS[dimension];+ return (+ <>+ <TilesSkeleton />+ <HeroSkeleton />+ {AI_USAGE_SOURCE_DIMENSIONS.includes(dimension) && <DonutCardSkeleton />}+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-12">+ {related.map((other, index) => (+ <ListCardSkeleton+ key={other}+ className={relatedSpan({ index, count: related.length })}+ />+ ))}+ </div>+ </>+ );+}++export function UsageListSkeleton() {+ return (+ <section className={cn(adminSurface.card, 'flex flex-col')}>+ <div className="flex flex-wrap items-center justify-between gap-3 p-3">+ <Skeleton className="h-9 w-full rounded-lg sm:max-w-xs" />+ <Skeleton className="h-3 w-16" />+ </div>+ <div+ className={cn(USAGE_LIST_GRID, 'border-y border-gray-6 px-5 py-2.5')}+ >+ <Skeleton className="h-3 w-12" />+ <Skeleton className="hidden h-3 w-12 justify-self-end md:block" />+ <Skeleton className="hidden h-3 w-10 justify-self-end md:block" />+ <Skeleton className="hidden h-3 w-12 justify-self-end md:block" />+ <Skeleton className="h-3 w-12 justify-self-end" />+ <span />+ </div>+ <ul className="flex flex-col divide-y divide-gray-6">+ {LIST_ROWS.map((row) => (+ <li key={row} className={cn(USAGE_LIST_GRID, 'px-5 py-3.5')}>+ <div className="flex min-w-0 items-center gap-3">+ <Skeleton className="size-8 shrink-0 rounded-lg" />+ <div className="flex flex-1 flex-col gap-1.5">+ <Skeleton className="h-3.5 w-40" />+ <div className="flex items-center gap-2">+ <Skeleton className="h-3 w-20" />+ <Skeleton className="h-1 w-24 rounded-full" />+ </div>+ </div>+ </div>+ <Skeleton className="hidden h-3.5 w-10 justify-self-end md:block" />+ <Skeleton className="hidden h-3.5 w-12 justify-self-end md:block" />+ <Skeleton className="hidden h-3.5 w-10 justify-self-end md:block" />+ <Skeleton className="h-3.5 w-14 justify-self-end" />+ <Skeleton className="size-4 rounded-sm" />+ </li>+ ))}+ </ul>+ </section>+ );+}++function TilesSkeleton() {+ return (+ <StatGrid columns={3}>+ {TILES.map((tile) => (+ <div+ key={tile}+ className={cn(adminSurface.card, 'flex flex-col gap-3 p-5')}+ >+ <div className="flex items-center gap-2">+ <Skeleton className="size-4 rounded-sm" />+ <Skeleton className="h-3.5 w-24" />+ </div>+ <Skeleton className="h-8 w-28" />+ <Skeleton className="h-3 w-40" />+ </div>+ ))}+ </StatGrid>+ );+}++function HeroSkeleton() {+ return (+ <section className={cn(adminSurface.card, 'flex flex-col gap-5 p-5')}>+ <div className="flex flex-wrap items-start justify-between gap-4">+ <div className="flex flex-col gap-2">+ <Skeleton className="h-3.5 w-24" />+ <div className="flex items-center gap-3">+ <Skeleton className="h-9 w-36" />+ <Skeleton className="h-5 w-14 rounded-md" />+ <Skeleton className="h-3.5 w-28" />+ </div>+ </div>+ <div className="flex items-center gap-2">+ <Skeleton className="h-8 w-48 rounded-lg" />+ <Skeleton className="h-8 w-16 rounded-lg" />+ </div>+ </div>+ <div className="flex items-center gap-5">+ <Skeleton className="h-3 w-40" />+ <Skeleton className="h-3 w-40" />+ </div>+ <Skeleton className="h-[280px] w-full rounded-lg" />+ </section>+ );+}++function DonutCardSkeleton({ className }: { className?: string }) {+ return (+ <section+ className={cn(adminSurface.card, 'flex flex-col gap-4 p-5', className)}+ >+ <CardTitleSkeleton />+ <div className="flex flex-1 flex-col items-center gap-6 sm:flex-row sm:gap-10">+ <Skeleton className="aspect-square w-full max-w-56 shrink-0 rounded-full" />+ <div className="flex w-full flex-col gap-4">+ {ROWS.map((row) => (+ <div key={row} className="flex items-center gap-3">+ <Skeleton className="size-2.5 rounded-full" />+ <Skeleton className="h-3.5 flex-1" />+ <Skeleton className="h-3.5 w-14" />+ </div>+ ))}+ </div>+ </div>+ </section>+ );+}++function ListCardSkeleton({ className }: { className?: string }) {+ return (+ <section+ className={cn(adminSurface.card, 'flex flex-col gap-3 p-5', className)}+ >+ <CardTitleSkeleton />+ <ul className="flex flex-col gap-1">+ {ROWS.map((row) => (+ <li key={row} className="flex flex-col gap-1.5 py-1.5">+ <div className="flex items-center gap-2.5">+ <div className="flex flex-1 flex-col gap-1.5">+ <Skeleton className="h-3.5 w-32" />+ <Skeleton className="h-3 w-20" />+ </div>+ <Skeleton className="h-3.5 w-14" />+ </div>+ <Skeleton className="h-1 w-full rounded-full" />+ </li>+ ))}+ </ul>+ </section>+ );+}++function CardTitleSkeleton() {+ return (+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-2">+ <Skeleton className="size-4 rounded-sm" />+ <Skeleton className="h-4 w-24" />+ </div>+ <Skeleton className="h-3.5 w-12" />+ </div>+ );+}++const TILES = ['pace', 'calls', 'tokens'];+const ROWS = ['a', 'b', 'c', 'd', 'e'];+const LIST_ROWS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];diff --git a/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-source-donut.tsx b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-source-donut.tsxnew file mode 100644index 00000000000..1e7d81837ed--- /dev/null+++ b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-source-donut.tsx@@ -0,0 +1,172 @@+import { isNil } from '@activepieces/core-utils';+import { AiUsageSourceSpend } from '@activepieces/shared';+import { t } from 'i18next';+import { useState } from 'react';+import { Cell, Pie, PieChart, Sector, SectorProps } from 'recharts';++import { adminSurface } from '@/app/components/admin';+import { ChartConfig, ChartContainer } from '@/components/ui/chart';+import { cn } from '@/lib/utils';++import { usageFormat } from './usage-format';++export function UsageSourceDonut({+ sources,+ className,+}: {+ sources: AiUsageSourceSpend[];+ className?: string;+}) {+ const [activeIndex, setActiveIndex] = useState<number | null>(null);+ const totalUsd = sources.reduce((sum, item) => sum + item.spendUsd, 0);+ const active = isNil(activeIndex) ? undefined : sources[activeIndex];+ const config = Object.fromEntries(+ sources.map((item, index) => [+ item.source,+ {+ label: usageFormat.sourceLabel({ source: item.source }),+ color: colorAt({ index }),+ },+ ]),+ ) satisfies ChartConfig;++ return (+ <section+ className={cn(adminSurface.card, 'flex flex-col gap-4 p-5', className)}+ >+ <h2 className="text-base font-semibold text-gray-12">+ {t('Spend by source')}+ </h2>+ <div className="flex flex-1 flex-col items-center gap-6 sm:flex-row sm:gap-10">+ <div className="relative aspect-square w-full max-w-56 shrink-0">+ <ChartContainer config={config} className="aspect-square w-full">+ <PieChart>+ {totalUsd === 0 && (+ <Pie+ data={EMPTY_RING}+ dataKey="value"+ innerRadius="62%"+ outerRadius="86%"+ strokeWidth={0}+ fill="var(--gray-3)"+ isAnimationActive={false}+ />+ )}+ <Pie+ data={sources}+ dataKey="spendUsd"+ nameKey="source"+ innerRadius="62%"+ outerRadius="86%"+ paddingAngle={1.5}+ strokeWidth={0}+ activeIndex={activeIndex ?? undefined}+ activeShape={ActiveSlice}+ onMouseEnter={(_, index) => setActiveIndex(index)}+ onMouseLeave={() => setActiveIndex(null)}+ >+ {sources.map((item, index) => (+ <Cell+ key={item.source}+ fill={colorAt({ index })}+ className="cursor-pointer outline-none transition-opacity duration-150"+ opacity={+ isNil(activeIndex) || activeIndex === index ? 1 : 0.35+ }+ />+ ))}+ </Pie>+ </PieChart>+ </ChartContainer>+ <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-0.5 px-10 text-center">+ <span className="truncate text-xs text-gray-11">+ {isNil(active)+ ? t('Total')+ : usageFormat.sourceLabel({ source: active.source })}+ </span>+ <span className="text-xl font-semibold tracking-tight tabular-nums text-gray-12">+ {usageFormat.usd(active?.spendUsd ?? totalUsd)}+ </span>+ {!isNil(active) && (+ <span className="text-xs tabular-nums text-gray-11">+ {usageFormat.percent(+ totalUsd === 0 ? 0 : active.spendUsd / totalUsd,+ )}+ </span>+ )}+ </div>+ </div>+ {sources.length === 0 && (+ <p className="w-full flex-1 text-sm text-gray-11">+ {t(+ 'Flow steps, Run Agent steps, agents, chat and knowledge base each get a slice once they use AI.',+ )}+ </p>+ )}+ <ul className="flex w-full min-w-0 flex-1 flex-col gap-1 empty:hidden">+ {sources.map((item, index) => {+ const share = totalUsd === 0 ? 0 : item.spendUsd / totalUsd;+ const dimmed = !isNil(activeIndex) && activeIndex !== index;+ return (+ <li+ key={item.source}+ className={cn(+ 'flex flex-col gap-1.5 rounded-md py-1.5 transition-opacity duration-150',+ dimmed && 'opacity-40',+ )}+ onMouseEnter={() => setActiveIndex(index)}+ onMouseLeave={() => setActiveIndex(null)}+ >+ <div className="flex items-center gap-2.5 text-sm">+ <span+ className="size-2.5 shrink-0 rounded-xs"+ style={{ backgroundColor: colorAt({ index }) }}+ />+ <span className="min-w-0 flex-1 truncate text-gray-12">+ {usageFormat.sourceLabel({ source: item.source })}+ </span>+ <span className="font-medium tabular-nums text-gray-12">+ {usageFormat.usd(item.spendUsd)}+ </span>+ <span className="w-10 text-right tabular-nums text-gray-11">+ {usageFormat.percent(share)}+ </span>+ </div>+ <div className="h-1 overflow-hidden rounded-full bg-gray-3">+ <div+ className="h-full rounded-full"+ style={{+ width: `${Math.max(share * 100, 1)}%`,+ backgroundColor: colorAt({ index }),+ }}+ />+ </div>+ </li>+ );+ })}+ </ul>+ </div>+ </section>+ );+}++function ActiveSlice(props: SectorProps) {+ return (+ <Sector {...props} outerRadius={(props.outerRadius ?? 0) + ACTIVE_GROWTH} />+ );+}++function colorAt({ index }: { index: number }): string {+ return SLICE_COLORS[index % SLICE_COLORS.length];+}++const EMPTY_RING = [{ value: 1 }];+const ACTIVE_GROWTH = 6;++const SLICE_COLORS = [+ 'var(--chart-1)',+ 'var(--chart-2)',+ 'var(--chart-3)',+ 'var(--chart-4)',+ 'var(--chart-5)',+];diff --git a/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-top-list.tsx b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-top-list.tsxnew file mode 100644index 00000000000..04fabd8f1cb--- /dev/null+++ b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-top-list.tsx@@ -0,0 +1,206 @@+import { isNil } from '@activepieces/core-utils';+import {+ AiUsageDimension,+ AiUsageItem,+ ApEdition,+ ApFlagId,+} from '@activepieces/shared';+import { t } from 'i18next';+import { ChevronRight, ExternalLink, ReceiptText } from 'lucide-react';+import { Link } from 'react-router-dom';++import { adminSurface } from '@/app/components/admin';+import { TextWithTooltip } from '@/components/custom/text-with-tooltip';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@/components/ui/tooltip';+import { flagsHooks } from '@/hooks/flags-hooks';+import { cn } from '@/lib/utils';++import { usageAdapters } from './usage-adapters';+import { dimensionIcon, ItemIcon, UsageEmptyState } from './usage-bits';+import { usageFormat } from './usage-format';++export function UsageTopList({+ dimension,+ items,+ totalUsd,+ search,+ title,+ subtitle,+ shareOf,+ seeAllLabel,+ className,+}: UsageTopListProps) {+ const TitleIcon = dimensionIcon({ dimension });+ return (+ <section+ className={cn(adminSurface.card, 'flex flex-col gap-3 p-5', className)}+ >+ {items.length > 0 && (+ <div className="flex items-center justify-between gap-2">+ <div className="flex flex-col gap-0.5">+ <h2 className="flex items-center gap-2 text-base font-semibold text-gray-12">+ <TitleIcon className="size-4 shrink-0 text-gray-11" />+ {title ?? usageFormat.dimensionLabel({ dimension })}+ </h2>+ {subtitle && <p className="text-xs text-gray-11">{subtitle}</p>}+ </div>+ <Button variant="ghost" size="xs" asChild>+ <Link to={`/platform/ai/usage/${dimension}${search}`}>+ {seeAllLabel ?? t('See all')}+ <ChevronRight className="size-3.5" />+ </Link>+ </Button>+ </div>+ )}+ {items.length === 0 ? (+ <UsageEmptyState+ dimension={dimension}+ label={title ?? usageFormat.dimensionLabel({ dimension })}+ />+ ) : (+ <ul className="flex flex-col gap-1">+ {items.map((item) => (+ <UsageTopRow+ key={item.id}+ item={item}+ totalUsd={totalUsd}+ search={search}+ shareOf={shareOf}+ />+ ))}+ </ul>+ )}+ </section>+ );+}++export function UsageTopRow({+ item,+ totalUsd,+ search,+ shareOf,+}: {+ item: AiUsageItem;+ totalUsd: number;+ search: string;+ shareOf?: string;+}) {+ const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);+ const share = totalUsd === 0 ? 0 : item.spendUsd / totalUsd;+ const name = usageAdapters.itemDisplayName({ item });+ return (+ <li className="flex items-center gap-2">+ <Link+ to={`/platform/ai/usage/${item.dimension}/${item.id}${search}`}+ className="flex min-w-0 flex-1 flex-col gap-1.5 rounded-md py-1.5 focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-gray-8/50"+ >+ <div className="flex min-w-0 items-center gap-2.5">+ {(item.dimension === 'key' || item.dimension === 'model') && (+ <ItemIcon item={item} />+ )}+ <div className="flex min-w-0 flex-1 flex-col">+ <TextWithTooltip tooltipMessage={name}>+ <p className="truncate text-sm font-medium text-gray-12">+ {name}+ </p>+ </TextWithTooltip>+ <div className="flex min-h-4 min-w-0 items-center gap-1.5">+ <p className="truncate text-xs text-gray-11">+ {usageAdapters.itemSubtitle({ item })}+ </p>+ {usageAdapters.hasSharedSpend({ item }) && (+ <SharedBadge item={item} />+ )}+ </div>+ </div>+ <div className="flex shrink-0 flex-col items-end">+ <span className="text-sm font-medium tabular-nums text-gray-12">+ {usageFormat.usd(item.spendUsd)}+ </span>+ </div>+ <ChevronRight className="size-4 shrink-0 text-gray-9" />+ </div>+ <Tooltip>+ <TooltipTrigger asChild>+ <div className="h-1 overflow-hidden rounded-full bg-gray-3">+ <div+ className="h-full rounded-full bg-accent-9"+ style={{ width: `${Math.max(share * 100, 1)}%` }}+ />+ </div>+ </TooltipTrigger>+ <TooltipContent side="top" sideOffset={6}>+ {shareOf+ ? t('{share} of {whole}', {+ share: usageFormat.percent(share),+ whole: shareOf,+ })+ : t('{share} of all AI spend in this period', {+ share: usageFormat.percent(share),+ })}+ </TooltipContent>+ </Tooltip>+ </Link>+ {item.dimension === 'key' && (+ <DashboardButton+ url={usageAdapters.dashboardUrlOf({ item, edition })}+ />+ )}+ </li>+ );+}++function DashboardButton({ url }: { url: string | undefined }) {+ if (isNil(url)) {+ return <span className="size-8 shrink-0" />;+ }+ return (+ <Button variant="ghost" size="icon-sm" asChild>+ {url.startsWith('/') ? (+ <Link to={url} aria-label={t('Open billing')}>+ <ReceiptText className="size-3.5" />+ </Link>+ ) : (+ <a+ href={url}+ target="_blank"+ rel="noreferrer"+ aria-label={t('Open provider dashboard')}+ >+ <ExternalLink className="size-3.5" />+ </a>+ )}+ </Button>+ );+}++export function SharedBadge({ item }: { item: AiUsageItem }) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant="info">{t('Shared')}</Badge>+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ {usageAdapters.sharedBadgeText({ item })}+ </TooltipContent>+ </Tooltip>+ );+}++type UsageTopListProps = {+ dimension: AiUsageDimension;+ items: AiUsageItem[];+ totalUsd: number;+ search: string;+ title?: string;+ subtitle?: string;+ shareOf?: string;+ seeAllLabel?: string;+ className?: string;+};diff --git a/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-types.ts b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-types.tsnew file mode 100644index 00000000000..6f6b09e68eb--- /dev/null+++ b/packages/web/src/app/routes/platform/setup/ai/usage-tab/usage-types.ts@@ -0,0 +1,9 @@+export const USAGE_METRICS: UsageMetric[] = ['spend', 'calls', 'tokens'];++export type UsageMetric = 'spend' | 'calls' | 'tokens';++export type UsagePoint = {+ label: string;+ current: number | null;+ previous: number | null;+};diff --git a/packages/web/src/features/agents/ai-providers.ts b/packages/web/src/features/agents/ai-providers.tsindex c0c07c5cc5a..a2a37ee2a7b 100644--- a/packages/web/src/features/agents/ai-providers.ts+++ b/packages/web/src/features/agents/ai-providers.ts@@ -11,6 +11,7 @@ export const SUPPORTED_AI_PROVIDERS: AiProviderInfo[] = [2. Once on the website, locate and click on the option to obtain your Claude API Key.`),logoUrl: 'https://cdn.activepieces.com/pieces/claude.png',+ dashboardUrl: 'https://console.anthropic.com/settings/billing',},{provider: AIProviderName.BEDROCK,@@ -76,6 +77,7 @@ export const SUPPORTED_AI_PROVIDERS: AiProviderInfo[] = [2. Once on the website, locate and click on the option to obtain your Google API Key.`),logoUrl: 'https://cdn.activepieces.com/pieces/google-gemini.png',+ dashboardUrl: 'https://aistudio.google.com/usage',},{provider: AIProviderName.MINIMAX,@@ -99,6 +101,7 @@ This connects to MiniMax's international endpoint. A key from the China platform2. Navigate to **API Keys** in your account settings.3. Click **Create new key**, copy the key, and paste it below.`),+ dashboardUrl: 'https://console.mistral.ai/usage',},{provider: AIProviderName.MOONSHOT,@@ -124,6 +127,7 @@ This connects to Moonshot's international endpoint. A key from the China platforIt is strongly recommended that you add your credit card information to your OpenAI account and upgrade to the paid plan **before** generating the API Key. This will help you prevent 429 errors.`),logoUrl: 'https://cdn.activepieces.com/pieces/openai.png',+ dashboardUrl: 'https://platform.openai.com/usage',},{provider: AIProviderName.OPENROUTER,@@ -132,6 +136,7 @@ It is strongly recommended that you add your credit card information to your Opemarkdown: t(`Follow these instructions to get your OpenRouter API Key:1. Go to https://openrouter.ai/settings/keys.2. Once on the website, locate and click on the option to obtain your OpenRouter API Key.`),+ dashboardUrl: 'https://openrouter.ai/activity',},{provider: AIProviderName.QWEN,@@ -184,4 +189,5 @@ export type AiProviderInfo = {name: string;markdown: string;logoUrl: string;+ dashboardUrl?: string;};diff --git a/packages/web/src/features/ai-usage/api/ai-usage-api.ts b/packages/web/src/features/ai-usage/api/ai-usage-api.tsnew file mode 100644index 00000000000..687df37199e--- /dev/null+++ b/packages/web/src/features/ai-usage/api/ai-usage-api.ts@@ -0,0 +1,56 @@+import {+ AiUsageDetail,+ AiUsageDimension,+ AiUsageItemList,+ AiUsageOverview,+ AiUsagePeriod,+ AiUsageScope,+} from '@activepieces/shared';++import { api } from '@/lib/api';++export const aiUsageApi = {+ getOverview({+ period,+ scope,+ }: {+ period: AiUsagePeriod;+ scope: AiUsageScope;+ }): Promise<AiUsageOverview> {+ return api.get<AiUsageOverview>('/v1/ai-usage/overview', {+ period,+ scope,+ });+ },+ getItems({+ dimension,+ period,+ scope,+ }: {+ dimension: AiUsageDimension;+ period: AiUsagePeriod;+ scope: AiUsageScope;+ }): Promise<AiUsageItemList> {+ return api.get<AiUsageItemList>('/v1/ai-usage/items', {+ dimension,+ period,+ scope,+ });+ },+ getDetail({+ dimension,+ id,+ period,+ scope,+ }: {+ dimension: AiUsageDimension;+ id: string;+ period: AiUsagePeriod;+ scope: AiUsageScope;+ }): Promise<AiUsageDetail> {+ return api.get<AiUsageDetail>(`/v1/ai-usage/items/${dimension}/${id}`, {+ period,+ scope,+ });+ },+};diff --git a/packages/web/src/features/ai-usage/hooks/ai-usage-hooks.ts b/packages/web/src/features/ai-usage/hooks/ai-usage-hooks.tsnew file mode 100644index 00000000000..326f862cfee--- /dev/null+++ b/packages/web/src/features/ai-usage/hooks/ai-usage-hooks.ts@@ -0,0 +1,97 @@+import { isNil } from '@activepieces/core-utils';+import {+ AiUsageDimension,+ AiUsagePeriod,+ AiUsageScope,+} from '@activepieces/shared';+import { useQuery } from '@tanstack/react-query';++import { platformHooks } from '@/hooks/platform-hooks';++import { aiUsageApi } from '../api/ai-usage-api';++function staleTimeMsFor({ period }: { period: AiUsagePeriod }): number {+ return PERIOD_STALE_TIME_SECONDS[period] * 1000;+}++function listStaleTimeMsFor({ period }: { period: AiUsagePeriod }): number {+ return Math.min(staleTimeMsFor({ period }), LIST_AND_DETAIL_MAX_STALE_MS);+}++export const aiUsageHooks = {+ useUsageOverview: ({+ period,+ scope,+ }: {+ period: AiUsagePeriod;+ scope: AiUsageScope;+ }) => {+ const { platform } = platformHooks.useCurrentPlatform();+ return useQuery({+ queryKey: ['ai-usage-overview', period, scope],+ queryFn: () => aiUsageApi.getOverview({ period, scope }),+ enabled: platform.plan.aiProvidersEnabled,+ staleTime: staleTimeMsFor({ period }),+ });+ },+ useUsageItems: ({+ dimension,+ period,+ scope,+ }: {+ dimension: AiUsageDimension | undefined;+ period: AiUsagePeriod;+ scope: AiUsageScope;+ }) => {+ const { platform } = platformHooks.useCurrentPlatform();+ return useQuery({+ queryKey: ['ai-usage-items', dimension, period, scope],+ queryFn: () => {+ if (isNil(dimension)) {+ return Promise.reject(new Error('missing dimension'));+ }+ return aiUsageApi.getItems({ dimension, period, scope });+ },+ enabled: platform.plan.aiProvidersEnabled && !isNil(dimension),+ staleTime: listStaleTimeMsFor({ period }),+ });+ },+ useUsageDetail: ({+ dimension,+ id,+ period,+ scope,+ }: {+ dimension: AiUsageDimension | undefined;+ id: string | undefined;+ period: AiUsagePeriod;+ scope: AiUsageScope;+ }) => {+ const { platform } = platformHooks.useCurrentPlatform();+ return useQuery({+ queryKey: ['ai-usage-detail', dimension, id, period, scope],+ queryFn: () => {+ if (isNil(dimension) || isNil(id)) {+ return Promise.reject(new Error('missing dimension or id'));+ }+ return aiUsageApi.getDetail({ dimension, id, period, scope });+ },+ enabled:+ platform.plan.aiProvidersEnabled && !isNil(dimension) && !isNil(id),+ staleTime: listStaleTimeMsFor({ period }),+ });+ },+};++const PERIOD_STALE_TIME_SECONDS: Record<AiUsagePeriod, number> = {+ '1h': 60,+ '6h': 60,+ '12h': 120,+ '24h': 120,+ '7d': 300,+ '30d': 600,+ '90d': 900,+ 'this-month': 600,+ 'last-month': 3600,+};+const LIST_AND_DETAIL_MAX_STALE_MS = 5 * 60 * 1000;diff --git a/packages/web/src/features/ai-usage/index.ts b/packages/web/src/features/ai-usage/index.tsnew file mode 100644index 00000000000..bf226df4174--- /dev/null+++ b/packages/web/src/features/ai-usage/index.ts@@ -0,0 +1,2 @@+export { aiUsageApi } from './api/ai-usage-api';+export { aiUsageHooks } from './hooks/ai-usage-hooks';