Skip to content

Studio: profile usage stats - #7593

Merged
danielhanchen merged 11 commits into
mainfrom
studio-profile-stats
Jul 29, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
studio-profile-stats

Conversation

@shimmyshimmer

Copy link
Copy Markdown
Member

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

  • Headline tiles: lifetime tokens, peak day, longest chat, current and longest streak.
  • Token activity grid with three modes. Daily shades each square by that day's volume; Weekly and Cumulative draw one bar per column so the shape of a busy stretch is actually visible.
  • Activity insights: chats, messages, tokens in and out, cached tokens, time in chat, tool calls, attachments, average and peak speed, time to first token.
  • Most used models, ranked by tokens exchanged.
  • When you work: hour-of-day and weekday histograms.
  • Training: runs, completed runs, steps, tokens trained, wall time and best loss, when the workspace has any.

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.py folds every metric in a single streaming pass over chat_messages. Token counts live inside each message's metadata_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.py runs 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

  • Larger avatar on the left with both name fields beside it, instead of stacked rows.
  • Picture options (upload, remove, avatar shape, sloth picks) moved into an edit popover behind the pencil, and clicking the picture itself goes straight to the file picker.
  • Name fields save on blur and on Enter.
  • Sloth in greeting moved to Chat defaults, where the rest of the chat toggles live.

Tests

  • 9 backend tests, including the event loop regression test and streak, session gap and empty history cases.
  • Frontend unit tests for the number, duration and activity series formatting.
  • tsc, i18n parity, the full frontend suite and a production build all pass.

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.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

@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: 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".

Comment on lines +265 to +268
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)

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 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]

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 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 👍 / 👎.

Comment on lines +153 to +157
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

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 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

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 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 👍 / 👎.

Comment on lines +248 to +252
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)

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 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,

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 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.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

All six review points were real. Fixed in 6ff20ec, each with a test that fails without its fix.

firstTokenTime. Confirmed against chat-adapter.ts:4250, which assigns Date.now() - streamStartTime, and against message-timing.tsx, which already renders the value straight through formatTimingMs. It is a duration, so first_token > start_ms was false for every real message and the average never collected a single sample. Now appended directly.

Fork ancestry. fork_chat_thread clones the ancestry with the original created_at on each copy, so the source conversation was counted twice. Forked threads now skip rows older than the fork itself. The thread's own created_at is the fork time and message timestamps come from the same client clock, so the two are comparable. New turns added after the fork still count.

Training tokens. Confirmed num_tokens originates from state.num_input_tokens_seen in worker.py:3913, a running total, and that get_run_metrics already treats the last value as final rather than summing. Now takes each run's final counter and sums those.

Resumed runs. The premise is right but the suggested fix is not reachable from the schema: resumed_from_run_id is only a create_run parameter, never a column. What it does do is set resume_blocked = 1 on the source, which is exactly the signal needed. Steps and tokens now count only runs no later run resumed from, so a 10 then 15 resume reports 15. Both attempts still show in the run count.

Timezone. Endpoint now takes tz_offset_minutes from the browser's getTimezoneOffset(), and "today" is derived from the same offset so the newest column and the current streak cannot drift.

Model attribution. Confirmed chat_threads.model_id is mutable via update_chat_thread, so it tracks the current selection rather than the model that produced an older turn. The fallback is gone; turns without a recorded checkpoint are left uncredited.

Backend suite is 13 tests, ruff check clean, and the frontend typechecks and builds.

@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

@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: 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"

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 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 👍 / 👎.

Comment on lines +79 to +80
utc = datetime.fromtimestamp(created_at_ms / 1000, tz = timezone.utc)
return (utc - timedelta(minutes = tz_offset_minutes)).replace(tzinfo = None)

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 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 👍 / 👎.

Comment on lines +209 to +212
if row["forked_from_thread_id"] and created_at < _as_int(row["thread_created_at"]):
continue

fold.threads.add(thread_id)

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 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 👍 / 👎.

Comment on lines +68 to +72
<span
className="min-w-0 truncate text-sm text-foreground"
title={run.name}
>
{run.modelLabel}

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 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 👍 / 👎.

Comment on lines +273 to +276
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)

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 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.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

All five follow-up points were correct too. Fixed in 9ae3090, each with a test I confirmed fails without its fix.

Cancelled runs. Right, and this one was my regression. mark_run_cancel_requested sets resume_blocked = 1 on a still-running run, so my filter dropped work that nothing had resumed. The two cases are separable: the resume claim in create_run sets the flag and leaves output_dir alone, while cancelling clears output_dir. Exclusion is now resume_blocked = 1 AND output_dir IS NOT NULL, so a cancelled run keeps the steps and tokens it earned.

This also caught a bad fixture in my earlier resume test, which set the flag without an output_dir. A genuinely superseded run keeps it, so the test now seeds both runs sharing one output dir.

Daylight saving. Correct, a single offset only describes half the year. The endpoint now takes an IANA tz and converts each timestamp with that date's own offset; tz_offset_minutes stays as the fallback for hosts without tzdata. There is a test asserting a January message reads as 21:00 on the 14th for America/New_York even when the caller sends the summer offset, plus one covering an unresolvable zone name.

Fork chat count. Correct, the skip ran before fold.threads.add, so a fork was invisible in "Total chats" until its first new turn. The thread is registered before the cloned rows are suppressed, so the count moves but the tokens and messages do not.

Routed responses. Confirmed responseModelId is reassigned from chunk.model at chat-adapter.ts:3581 while contextUsage.modelId stays params.checkpoint. responseDetails.responseModelId is now preferred, with contextUsage.modelId as the fallback for older messages.

Renamed runs. Correct. One adjustment to the suggestion: reading run.name alone would have shown the full repo id for un-renamed runs, since the backend was returning COALESCE(display_name, model_name). The fallback now goes through the same short-label helper, so the row shows the chosen name when renamed and the short model label otherwise, with the model label moving next to the dataset so it stays visible.

Backend suite is 19 tests, ruff check clean, frontend typechecks, builds and passes i18n parity.

@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

@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: 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}

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 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 👍 / 👎.

Comment on lines +229 to +230
if row["forked_from_thread_id"] and created_at < _as_int(row["thread_created_at"]):
continue

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 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"

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 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)

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 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 👍 / 👎.

Comment on lines +29 to +32
Math.abs(scaled) >= 100
? Math.round(scaled).toString()
: scaled.toFixed(1);
return `${text.replace(TRAILING_ZERO_DECIMAL, "")}${suffix}`;

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 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 👍 / 👎.

Comment thread studio/frontend/src/i18n/locales/en.ts Outdated
Comment on lines +416 to +417
privacyNote:
"Stats are computed locally from your chat and training history and never leave this device.",

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 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):

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 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.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

All seven were real. Fixed in 1338f09, with a test behind each of the backend ones that I confirmed fails without its fix.

Deleted fork source. Right, forked_from_thread_id is not a foreign key, so it survives the source thread and my skip then discarded the only remaining copies. The suppression now joins the source row, so copies are ignored only while the originals are still there to be counted in their place.

Deleted continuation. Also right, and a hole in my previous fix. delete_run never clears the predecessor's flag, so the source stayed excluded while its row and metrics remained in history. Supersession now additionally requires a continuation that still exists, sharing the output dir with a later start.

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 datetime.fromtimestamp raises ValueError on values SQLite stores happily, and createdAt is a plain client-supplied integer. One bad imported row returned 500 for the entire panel. Those rows are now skipped for day and hour bucketing while their tokens still count.

Future dates. Correct, today - last goes negative and passes a <= 1 day check. The window is now bounded at both ends.

Compact rounding. Reproduced exactly: 999,999 rendered as 1000K and 999,999,999 as 1000M. Rounding into the next unit now promotes the suffix, so those read 1M and 1B. Only the top unit can still show four digits, since there is nothing above T.

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, ruff check clean, typecheck, build and i18n parity all pass.

@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: 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".

Comment on lines +244 to +245
if row["fork_source_id"] and created_at < _as_int(row["thread_created_at"]):
continue

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 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 👍 / 👎.

Comment on lines +107 to +109
): number[] {
if (mode === "daily") return daily.map((day) => day.tokens);

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 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 👍 / 👎.

Comment on lines +235 to +237
# 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)

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 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.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Two fixed in f9970b8, one resolved as a documentation correction rather than a maths change.

Sibling forks. Correct, and it was a hole in the previous fix rather than a new one. With the source gone, fork_source_id is null for every sibling, so each of them re-counted the shared ancestry. One fork per dead source is now elected to keep its copies, chosen by the highest number of copied rows, which is the sibling that branched latest and therefore holds the longest ancestry. Nothing is lost and nothing is counted twice. The election runs once per request over orphaned forks only, so the streaming pass is unaffected.

Comparison panes. Confirmed against use-chat-sidebar-items.ts, which folds every pairId row into a single compare item. The chat total now keys on the pair when present, so one comparison counts as one conversation while both panes still contribute their own messages and tokens.

Cumulative baseline. The observation is right: the series is capped at MAX_DAILY_DAYS, so cumulative is window-scoped, and my comment claiming a "running lifetime total" was wrong. I have corrected the comment rather than seeding a baseline, and here is the reasoning, since you offered both options.

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, ruff check clean, typecheck, build and i18n parity pass.

@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

@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: 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".

Comment on lines +281 to +285
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)
):

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 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 👍 / 👎.

Comment on lines +116 to +121
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)

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 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 👍 / 👎.

Comment on lines +217 to +220
const title = summary.firstDay
? t("settings.profile.stats.weekTooltip", {
date: dateFormatter.format(parseDayKey(summary.firstDay)),
tokens: formatFullNumber(summary.value),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge 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 👍 / 👎.

Comment on lines +249 to +251
const monthLabels = useMemo(
() => buildMonthLabels(grid, navigator.language),
[grid],

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 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.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

All four were right. Fixed in 485684d.

Deleted original message. Correct, and the fix I had was too coarse. Confirmed there is a per-message prune path in reconcile_chat_messages, so a pre-fork message can be removed from the original thread while the clone stays in the fork, and checking only that the source thread existed dropped it entirely.

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: fork_chat_thread copies created_at verbatim, so a clone carries the original's exact timestamp, and my fixtures had been giving clones the user turn's timestamp instead of the assistant reply's. They model the real clone now.

Future streaks. Correct, I had only guarded the current streak. Future dates still padded longest and could be returned as lastActiveDay. They are filtered before any field is computed.

Cumulative tooltip. Right, and columnSummary was already computing the weekly figure. The tooltip reports summary.tokens while the bar height keeps using summary.value, so the label matches what it claims in every mode.

Formatter locale. Also right on both counts. The month captions, the day tooltip and the weekday axis in the rhythm card all used navigator.language, and the memos had no locale dependency so switching language while the panel was open could not update them. All three now use useLocale() and list it as a dependency.

27 backend tests, 27 frontend, ruff check clean, typecheck, build and i18n parity pass.

@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: 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()})"

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 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 👍 / 👎.

Comment on lines +64 to +65
for (const [index, day] of visible.entries()) {
cells.push({ key: day.date, day, value: values[start + index] ?? 0 });

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 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 👍 / 👎.

Comment on lines +54 to +56
if isinstance(value, (int, float)):
return (
float(value) if value == value and value not in (float("inf"), float("-inf")) else None

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 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.

@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: 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".

Comment on lines +212 to +216
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()}

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 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 👍 / 👎.

Comment on lines +296 to +300
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

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 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)

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 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 👍 / 👎.

@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

@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: 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)

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 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 👍 / 👎.

Comment on lines +245 to +246
const shaded = mode === "daily";
const values = useMemo(() => seriesForMode(daily, mode), [daily, mode]);

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 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 👍 / 👎.

Comment on lines +430 to +433
AND EXISTS (
SELECT 1 FROM training_runs continuation
WHERE continuation.output_dir = {prefix}output_dir
AND continuation.started_at > {prefix}started_at

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 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.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

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 (_as_float)
Confirmed. json parses integers of any width and float() raises OverflowError past roughly 1e308, so a 309-digit counter reached the conversion and returned 500 for the whole panel. The guard catches it and the field degrades to zero like any other unreadable value. The row still contributes whatever else it has rather than being dropped.

Fork election is per thread, not per message
Confirmed, and worse than a tie-break problem. fork_chat_thread walks the parent_id chain and copies one branch, so a fork taken at a reply and a fork taken at its regeneration hold different rows. Electing one winner per source meant the loser's unique branch was skipped once the source was deleted, and lifetime tokens went down. Election is now keyed on the original message identity, so each branch keeps exactly one surviving copy. Reinstating the old per-thread election makes the new test report 1 message where it should report 2.

Resume supersession without a logged step
Confirmed. create_run claims the source the moment the resume starts, but final_step is only written by update_run_progress on the first metric flush. A continuation that errored before then had a null final_step and no metrics, so the source's completed work vanished from Steps and Tokens permanently. Supersession now also requires the continuation to have reached the source's step.

Cumulative bars against a hidden baseline
Confirmed. seriesForMode runs over the full returned series while buildColumns trims to the visible columns, so the first visible bar opened at the hidden total. Since the peak is computed from the visible grid, the whole window flattened. The series is now rebased off the last hidden day. Extracted as windowBaseline so it is directly testable.

Backend suite is 30 passing, frontend 30.

@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

@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: 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".

Comment on lines +40 to +41
// avatarShape lives inside the avatar edit popover, so it has no
// always-rendered label for search to scroll to.

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 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)

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 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 👍 / 👎.

Comment on lines +349 to +352
usage = metadata.get("contextUsage")
timing = metadata.get("timing")
usage = usage if isinstance(usage, dict) else {}
timing = timing if isinstance(timing, dict) else {}

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 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

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 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.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Latest round. Four fixed, one already landed, one correct but out of scope here.

Future dates in peakDay and activeDays

Confirmed. _streaks filters ahead-of-today dates and _daily_series ends at today, but peakDay took max over every bucket and activeDays was len(fold.by_day). A skewed clock could headline a date the grid cannot show. Both now read a <= today view of the buckets.

Cancelled continuation un-supersedes its source

Confirmed, and it is the third symptom of the same weakness: output_dir was standing in for lineage. mark_run_cancel_requested nulls it, so the match broke and the source's steps were added back on top of the continuation's cumulative counters.

Rather than patch a third special case, training_runs now stores resumed_from_run_id, which create_run already accepted as a parameter and threw away. The predicate prefers that link and keeps the output_dir match only for rows written before the column existed. This collapses all three reported cases into one rule: cancelled continuation, deleted continuation, and a continuation that failed before its first metric flush.

The column is nullable and added by ALTER TABLE in _ensure_schema. Verified against a database built on the old schema: the column is absent before, present after, existing rows keep their values with NULL lineage, and a second run is a no-op. Full backend suite is unchanged at 18 pre-existing failures (flash-attn and tilelang, unrelated), 1353 passing before and 1356 after.

serverTimings fallback

Confirmed. serverTimings is persisted in message metadata and message-response-details-sheet.tsx already falls back to prompt_n, predicted_n and cache_n. The aggregation read contextUsage only, so local-engine replies were undercounted against what the app itself displays. The same chain is in place now.

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 avatarShape.

Cumulative rebase

Already landed in df7300a, before this comment was written. buildColumns takes the mode and subtracts windowBaseline.

Embedding runs and include_num_input_tokens_seen

The diagnosis is right: worker.py builds SentenceTransformerTrainingArguments without the flag while its own callback reads state.num_input_tokens_seen, and the normal trainer sets it explicitly at trainer.py:3235. So embedding runs log a null token count.

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.

@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

@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: 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".

@oobabooga

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 7637b1cafd

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@danielhanchen
danielhanchen merged commit a7031d6 into main Jul 29, 2026
3 of 55 checks passed
@danielhanchen
danielhanchen deleted the studio-profile-stats branch July 29, 2026 15:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants