Skip to content

fix(studio): refresh profile stats and mode-aware activity summary - #9402

Merged
danielhanchen merged 6 commits into
unslothai:mainfrom
Souravrajvi0:feat/fix-profile-stats-refresh-2256
Sep 8, 2026
Merged

danielhanchen merged 6 commits into
unslothai:mainfrom
Souravrajvi0:feat/fix-profile-stats-refresh-2256

Conversation

@Souravrajvi0

@Souravrajvi0 Souravrajvi0 commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #9337

Problem

  • Switching Daily / Weekly / Cumulative on the Token activity card updated only the graph; the subtitle below stayed frozen (e.g. always "42.9K tokens over the last 43 weeks").
  • Profile stats were fetched once on mount and could go stale if the user chatted in another tab and returned to Settings → Profile.

Changes

  • Mode-aware subtitle: each view now shows a summary that matches the selected mode:
    • Daily — total tokens in the visible window
    • Weekly — peak week total in the visible window
    • Cumulative — accumulated total over the visible window
  • Stats refresh: refetch on tab focus/visibility and when Settings reopens.
  • Added activitySummaryForMode() helper with unit tests; updated all 12 locale files.

Testing

  • npm test -- tests/profile-stats-format.test.ts — all 1624 tests pass (includes new activitySummaryForMode coverage)
  • npx tsc --noEmit — no type errors

Update the token activity card subtitle when switching Daily, Weekly, or
Cumulative views, and refetch profile stats when the tab regains focus or
settings reopens so headline numbers stay current.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: da17dbb4af

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Headless browser check that the token activity subtitle updates across
Daily, Weekly, and Cumulative modes against a mocked API.
@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the subtitle in studio/frontend/src/features/profile/components/stats/token-activity-card.tsx does not follow the Daily/Weekly/Cumulative switch, and the helper plus locale updates look right. Could you drop the new puppeteer e2e files and their mock server and keep this to the card, the hook and the unit test in tests/profile-stats-format.test.ts?

Remove the mock server and headless browser spec per review feedback.
Keep the card, hook, locale updates, and profile-stats-format unit tests.
@Souravrajvi0

Souravrajvi0 commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Confirmed the subtitle in studio/frontend/src/features/profile/components/stats/token-activity-card.tsx does not follow the Daily/Weekly/Cumulative switch, and the helper plus locale updates look right. Could you drop the new puppeteer e2e files and their mock server and keep this to the card, the hook and the unit test in tests/profile-stats-format.test.ts?

image image image

Thanks for the review, @danielhanchen I've dropped the puppeteer e2e harness and mock server. The PR now only includes the card, hook, helper, locale updates, and the unit test in [tests/profile-stats-format.test.ts

Confirmed locally that the Token Activity subtitle updates across Daily / Weekly / Cumulative:

Daily: 0 tokens over the last 43 weeks
Weekly: Peak week 0 tokens · last 43 weeks
Cumulative: 0 tokens accumulated over the last 43 weeks

Let me know if anything else should change.

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@Souravrajvi0

Copy link
Copy Markdown
Contributor Author

@danielhanchen Feedback addressed — ready for re-review.

Dropped the puppeteer e2e harness and mock server per your Aug 22 note. This PR is now limited to the token activity card, hook, helper, locale updates, and tests/profile-stats-format.test.ts.

Confirmed locally that the subtitle updates across Daily / Weekly / Cumulative. Rebased branch is current with main. Let me know if anything else should change.

The closed->open watcher in useProfileStats cannot fire. ProfileStatsContent
sits inside the settings DialogContent, which is not force-mounted, so Radix
unmounts the panel on close and the hook is gone before the store flips back to
open. Measured on a real build: with the dialog closed the Token activity card
is absent from the DOM, and reopening Settings costs exactly one
/api/profile/stats request, from the mount effect. Removing the effect keeps
that behaviour and drops a dependency from features/profile on
features/settings.

The focus/visibility refresh is the part that does work, and it stays. Verified
on Chromium, Firefox and WebKit against two installs: a focus event triggers no
refetch at the merge base and exactly one on this branch.

Tests:
- pin the refresh wiring, the unsubscribe contract, that a tab going hidden does
  not refetch, and that repeated mounts leave no listeners behind
- assert daily and cumulative still equal the reduce this PR replaced, over 200
  generated grids, so the number under every existing subtitle cannot drift
- cover the shapes a real grid takes: all-padding columns and a short final week
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-08T11:26:46.096984Z a245e43 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e5689db305

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

// Reopening Settings needs no watcher of its own -- the dialog content is not
// force-mounted, so the panel unmounts on close and the effect above refetches
// when it mounts again.
useEffect(() => subscribeResidentStatusRefresh(load), [load]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Coalesce duplicate foreground refreshes

When a backgrounded profile tab returns and the browser emits both visibilitychange and focus, this subscription calls load twice because subscribeResidentStatusRefresh deliberately registers both events (resident-status-refresh.ts:30-37). Although the second call aborts the first fetch, /api/profile/stats runs its potentially 1.2-second cold aggregation via asyncio.to_thread (profile_stats.py:48-53), so an already-started worker continues and two complete database/message scans can run concurrently whenever the fingerprint changed. Coalesce the paired events or use a deduplicated foreground subscription for this expensive endpoint.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The mechanism is right, but this is duplicated work rather than a correctness problem, and it predates the PR.

Measured it on a live install rather than reasoning about it: firing the pair in one tick sends 2 requests to /api/profile/stats and completes 1 response. So yes, the losing fetch is aborted client side and the server thread keeps going, since Starlette only consumes http.disconnect for StreamingResponse and a thread handed work by asyncio.to_thread cannot be cancelled anyway (https://marcelotryle.com/blog/2024/06/06/understanding-client-disconnection-in-fastapi/, fastapi/fastapi#8805).

What that costs is bounded, though. compute_profile_stats memoises on (fingerprint, days, tz) with a 20s TTL, so the duplicate only redoes the fold in the window where history just changed, and both calls then write the same bytes. The endpoint is a read-only GET: same payload, same final state, nothing lost, nothing crashes.

The double subscribe is also a deliberate property of the shared helper, not something this PR introduces. resident-status-refresh.ts says it outright: focus alone misses a backgrounded tab, visibility alone a window that never hid, so a redundant pair of reads is cheaper than a missed switch. hub-page.tsx and use-chat-model-runtime.ts have both taken that pair since the helper was written. Coalescing inside the profile hook would make this one caller behave differently from the other two for a saving capped by a 20s memo, and coalescing in the helper is a change to Hub and chat behaviour that belongs in its own PR.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 8, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: e5689db305

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

27 comment lines to 5. Cuts narration that restated the code: what the helper
replaced, what the effect below depends on, and a paragraph restating the body
of the listener-leak test.

Kept the four facts the code does not state: the dialog is not force-mounted,
weekly is a max rather than a sum, null grid cells are normal padding, and
dropping the source assertion silently restores the stale-stats bug.
@unslothai unslothai deleted a comment from shimmyshimmer Sep 8, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Before/after for this change, shot from two isolated Studio installs: BEFORE is the merge base a2a4143c, AFTER is the current head a245e43a. Both sides were seeded with the same 825K tokens across 26 weeks, one of them a deliberately dominant 300K week, so the peak is distinguishable from the total.

Weekly is the mode worth looking at. It is the only one where both the wording and the number move:

Token activity card, Weekly mode, before and after

The 300K in the new subtitle is the seeded peak week, and it matches the one tall bar in the same frame.

Cumulative changes wording only, same number:

Token activity card, Cumulative mode, before and after

Daily is deliberately not pictured. Its string is byte identical on both sides and activitySummaryForMode returns exactly what the old visibleTotal did, so that pair would prove nothing.

Subtitle strings read straight off the running card:

mode before after
Daily 825K tokens over the last 43 weeks 825K tokens over the last 43 weeks
Weekly 825K tokens over the last 43 weeks Peak week 300K tokens - last 43 weeks
Cumulative 825K tokens over the last 43 weeks 825K tokens accumulated over the last 43 weeks

Both halves of each image have the same mode pill selected and the same chart, and both installs reported identical data (api_total_tokens 825000, 78 active days), so the subtitle is the only thing that moved.

The refresh half of the PR is not something a screenshot can show, so I measured it instead, on all three engines against both installs. Returning focus to the tab triggers no refetch at the merge base and exactly one on this branch:

engine before after
Chromium (Chrome, Edge) 0 refetch, 1 distinct subtitle 1 refetch, 3 distinct
Firefox 0 refetch, 1 distinct subtitle 1 refetch, 3 distinct
WebKit (Safari) 0 refetch, 1 distinct subtitle 1 refetch, 3 distinct

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 8, 2026
@danielhanchen
danielhanchen merged commit 8a028ba into unslothai:main Sep 8, 2026
24 of 36 checks passed
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.

[Bug] Stats dont seem to be refreshing correctly

2 participants