Repository navigation
Studio: profile usage stats - #7593
Conversation
Adds a "Your stats" section to the Profile settings tab, built entirely from local history in studio.db. No telemetry, nothing uploaded. Backend - storage/profile_stats_db.py folds every metric in one streaming pass over chat_messages, memoised against a (count, max created_at) fingerprint so reopening the tab is free until history changes. - routes/profile_stats.py serves GET /api/profile/stats from a worker thread, so a cold pass cannot stall token streaming. Frontend - Headline tiles, a token activity grid with daily/weekly/cumulative modes, activity insights, most used models, hour and weekday rhythms, and training run totals. - The stats panel is lazy loaded so recharts stays out of the main bundle. - Personalization panel now puts a larger avatar beside the two name fields, with picture options moved into an edit popover. - "Sloth in greeting" moves to Chat defaults, next to the other chat toggles. Tests: 9 backend tests including a regression test that the endpoint does not block the event loop, plus formatting unit tests.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f9b4ca4ff0
ℹ️ 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".
| start_ms = _as_float(timing.get("streamStartTime")) | ||
| first_token = _as_float(timing.get("firstTokenTime")) | ||
| if start_ms and first_token and first_token > start_ms: | ||
| fold.first_token_ms.append(first_token - start_ms) |
There was a problem hiding this comment.
Read first-token timing as an elapsed duration
For real chat records, firstTokenTime is already an elapsed millisecond duration (Date.now() - streamStartTime in studio/frontend/src/features/chat/api/chat-adapter.ts:4248-4250), while streamStartTime is an epoch timestamp. Consequently, first_token > start_ms is false for every normal response, no samples are collected, and “Average time to first token” always displays —; append the duration directly rather than subtracting the start timestamp.
Useful? React with 👍 / 👎.
| """ | ||
| ).fetchone() | ||
|
|
||
| tokens = conn.execute("SELECT COALESCE(SUM(num_tokens), 0) FROM training_metrics").fetchone()[0] |
There was a problem hiding this comment.
Compute training tokens from each run's final counter
When a run has multiple metric rows, num_tokens is the cumulative state.num_input_tokens_seen counter recorded at each logging step, not a per-step delta; the existing get_run_metrics implementation likewise treats the last non-null value as final_num_tokens (studio/backend/storage/studio_db.py:1286-1289). Summing every sample therefore produces a triangular overcount in the Training “Tokens trained” tile; aggregate the final or maximum counter per run and then sum those run totals.
Useful? React with 👍 / 👎.
| SELECT m.thread_id, m.role, m.metadata_json, m.attachments_json, m.created_at, | ||
| t.title, t.model_id, t.model_type | ||
| FROM chat_messages m | ||
| LEFT JOIN chat_threads t ON t.id = m.thread_id | ||
| ORDER BY m.thread_id, m.created_at |
There was a problem hiding this comment.
Exclude copied fork ancestry from lifetime usage
When a conversation is forked, fork_chat_thread clones every ancestor message into the new thread, preserving its metadata, attachments, and original timestamp (studio/backend/storage/studio_db.py:2530-2554). Folding all chat_messages unconditionally counts both the originals and those copies, so forking at the end of a conversation immediately duplicates its messages, tokens, attachments, activity, and chat time despite no additional usage; inherited fork rows need to be excluded from the lifetime aggregates.
Useful? React with 👍 / 👎.
| thread_seconds += gap | ||
| previous_created = created_at | ||
|
|
||
| stamp = datetime.fromtimestamp(created_at / 1000) if created_at > 0 else None |
There was a problem hiding this comment.
Aggregate activity in the browser's timezone
In remote or API-only deployments where the browser and backend use different timezones, converting epoch timestamps with the backend's local timezone assigns messages to the wrong hour, weekday, and sometimes adjacent calendar day for the user. The frontend then parses these timezone-free day keys as browser-local dates, so the activity grid, streaks, peak day, and “When you work” charts can all shift; the endpoint needs the user's timezone or should return timestamped data that the client aggregates locally.
Useful? React with 👍 / 👎.
| model_id = usage.get("modelId") | ||
| if not isinstance(model_id, str) or not model_id.strip(): | ||
| model_id = row["model_id"] if isinstance(row["model_id"], str) else "" | ||
| if model_id.strip(): | ||
| fold.note_model(model_id.strip(), message_tokens) |
There was a problem hiding this comment.
Avoid assigning unscoped turns to the thread's initial model
When a user switches models within an existing conversation and a response has timing metadata but no contextUsage.modelId—the fallback case this code explicitly supports—the thread-level model_id still describes the model recorded when the thread was created, not necessarily the model that generated that response. Those turns are therefore credited to the wrong entry in “Most used models”; unscoped responses should be omitted or persisted with their run-time checkpoint rather than inferred from the thread.
Useful? React with 👍 / 👎.
| """ | ||
| SELECT COUNT(*) AS runs, | ||
| SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS completed, | ||
| SUM(COALESCE(final_step, 0)) AS steps, |
There was a problem hiding this comment.
Count only incremental steps for resumed training runs
When a stopped or errored run is resumed, history retains the original attempt's final_step while the new run's counter continues from that checkpoint; for example, the resume tests preserve an old run at step 10 and a continuation at step 15. Summing both absolute counters reports 25 training steps even though the training reached step 15, so resumed attempts need to contribute only the steps advanced beyond their source checkpoint.
Useful? React with 👍 / 👎.
Six accuracy fixes, each with a test that fails without it. - firstTokenTime is already an elapsed duration, not a timestamp. Subtracting streamStartTime made the comparison false for every real message, so "Average time to first token" was always empty. - Forking clones the whole ancestry into the new thread with the original timestamps. Those copies were counted again, doubling tokens, messages, attachments and activity for the source conversation. Rows older than the fork are now skipped. - training_metrics.num_tokens is state.num_input_tokens_seen, a running total logged at each step, so summing the samples multiplied the real figure. Take each run's final counter, matching get_run_metrics. - A resumed run continues its source's step and token counters from the checkpoint, so adding both reported the same progress twice. Only runs no later run resumed from are counted. - Days, hours and weekdays were bucketed in the server's timezone while the client parses the keys as browser-local. The endpoint now takes the caller's getTimezoneOffset(). - A turn with no contextUsage.modelId fell back to the thread's model_id, which tracks the current selection and so misattributed older turns after a mid-conversation switch. Those turns are left uncredited instead.
|
All six review points were real. Fixed in firstTokenTime. Confirmed against Fork ancestry. Training tokens. Confirmed Resumed runs. The premise is right but the suggested fix is not reachable from the schema: Timezone. Endpoint now takes Model attribution. Confirmed Backend suite is 13 tests, |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6ff20ecdeb
ℹ️ 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".
| # resume_blocked marks a run that some later run resumed from; counting | ||
| # only the unresumed tails avoids adding the same progress twice. | ||
| steps = conn.execute( | ||
| "SELECT COALESCE(SUM(final_step), 0) FROM training_runs WHERE resume_blocked = 0" |
There was a problem hiding this comment.
Include cancelled runs in lifetime training totals
When a user cancels training without saving, mark_run_cancel_requested() sets resume_blocked = 1 even though the run was not resumed. This filter therefore drops all of that run's completed steps, and the identical filter in the token query drops its trained tokens, while the run count and duration still include it. Distinguish runs superseded by a continuation from runs merely made non-resumable so cancelled work remains in the lifetime totals.
Useful? React with 👍 / 👎.
| utc = datetime.fromtimestamp(created_at_ms / 1000, tz = timezone.utc) | ||
| return (utc - timedelta(minutes = tz_offset_minutes)).replace(tzinfo = None) |
There was a problem hiding this comment.
Account for historical daylight-saving offsets
In timezones with daylight saving, the frontend sends only today's new Date().getTimezoneOffset(), and this line applies that fixed offset to every historical message. For example, opening the panel during UTC-4 applies UTC-4 to winter records that should use UTC-5, shifting the hourly distribution and moving messages near midnight onto the wrong day, which can alter the heatmap and streaks. Pass an IANA timezone and convert each timestamp with its date-specific offset rather than reusing the current offset.
Useful? React with 👍 / 👎.
| if row["forked_from_thread_id"] and created_at < _as_int(row["thread_created_at"]): | ||
| continue | ||
|
|
||
| fold.threads.add(thread_id) |
There was a problem hiding this comment.
Count forked conversations before skipping cloned messages
When a user creates a fork but has not sent a new turn in it, every copied message is skipped here before fold.threads.add(thread_id) runs. The fork is nevertheless a persisted, visible chat_threads row, so the “Total chats” value remains unchanged until the first new message is added to the fork. Count conversation rows independently from the cloned-message suppression so creating a visible fork is reflected immediately without double-counting its tokens or messages.
Useful? React with 👍 / 👎.
| <span | ||
| className="min-w-0 truncate text-sm text-foreground" | ||
| title={run.name} | ||
| > | ||
| {run.modelLabel} |
There was a problem hiding this comment.
Display renamed training-run titles
For a run that the user renamed in training history, the backend already returns that preferred title as run.name, but this row renders run.modelLabel instead. As a result, every renamed run loses its user-selected identity in the new recent-runs list and multiple runs of the same model become indistinguishable; run.name is only placed in a hover title. Render the returned name as the primary text and keep the model label as secondary information if needed.
Useful? React with 👍 / 👎.
| raw_model_id = usage.get("modelId") | ||
| model_id = raw_model_id.strip() if isinstance(raw_model_id, str) else "" | ||
| if model_id: | ||
| fold.note_model(model_id, message_tokens) |
There was a problem hiding this comment.
Attribute tokens to the model that produced the response
When an external provider returns a concrete chunk.model different from the requested checkpoint—such as a routed or auto selection—the persisted metadata contains the actual producer in responseDetails.responseModelId, while contextUsage.modelId remains the requested checkpoint. Reading only the latter here credits every routed response to the alias or requested model, so the “Most used models” ranking can report a model that never produced those tokens. Prefer the recorded response model when present and fall back to the requested model for older messages.
Useful? React with 👍 / 👎.
Follow-up to the previous pass, each with a test that fails without it. - Cancelling a run also sets resume_blocked, so filtering on that flag alone dropped the steps and tokens of cancelled work while still counting the run and its duration. Only a run a later run resumed from is excluded now: the resume claim leaves output_dir intact, cancelling clears it, which tells the two apart. - A fixed getTimezoneOffset() was applied to every historical message, so winter records read an hour out when the panel is opened on summer time, moving messages near midnight onto the wrong day. The endpoint now takes an IANA timezone and converts each timestamp with its own offset, keeping the fixed offset as the fallback. - A fork with no new turn was skipped before its thread was registered, so it did not appear in the chat total until its first message. The thread is now counted before the cloned rows are suppressed. - Routed and aliased responses record the model that actually answered in responseDetails.responseModelId, while contextUsage.modelId stays the requested checkpoint. Most used models now prefers the former. - Renamed runs showed the model label instead of the name the user chose. The name leads and the model moves beside the dataset.
|
All five follow-up points were correct too. Fixed in Cancelled runs. Right, and this one was my regression. This also caught a bad fixture in my earlier resume test, which set the flag without an Daylight saving. Correct, a single offset only describes half the year. The endpoint now takes an IANA Fork chat count. Correct, the skip ran before Routed responses. Confirmed Renamed runs. Correct. One adjustment to the suggestion: reading Backend suite is 19 tests, |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9ae3090b98
ℹ️ 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".
| value={draftName} | ||
| maxLength={PROFILE_TEXT_MAX_LENGTH} | ||
| onChange={(e) => setDraftName(e.target.value)} | ||
| onBlur={saveName} |
There was a problem hiding this comment.
Persist profile text before unmounting the tab
When a user edits the display name or nickname and dismisses Settings with Escape (or another programmatic close) while the input remains focused, the Profile tab is unmounted without dispatching blur, so saveName/saveNickname never runs and the edit is silently lost. Since the former explicit Save buttons were removed, commit pending drafts when the dialog/tab closes rather than relying exclusively on onBlur and Enter.
Useful? React with 👍 / 👎.
| if row["forked_from_thread_id"] and created_at < _as_int(row["thread_created_at"]): | ||
| continue |
There was a problem hiding this comment.
Retain copied usage when the source thread is deleted
When a user forks a conversation and later deletes the source thread, the fork remains with its cloned ancestry, but this condition still skips every pre-fork row because forked_from_thread_id is retained and is not a foreign key. The only remaining copies of those messages are therefore omitted from tokens, message counts, activity, and session totals; deduplication needs to account for whether another counted copy of the ancestry still exists.
Useful? React with 👍 / 👎.
| ``output_dir`` alone. Cancelling clears ``output_dir`` while setting the | ||
| same flag, so the flag alone cannot tell the two apart. | ||
| """ | ||
| return f"{prefix}resume_blocked = 1 AND {prefix}output_dir IS NOT NULL" |
There was a problem hiding this comment.
Recount a resume source after deleting its continuation
When a resumed continuation is deleted through the training-history API, delete_run removes only that row and does not clear the predecessor's resume_blocked flag or output_dir. The surviving source run therefore continues to satisfy this predicate and contributes zero steps and tokens even though its row and metrics remain visible in history; supersession must depend on a continuation that still exists or deletion must restore the source.
Useful? React with 👍 / 👎.
| """Wall-clock time in the caller's timezone, not the server's.""" | ||
| if created_at_ms <= 0: | ||
| return None | ||
| return datetime.fromtimestamp(created_at_ms / 1000, tz = zone).replace(tzinfo = None) |
There was a problem hiding this comment.
Skip timestamps outside datetime's supported range
If any stored chat message has an out-of-range millisecond timestamp, datetime.fromtimestamp raises ValueError, OverflowError, or OSError and the route returns 500 for the entire stats panel. ChatMessage.createdAt is only typed as an integer and SQLite accepts values far beyond Python's datetime range, so one malformed API/imported history row can permanently break this feature instead of being ignored like other malformed metadata.
Useful? React with 👍 / 👎.
| Math.abs(scaled) >= 100 | ||
| ? Math.round(scaled).toString() | ||
| : scaled.toFixed(1); | ||
| return `${text.replace(TRAILING_ZERO_DECIMAL, "")}${suffix}`; |
There was a problem hiding this comment.
Promote rounded compact values to the next unit
For values just below a unit boundary, the formatter chooses the lower unit before rounding, so 999_999 is displayed as 1000K and analogous values become 1000M or 1000B. Token totals commonly cross these boundaries, and the resulting headline and model values are not actually compact; promote a rounded value of 1000 to the next suffix.
Useful? React with 👍 / 👎.
| privacyNote: | ||
| "Stats are computed locally from your chat and training history and never leave this device.", |
There was a problem hiding this comment.
Avoid claiming remote stats never leave the device
When Studio is accessed from a remote browser, which this endpoint explicitly supports, the backend computes these aggregates on the server and sends them over the network to the browser. The unconditional statement that the stats “never leave this device” is therefore false for a supported deployment and can mislead users about sensitive usage data; the copy should distinguish local desktop use from remote Studio access.
Useful? React with 👍 / 👎.
|
|
||
| last = ordered[-1] | ||
| current_streak = 0 | ||
| if today - last <= timedelta(days = 1): |
There was a problem hiding this comment.
Exclude future dates from the current streak
If history contains an in-range future timestamp—for example after a client clock was ahead and was later corrected—today - last is negative and still satisfies this <= 1 day check. The UI then reports a future sequence as the current streak even though none of those days is today or yesterday; require the last active day to be no later than today as well.
Useful? React with 👍 / 👎.
- Deleting a forked conversation's source left the fork holding the only copies of those messages, but the skip still dropped them because forked_from_thread_id is not a foreign key. The suppression now joins the source row, so copies are only ignored while the originals survive. - delete_run never clears the predecessor's resume_blocked, so removing a continuation stranded its source at zero steps and tokens while the run stayed visible. Supersession now requires a continuation that still exists. - created_at is a client-supplied integer stored unchecked, so one out-of-range row made datetime raise and returned 500 for the whole panel. Those rows are now skipped for day and hour buckets. - A future-dated row satisfied the current-streak window, reporting days that have not happened. The last active day must now be today or yesterday. - Compact numbers rounded 999,999 to "1000K". Rounding into the next unit now steps up the suffix. - Escape or a programmatic close unmounts the Profile tab without a blur, dropping an in-progress name edit. Drafts are committed on unmount; both saves no-op when unchanged. - Stats copy no longer claims the numbers never leave the device, which is untrue when Studio is reached from another machine. It states what actually holds: nothing is collected or sent to Unsloth.
|
All seven were real. Fixed in Deleted fork source. Right, Deleted continuation. Also right, and a hole in my previous fix. Worth noting for anyone reading the diff: the EXISTS subquery selects from the same table, so the outer row has to be aliased or a bare column name binds to the subquery instead. Both call sites now qualify it. Out-of-range timestamps. Confirmed Future dates. Correct, Compact rounding. Reproduced exactly: 999,999 rendered as Pending profile text. Fixed by committing the drafts on unmount rather than relying on blur alone. Both saves already no-op when the value is unchanged, so the extra commit is harmless if blur did fire. I could not empirically confirm the focus and unmount ordering here, so this is belt and braces rather than a reproduction. Privacy copy. Fair, and worth correcting given what the claim is about. Remote access is supported, so "never leave this device" was not true in that deployment. The copy now states what actually holds everywhere: the numbers come from your own history, nothing is collected, and nothing is sent to Unsloth or any third party. Backend suite is 23 tests, frontend 27, |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1338f09b97
ℹ️ 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".
| if row["fork_source_id"] and created_at < _as_int(row["thread_created_at"]): | ||
| continue |
There was a problem hiding this comment.
Deduplicate ancestry after deleting a multiply-forked source
When two or more sibling forks exist and their source thread is later deleted, the new source-existence gate makes fork_source_id null for every fork, so every surviving copy of the cloned ancestry passes this condition. Messages, tokens, attachments, activity, and chat time are then multiplied by the number of sibling forks; deduplication should retain one canonical surviving copy rather than enabling all copies when the original disappears.
Useful? React with 👍 / 👎.
| ): number[] { | ||
| if (mode === "daily") return daily.map((day) => day.tokens); | ||
|
|
There was a problem hiding this comment.
Seed cumulative activity with the pre-window total
For profiles with history older than 366 days, the backend caps daily at MAX_DAILY_DAYS, but cumulative mode starts its running total at zero. Its final bar therefore reports only the tokens from the last year rather than the lifetime cumulative total described here, and it can be substantially lower than the adjacent “Lifetime tokens” value; return a pre-window baseline or describe this mode as cumulative within the displayed window.
Useful? React with 👍 / 👎.
| # A fork is its own visible conversation, so it counts towards the chat | ||
| # total from the moment it exists, before any new turn is added. | ||
| fold.threads.add(thread_id) |
There was a problem hiding this comment.
Group comparison panes into one chat
When a user creates a comparison conversation, Studio persists one chat_threads row per pane with a shared pair_id, while the sidebar groups those rows into a single visible conversation in use-chat-sidebar-items.ts:58-75. Adding each raw thread_id here therefore reports one comparison as multiple chats and lowers “Average tokens per chat”; use the pair ID as the conversation key when it is present.
Useful? React with 👍 / 👎.
- Deleting a thread that had been forked more than once left every sibling holding a copy of the shared ancestry, and the source-existence gate then let all of them count it, multiplying the usage by the number of forks. One fork per dead source is now elected to keep its copies, the one carrying the most, so nothing is lost or counted twice. - Compare mode persists one thread per pane under a shared pair_id and the sidebar renders them as a single conversation. The chat total now keys on the pair, so one comparison is one chat and average tokens per chat is not halved. - Corrected the note on cumulative mode: it is the running total across the displayed window, not lifetime. Seeding it with everything older than the window would flatten every bar against a baseline the grid has no room to show.
|
Two fixed in Sibling forks. Correct, and it was a hole in the previous fix rather than a new one. With the source gone, Comparison panes. Confirmed against Cumulative baseline. The observation is right: the series is capped at The grid is a bar chart scaled to the tallest column. On a profile with several years of history, seeding the running total with everything older would put every bar within a few percent of the peak, so the whole mode would render as a solid block and show nothing. The card description already scopes the figure with "{total} tokens over the last {weeks} weeks", so the visible copy was not making the lifetime claim; only my comment was. Cumulative growth across the displayed window is the useful reading, and "Lifetime tokens" remains the lifetime figure in the tiles above. Happy to revisit if you would rather the mode were renamed. 25 backend tests, 27 frontend, |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f9970b8744
ℹ️ 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".
| if ( | ||
| row["forked_from_thread_id"] | ||
| and created_at < _as_int(row["thread_created_at"]) | ||
| and (row["fork_source_id"] or thread_id not in keepers) | ||
| ): |
There was a problem hiding this comment.
Preserve fork copies when their source message is deleted
When a user forks a conversation and later deletes a pre-fork message from the original thread, the explicit delete flow prunes only the original row while the cloned row remains visible in the fork. This condition checks only whether the source thread still exists, so it continues skipping every cloned ancestor and the profile totals lose that message's tokens, attachments, and activity. Suppress a clone only while its corresponding original message still survives, rather than while any source-thread row exists.
Useful? React with 👍 / 👎.
| ordered = sorted(days) | ||
| longest = 1 | ||
| running = 1 | ||
| for previous, current in zip(ordered, ordered[1:]): | ||
| running = running + 1 if current - previous == timedelta(days = 1) else 1 | ||
| longest = max(longest, running) |
There was a problem hiding this comment.
Exclude future activity from historical streaks
When imported history or a skewed client clock produces several consecutive future-dated messages, this calculation includes those dates in longest and reports a future lastActiveDay; only the current-streak calculation below rejects the future tail. Filter activity to dates no later than today before calculating all streak fields so malformed future history cannot inflate the headline longest-streak statistic.
Useful? React with 👍 / 👎.
| const title = summary.firstDay | ||
| ? t("settings.profile.stats.weekTooltip", { | ||
| date: dateFormatter.format(parseDayKey(summary.firstDay)), | ||
| tokens: formatFullNumber(summary.value), |
There was a problem hiding this comment.
Show weekly tokens in cumulative tooltips
In cumulative mode, summary.value is the running total at the end of the column, but the tooltip labels it as tokens for the “Week of” that date. Selecting Cumulative therefore shows an increasingly large lifetime-within-window figure where users expect that week's volume, even though columnSummary already computes the actual weekly amount as summary.tokens; use that value for this tooltip while retaining summary.value for bar height.
Useful? React with 👍 / 👎.
| const monthLabels = useMemo( | ||
| () => buildMonthLabels(grid, navigator.language), | ||
| [grid], |
There was a problem hiding this comment.
Format activity dates with the selected UI locale
When the user selects an app language that differs from the browser/OS language, the activity card's month captions remain in navigator.language rather than the language used by useT; the date tooltip formatter below has the same problem. Because these memoized formatters also omit the selected locale from their dependencies, changing the language while the panel is mounted cannot update them. Use the i18n locale store as the formatter locale and dependency.
Useful? React with 👍 / 👎.
- A pre-fork message can be pruned from its original thread while the clone stays in the fork. The suppression only checked that the source thread existed, so that message's tokens and activity vanished. Clones are now matched to the row they came from, and one fork per source is elected to stand in whenever the original is gone, whether the whole thread or just that message went. - Future-dated history was filtered out of the current streak but still padded the longest streak and could be reported as the last active day. It is dropped before any streak field is computed. - Cumulative mode labelled its tooltip "week of" while showing the running total. It now reports that week's tokens; the bar height still uses the running total. - The activity grid and weekday axis formatted dates with the browser language rather than the language chosen in Settings, and the memos could not react to a change. They follow the app locale now. The fork fixtures were also corrected: fork_chat_thread copies created_at verbatim, so a clone carries the original's timestamp, which the previous fixtures did not model.
|
All four were right. Fixed in Deleted original message. Correct, and the fix I had was too coarse. Confirmed there is a per-message prune path in Clones carry no link back, since fork gives them fresh ids, but within one thread the timestamp and role identify the row they were taken from. Suppression is now per message: a clone is skipped only while its original is still there. That subsumes the deleted-thread case, so both now go through one rule, and the elected fork stands in whenever the original is gone for either reason. This surfaced a real problem in my own fixtures, which is worth calling out. Four existing fork tests started failing, and the fixtures were wrong rather than the code: Future streaks. Correct, I had only guarded the current streak. Future dates still padded Cumulative tooltip. Right, and Formatter locale. Also right on both counts. The month captions, the day tooltip and the weekday axis in the rhythm card all used 27 backend tests, 27 frontend, |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 485684db5f
ℹ️ 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".
| # resume_blocked while leaving output_dir intact, whereas cancelling clears | ||
| # output_dir, so a cancelled run keeps contributing the work it did do. | ||
| steps = conn.execute( | ||
| f"SELECT COALESCE(SUM(r.final_step), 0) FROM training_runs r WHERE NOT ({_superseded()})" |
There was a problem hiding this comment.
Preserve source counters until a resume records progress
When a stopped run is resumed but the continuation has not emitted a metric yet—or errors before its first training step—this predicate excludes the source immediately, while the continuation has a null/zero final_step and no training_metrics row. The lifetime Steps and Tokens trained therefore drop by all of the source run's completed work and can remain wrong permanently after an early continuation failure; retain the source counters until the continuation has usable cumulative counters, or fall back to them when it does not.
Useful? React with 👍 / 👎.
| for (const [index, day] of visible.entries()) { | ||
| cells.push({ key: day.date, day, value: values[start + index] ?? 0 }); |
There was a problem hiding this comment.
Reset cumulative values when trimming hidden weeks
When the card is too narrow to show all returned weeks, start trims older days but this lookup retains cumulative values computed over the complete daily array. Consequently the first visible cumulative bar already includes every hidden week, contradicting the displayed-window semantics and often flattening the visible progression against a large off-screen baseline; recompute cumulative values for visible or subtract the value immediately before start.
Useful? React with 👍 / 👎.
| if isinstance(value, (int, float)): | ||
| return ( | ||
| float(value) if value == value and value not in (float("inf"), float("-inf")) else None |
There was a problem hiding this comment.
Reject oversized JSON integers without failing stats
When imported or API-written message metadata contains a valid JSON integer outside the float range, such as a 309-digit token counter, float(value) raises OverflowError before the finite-value checks run. Because metadata fields are not schema-validated on storage, one such row makes /api/profile/stats return 500 and prevents the entire panel from loading; catch the conversion error or reject oversized integers before converting them.
Useful? React with 👍 / 👎.
Removes the "When you work" and "Your week" row from the Profile stats. The backend stopped computing the hour and weekday buckets too, since nothing else read them, and the payload no longer carries them. The timezone and malformed-timestamp tests now assert on day buckets, which is what the activity grid and streaks actually use; the daylight-saving case moved to a timestamp where the hour of drift crosses midnight so the day still proves it. This was the only recharts consumer in the profile panel, so the lazy split's note about keeping charts out of the main bundle no longer applies and has been corrected. Build drops about 22 KB across two fewer chunks.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8644b4c208
ℹ️ 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".
| rank = (_as_int(row["copied"]), row["id"]) | ||
| current = best.get(row["source_id"]) | ||
| if current is None or rank > current: | ||
| best[row["source_id"]] = rank | ||
| return {thread_id for _, thread_id in best.values()} |
There was a problem hiding this comment.
Keep clones per message across divergent forks
When retries or regenerations leave sibling message branches and the user forks different branches before deleting the source thread, this election permits only one entire fork to represent that source. Fork ancestry follows each message's parent_id chain, so the elected fork does not necessarily contain unique replies cloned into the other fork; those replies are subsequently skipped by the thread_id not in keepers check, making lifetime messages and tokens decrease after source deletion. Elect canonical copies per original message rather than per source thread.
Useful? React with 👍 / 👎.
| source_id = row["forked_from_thread_id"] | ||
| if source_id and created_at < _as_int(row["thread_created_at"]): | ||
| original = (source_id, created_at, row["role"]) | ||
| if original in surviving or thread_id not in keepers: | ||
| continue |
There was a problem hiding this comment.
Trace clone ancestry past deleted intermediate forks
When thread A is forked from an existing root, thread B is then forked from A, and A is deleted, B's immediate source_id no longer has surviving rows, so this condition counts B's cloned ancestry. The root's original rows still count independently, immediately duplicating their messages, tokens, attachments, activity, and time; deduplication needs to follow the fork lineage to the surviving root or retain a stable original-message identity.
Useful? React with 👍 / 👎.
| streak = _streaks(set(fold.by_day.keys()), today) | ||
| daily = _daily_series(fold, today, days) | ||
|
|
||
| peak_day = max(fold.by_day.items(), key = lambda item: item[1]["tokens"], default = None) |
There was a problem hiding this comment.
Exclude future buckets from peak-day selection
When imported history or a skewed client clock creates a future-dated message with a high token count, _streaks correctly removes that date but this unfiltered maximum still reports it as the profile's peak day, even though the returned activity series ends at today. Filter candidate buckets to dates no later than today before selecting the peak.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8644b4c208
ℹ️ 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".
| streak = _streaks(set(fold.by_day.keys()), today) | ||
| daily = _daily_series(fold, today, days) | ||
|
|
||
| peak_day = max(fold.by_day.items(), key = lambda item: item[1]["tokens"], default = None) |
There was a problem hiding this comment.
Exclude future buckets from peak-day statistics
When imported history or a skewed client clock creates future-dated messages, _streaks filters those dates and _daily_series cannot display them, but this max still selects them for peakDay; activeDays likewise counts them via len(fold.by_day). The panel can therefore report a future peak date and an active-day total inconsistent with its streak and activity grid. Filter the day buckets to dates on or before today before computing all date-based summaries.
Useful? React with 👍 / 👎.
| const shaded = mode === "daily"; | ||
| const values = useMemo(() => seriesForMode(daily, mode), [daily, mode]); |
There was a problem hiding this comment.
Rebase cumulative values after trimming hidden days
When the card is too narrow to show the full 366-day series, buildColumns trims older days but indexes into cumulative values calculated over the untrimmed array. The first visible bar therefore already includes every hidden day's tokens, making the cumulative chart nearly flat on mobile or other narrow layouts and inconsistent with the header's visibleTotal. Compute cumulative values from the visible slice, or subtract the cumulative value immediately before start.
Useful? React with 👍 / 👎.
| AND EXISTS ( | ||
| SELECT 1 FROM training_runs continuation | ||
| WHERE continuation.output_dir = {prefix}output_dir | ||
| AND continuation.started_at > {prefix}started_at |
There was a problem hiding this comment.
Keep the source superseded when a resumed run is cancelled
When a stopped run is resumed and the continuation is later cancelled, mark_run_cancel_requested clears the continuation's output_dir. This predicate then no longer recognizes the source as superseded, even though the cancelled continuation remains in history with cumulative final_step and num_tokens counters, so _training_stats sums both the source and continuation and double-counts their shared work. Preserve explicit resume lineage or otherwise keep the source excluded while that continuation row exists.
Useful? React with 👍 / 👎.
Four fixes from review: - _as_float raised OverflowError on a JSON integer wider than float, so one oversized counter returned 500 for the whole panel. It degrades to zero now, like every other unreadable field. - Fork dedup elected one winner per source thread, but fork_chat_thread copies a single parent_id branch, so sibling forks of a retry and a regeneration hold different rows. Electing per original message keeps each branch when the source is deleted. - create_run claims a resume source before the continuation logs its first step, so a continuation that failed early took the source's completed steps and tokens with it. Supersession now needs the continuation to have reached the source's step. - Cumulative activity is a running total over the displayed window, but a narrow card trims older weeks without rebasing, opening the first visible bar at the hidden total and flattening the rest.
|
Worked through the latest round. All four hold up against the source, and each fix has a test that fails without it. Oversized JSON integers ( Fork election is per thread, not per message Resume supersession without a logged step Cumulative bars against a hidden baseline Backend suite is 30 passing, frontend 30. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: df7300a3e1
ℹ️ 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".
| // avatarShape lives inside the avatar edit popover, so it has no | ||
| // always-rendered label for search to scroll to. |
There was a problem hiding this comment.
Add the statistics labels to settings search
The new stats section is absent from SETTINGS_SEARCH_INDEX, although the Settings dialog searches only this static index. Consequently, queries such as “Your stats”, “Lifetime tokens”, or “Training time” return no Profile result even though those sections render data-settings-label targets. Add the always-rendered stats labels (at minimum settings.profile.stats.title) to the profile entries.
Useful? React with 👍 / 👎.
| streak = _streaks(set(fold.by_day.keys()), today) | ||
| daily = _daily_series(fold, today, days) | ||
|
|
||
| peak_day = max(fold.by_day.items(), key = lambda item: item[1]["tokens"], default = None) |
There was a problem hiding this comment.
Exclude future buckets from day-based highlights
When imported history or a skewed client clock creates a future-dated message, _streaks correctly filters that date, but this unfiltered max can still report it as the user's peak day and activeDays also includes it. The activity grid ends at today, so the resulting headline can name a future date that does not appear in the chart; filter fold.by_day to dates at or before today for these day-based summaries.
Useful? React with 👍 / 👎.
| usage = metadata.get("contextUsage") | ||
| timing = metadata.get("timing") | ||
| usage = usage if isinstance(usage, dict) else {} | ||
| timing = timing if isinstance(timing, dict) else {} |
There was a problem hiding this comment.
Fall back to persisted server token timings
For historical or local-engine responses without contextUsage, this treats prompt tokens as zero and reconstructs the total from only timing.tokenCount, even when the persisted serverTimings contains prompt_n, predicted_n, and cache_n. The existing response-details UI already uses those fields as its fallback (message-response-details-sheet.tsx:314-324,400-403), so the new lifetime, input, and cached-token statistics undercount messages that the app itself can still display accurately.
Useful? React with 👍 / 👎.
| tokens = conn.execute( | ||
| f""" | ||
| SELECT COALESCE(SUM(run_tokens), 0) FROM ( | ||
| SELECT MAX(m.num_tokens) AS run_tokens |
There was a problem hiding this comment.
Record token counts for embedding training runs
The aggregation assumes every run records state.num_input_tokens_seen, but the embedding path constructs SentenceTransformerTrainingArguments without enabling include_num_input_tokens_seen while its callback reads that field (core/training/worker.py:3837-3867,3912-3914). Unlike the normal trainer, which explicitly enables the counter, embedding runs therefore contribute zero to the new “Tokens trained” total; enable token tracking for that path or derive its token count separately.
Useful? React with 👍 / 👎.
Four more from review: - peakDay and activeDays read every day bucket, so a future-dated message could headline a date the activity grid cannot show. Both now stop at today, like the streaks and the grid already did. - Supersession matched runs by output_dir, but cancelling a resumed continuation nulls that column, which un-superseded the source and double-counted their shared steps and tokens. training_runs now stores resumed_from_run_id, which create_run already accepted and discarded. Rows written before the column stay on the output_dir heuristic. - Token totals read contextUsage only, while the response details sheet already falls back to serverTimings prompt_n, predicted_n and cache_n. Local-engine replies were undercounted against what the app displays. - The stats section was missing from the settings search index, so the headline labels were unreachable from search.
|
Latest round. Four fixed, one already landed, one correct but out of scope here. Future dates in peakDay and activeDays Confirmed. Cancelled continuation un-supersedes its source Confirmed, and it is the third symptom of the same weakness: Rather than patch a third special case, The column is nullable and added by serverTimings fallback Confirmed. Settings search index Confirmed. Added the stats heading and the five highlight labels. The insight and training cards render conditionally, so they stay out, matching the convention already noted in that file for Cumulative rebase Already landed in Embedding runs and The diagnosis is right: Not fixing it here. It is a one-line change to a training hot path that I cannot verify without running an embedding job, and it belongs with the training code rather than in a read-only stats panel. Worth its own PR. Backend 33 passing, frontend 32. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8141a7b128
ℹ️ 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".
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
Adds a Your stats section to the Profile tab in Settings, and tidies up the personalization form above it.
Everything is computed from history already sitting in
studio.db. Nothing new is recorded, nothing is uploaded, and there is no telemetry of any kind.What you get
The grid is sized to the card and never scrolls, so today is always the rightmost column.
Backend
GET /api/profile/stats, backed by two new files:storage/profile_stats_db.pyfolds every metric in a single streaming pass overchat_messages. Token counts live inside each message'smetadata_json, which cannot be summed in SQL portably (JSON1 is not guaranteed on every bundled SQLite), so the pass parses them in Python. The result is memoised against a(count, max created_at)fingerprint, so reopening the tab costs nothing until history actually changes.routes/profile_stats.pyruns that pass in a worker thread. A cold pass is roughly 90 ms at 10k messages and 1.2 s at 260k. On the event loop that would stall token streaming for anyone who opens Settings mid-generation, so it goes off-thread. There is a test covering exactly this.Cost when you are not looking at it
Nothing measurable. Only the active settings tab renders, settings search runs off a static key index rather than mounting tabs, and there is no polling. The stats panel is also lazy loaded, which keeps recharts out of the main bundle: cold load grows by about 2 KB gzipped.
Personalization panel
Tests
tsc, i18n parity, the full frontend suite and a production build all pass.