Skip to content

feat(usage): add global usage dashboard and per-session usage panel - #500

Open
chriswritescode-dev wants to merge 9 commits into
mainfrom
om-218-usage-analytics-global-dashboard-and-per
Open

chriswritescode-dev wants to merge 9 commits into
mainfrom
om-218-usage-analytics-global-dashboard-and-per

Conversation

@chriswritescode-dev

@chriswritescode-dev chriswritescode-dev commented Nov 30, 2026 •

Copy link
Copy Markdown
Owner

User description

Summary

  • Adds a read-only global Usage dashboard at ?usage=open, opened from the sidebar footer and the mobile More drawer: range selector (15m to all time plus custom), spend, tokens, prompts, steps, active days and streak, token composition, activity chart, models, tool reliability and sessions by spend, with a multi-select model filter that hides metrics that cannot be split per model.
  • Adds a per-session usage panel at ?panel=usage (and ?dialog=usage from the mobile More drawer): spend, average tokens/s, tokens, steps, composition, models and tools, aggregated from the session's newest assistant steps.
  • Frontend only: reads OpenCode's GET /api/experimental/session/stats through the existing /api/opencode proxy, so the local and linked servers behave the same, with types from @opencode/client and no new backend storage. The stats endpoint failing degrades to a "Usage unavailable" state.

Closes #478

Validation

  • pnpm install --frozen-lockfile — pass
  • pnpm --filter frontend typecheck — pass
  • usage component/lib/hook tests — pass
  • pnpm lint — pass
  • pnpm --filter frontend build — pass
  • Manual desktop and mobile checks against real OpenCode servers (local and linked), including the mobile table clipping fix in 5dc76b2

PR Type

Enhancement, Tests


Description

  • Add full-screen global usage dashboard via ?usage=open.

  • Add per-session usage panel at ?panel=usage and ?dialog=usage.

  • Filter usage by range and selected models, persisted locally.

  • Wire Usage entries into sidebar, mobile menus and tool rail.

  • Add usage data layer, aggregation helpers and extensive tests.


Diagram Walkthrough

flowchart LR
  Stats["OpenCode stats endpoint"] -- "proxied fetch" --> API["usage API + hooks"]
  Messages["Session assistant messages"] -- "paged fetch" --> API
  API -- "aggregated stats" --> Dashboard["Global Usage dialog"]
  API -- "assistant steps" --> SessionPanel["Session usage panel"]
  Nav["Sidebar, mobile menu, tool rail"] -- "opens" --> Dashboard
  Nav -- "opens" --> SessionPanel
  Dashboard -- "range and model selections" --> Prefs["localStorage preferences"]
  SessionPanel -- "range selection" --> Prefs
  Dashboard -- "sessions by spend" --> Sessions["Session list links"]
Loading

File Walkthrough

Relevant files
Enhancement
27 files
UsageDashboard.tsx
Global usage dashboard with range and model filters           
+165/-0 
SessionUsageContent.tsx
Session usage panel aggregating local assistant steps       
+120/-0 
UsageSessionsTable.tsx
Sessions by spend table with paging and range filtering   
+200/-0 
usage.ts
Stats request and paged assistant message loader                 
+50/-0   
usageStats.ts
Usage aggregation, tool stats and formatting helpers         
+223/-0 
usageRange.ts
Usage range presets, resolution and validation schema       
+123/-0 
useUsage.ts
Query hooks for stats and session usage                                   
+49/-0   
useUsagePreferences.ts
Persist usage range and model filter preferences                 
+55/-0   
useUsageDialog.ts
URL-driven usage dialog open and close                                     
+27/-0   
UsageDialog.tsx
Full-screen usage dialog with linked server switcher         
+38/-0   
SessionUsageDialog.tsx
Session usage full-screen mobile dialog shell                       
+27/-0   
UsageRangePicker.tsx
Preset and custom range selector inputs                                   
+88/-0   
UsageModelFilter.tsx
Multi-select model filter with overflow badge                       
+55/-0   
UsageActivityChart.tsx
Daily activity bar chart scaled by busiest day                     
+34/-0   
UsageModelsTable.tsx
Models table with steps, tokens, cost and share                   
+48/-0   
UsageToolsTable.tsx
Tool reliability table with counts and P50                             
+58/-0   
UsageSummaryCards.tsx
Summary cards for spend, tokens, steps and throughput       
+61/-0   
UsageTokenComposition.tsx
Token composition card with all token fields                         
+33/-0   
moreDrawerItems.ts
Add Usage and Session usage navigation entries                     
+19/-3   
MoreDrawer.tsx
Open usage dialogs from mobile menu items                               
+7/-1     
DesktopSidebar.tsx
Add Usage entry to sidebar footer                                               
+6/-2     
ToolSidePanel.tsx
Register session usage as a tool panel                                     
+3/-1     
useToolPanel.ts
Treat usage as a valid panel tool                                               
+1/-1     
opencode.ts
Allow filtering session messages by type                                 
+2/-0     
App.tsx
Mount global usage dialog in app shell                                     
+2/-0     
SessionDetail.tsx
Render session usage dialog when undocked                               
+8/-0     
index.ts
Re-export usage stats and token types                                       
+7/-0     
Tests
22 files
usage.test.ts
Test stats requests and assistant message paging                 
+206/-0 
usageRange.test.ts
Test range presets, resolution and schema validation         
+253/-0 
usageStats.test.ts
Test aggregation, throughput, tools and formatting             
+340/-0 
useUsage.test.tsx
Test usage query keys and fetch behavior                                 
+177/-0 
useUsageDialog.test.tsx
Test dialog URL state and history handling                             
+118/-0 
useUsagePreferences.test.tsx
Test persisted range and model preferences                             
+174/-0 
UsageDashboard.test.tsx
Test dashboard metrics, filters and error states                 
+452/-0 
SessionUsageContent.test.tsx
Test session panel filtering, paging and errors                   
+448/-0 
UsageSessionsTable.test.tsx
Test session ranking, paging, caps and links                         
+574/-0 
UsageDialog.test.tsx
Test global dialog opening and server scoping                       
+187/-0 
UsageRangePicker.test.tsx
Test range preset and custom input behavior                           
+92/-0   
UsageModelFilter.test.tsx
Test model multi-select and badge rendering                           
+92/-0   
UsageActivityChart.test.tsx
Test activity bars and zero-step handling                               
+67/-0   
UsageModelsTable.test.tsx
Test model rows, shares and empty states                                 
+92/-0   
UsageToolsTable.test.tsx
Test tool rows, totals and missing P50                                     
+72/-0   
UsageSummaryCards.test.tsx
Test summary card labels and optional stats                           
+86/-0   
UsageTokenComposition.test.tsx
Test token composition labels and values                                 
+38/-0   
MoreDrawer.test.tsx
Test mobile usage entries and dialog opening                         
+41/-1   
DesktopSidebar.test.tsx
Test desktop sidebar usage entry behavior                               
+14/-1   
moreDrawerItems.test.ts
Update nav model expectations for usage items                       
+55/-34 
ToolSidePanel.test.tsx
Test session usage tool for local and linked servers         
+80/-1   
useToolPanel.test.ts
Test usage panel tool rewriting to dialog                               
+25/-0   
Additional files
1 files
SessionUsageDialog.test.tsx +84/-0   

@lil-worker-cstech

lil-worker-cstech Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit dd60803)

Since the last review — 1 finding was open on the previous HEAD

  • ✅ 1 addressed by the pushes since then: frontend/src/components/usage/UsageSessionsTable.tsx:123-127
  • ✚ 1 newly found in this run

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

478 - Partially compliant

Compliant requirements:

  • Global Usage dialog driven by ?usage=open, with sidebar and mobile entries
  • Range presets plus custom range, persisted, defaulting to 4h
  • Summary cards, token composition, models table and tool reliability
  • Activity chart limited to multi-day ranges
  • Model filter with "All models", +N more badge, hidden unsplittable sections and explanatory note
  • Reset filters button
  • Per-session usage panel with range and model filters, throughput formula, paging limits, truncation note and pruning
  • Mobile Workspace "Session usage" entry for local and linked sessions
  • Frontend only, using shared types from the client
  • Unit and component tests

Non-compliant requirements:

  • The sessions-by-spend table has no Steps or Avg tokens/s columns
  • The storage keys are oc:usage:range, oc:usage:session-range and oc:usage:models, not the ocm.usage-*.v1 names in the ticket

Requires further human verification:

  • Mobile full-screen sheet layout and table clipping
  • Back-button behavior on real browsers when the dialog was opened with replace from the More drawer
  • Behavior against real local and linked OpenCode servers, including ones without the experimental stats endpoint
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
⚠️ Risk level: Medium
✅ Merge recommendation: Needs review
Merge recommendation checks
✅ CI on reviewed head: passed
✅ Head is current with its base: up to date
⚠️ Human authors: bot or unlinked author
✅ No sensitive paths or risky changes: none detected
⚠️ Changed lines within cap: 5321 changed lines exceeds cap 100
🔎 Failure modes

What: The sessions-by-spend table can keep requesting the next page without end, because the auto-paging effect never reaches the 500-session cap.
Where: frontend/src/components/usage/UsageSessionsTable.tsx:UsageSessionsTable
Trigger: A server returns an empty (or fully duplicate) session page that still carries a `next` cursor. `sessions.length` stops growing, but each `isFetchingNextPage` true→false transition runs the effect again.
Detected by: Nothing. No test covers an empty page that still has a cursor.
Covered in this PR: No

What: Sessions that were active in the range can be left out of "Sessions by spend", because paging stops based on the last loaded session's `time.updated`.
Where: frontend/src/components/usage/UsageSessionsTable.tsx:UsageSessionsTable
Trigger: The session list endpoint returns sessions in an order other than `time.updated` descending, for example by creation time.
Detected by: Nothing. The tests use fixtures that are already sorted by `updated`.
Covered in this PR: No

What: The per-session panel shows stale totals for a session that is still running, because the query is only refetched on remount.
Where: frontend/src/hooks/useUsage.ts:buildSessionUsageQueryOptions
Trigger: The panel is open while the agent keeps producing steps. `refetchOnWindowFocus` is false and nothing invalidates `sessionUsageQueryKey`.
Detected by: Nothing
Covered in this PR: No

🧪 PR contains tests
🔒 No security concerns identified
✅ Resolved findings

frontend/src/components/usage/UsageSessionsTable.tsx:123-127

Heavy per-row fetching

To show the Steps and Avg tokens/s columns, each visible row runs loadSessionUsageMessages. That is up to 5 requests of 200 full assistant messages, including tool content, per session. Opening the dashboard can therefore send 50 or more large message requests on top of paging through up to 500 sessions, and each "Show more" adds 10 more sessions to load. On large or remote servers this makes the dashboard slow and expensive. Consider loading these columns only on demand, using a lighter count source, or capping pages per row to 1.

frontend/src/components/usage/UsageDashboard.tsx:61-66

Saved filter wiped

The pruning effect writes the reduced list back to storage through setModels. Switching to a short range where the selected models were not used therefore deletes the user's saved global model filter for good, which goes against "the selected models are persisted". Consider pruning only the displayed selection, for example models.filter(available.has) computed during render, without writing it back to storage.

frontend/src/components/usage/UsageSessionsTable.tsx:42-44

Range end ignored

isSessionActiveFrom checks only range.from, so with a custom range in the past every newer session passes the filter. Sessions created after the range ended show up in "Sessions by spend" with their lifetime cost. Sessions updated after to should still be kept, as the existing test expects, but sessions created after to should be excluded.

@lil-worker-cstech

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 6d8be37

Comment on lines +66 to +74
const isAtSessionCap = sessions.length >= SESSION_CAP
const showsCapNote = isAtSessionCap && hasNextPage && isOldestLoadedInRange
const willLoadMoreSessions =
hasLoadedSessions && hasNextPage === true && !isError && !isAtSessionCap && isOldestLoadedInRange

useEffect(() => {
if (!willLoadMoreSessions || isFetchingNextPage) return
void fetchNextPage()
}, [fetchNextPage, isFetchingNextPage, sessions.length, willLoadMoreSessions])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unbounded auto-paging

The effect fetches the next page whenever willLoadMoreSessions is true and no fetch is running. The 500-session cap is based on sessions.length. If a page comes back empty (or adds no new sessions) but still has a next cursor, the count never grows. Each finished fetch toggles isFetchingNextPage, which runs the effect again, so the table keeps requesting pages from the server indefinitely. Consider capping by the number of pages fetched, or stopping when a page adds no sessions.

@lil-worker-cstech

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit dd60803

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Usage analytics: global dashboard and per-session usage panel

1 participant