feat(usage): real-time stats refresh + fix codex sync panic on non-ASCII model names#3027
Merged
farion1231 merged 1 commit intoMay 29, 2026
Conversation
…CII model names The usage dashboard previously only refreshed on app restart for users who don't route through the cc-switch proxy. Two issues were involved: 1. The session-sync background task panicked when a Codex model name contained non-ASCII characters (e.g. `【官】glm-5.1`), because `normalize_codex_model` sliced `&name[name.len() - 11..]` without verifying char boundaries. Once the task panicked, no session logs were imported until the app was restarted (where startup-time `rollup_and_prune` happened to flush pending data). 2. Even with sync working, the dashboard only polled every 30s and skipped polling when the window was unfocused, so freshly-imported data was invisible until the next poll or window refocus. Fixes ----- * `normalize_codex_model`: guard the 11-byte ISO-date suffix slice with `is_char_boundary` + `is_ascii` checks. ASCII-only suffix means the date-stripping logic is correct, and non-ASCII names (which can never be valid date suffixes anyway) now bypass the slice safely. * New `usage_events` module that emits `usage-log-recorded` to the frontend whenever `proxy_request_logs` actually gains a new row. Sources covered: proxy `log_request`, Claude/Codex/Gemini session sync, and startup `rollup_and_prune`. Notifications use a global `OnceLock<AppHandle>` so call sites that don't already hold an `AppHandle` (e.g. `UsageLogger`) can notify without signature churn. * 200ms debounce in `notify_log_recorded` collapses bursts (a single Codex sync importing 3000+ entries triggers ~2 emits, not 3000) so the frontend's `invalidateQueries` is never spammed. * Frontend `useUsageEventBridge` listens for the event and invalidates `usageKeys.all`. Hook is mounted only on `UsageDashboard`, so the listener is unsubscribed automatically when the user navigates away. Verification ------------ * `cargo check` passes (existing 25 dead-code warnings in `commands/misc.rs` are pre-existing and unrelated). * `tsc --noEmit` passes. * Manually verified end-to-end: a Codex sync run that imported 3145 entries produced 2 debounced emits, both logged as `emit usage-log-recorded 成功`, and the dashboard updated within ~200ms. Behaviour notes --------------- * `INSERT OR IGNORE` paths (Claude/Codex session sync) only notify when the row is actually inserted, so dedup-skipped writes don't trigger empty refreshes. * Gemini's `INSERT … ON CONFLICT … DO UPDATE` path reuses the existing `conn.changes() > 0` check and only notifies when token counts truly changed. * `rollup_and_prune` notifies once per pruning cycle (at most once per app start) so the dashboard reflects the new aggregate state.
Owner
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
farion1231
approved these changes
May 29, 2026
farion1231
left a comment
Owner
There was a problem hiding this comment.
Thank you for your contribution!
royccai
pushed a commit
to royccai/cc-switch-mod
that referenced
this pull request
May 31, 2026
…CII model names (farion1231#3027) The usage dashboard previously only refreshed on app restart for users who don't route through the cc-switch proxy. Two issues were involved: 1. The session-sync background task panicked when a Codex model name contained non-ASCII characters (e.g. `【官】glm-5.1`), because `normalize_codex_model` sliced `&name[name.len() - 11..]` without verifying char boundaries. Once the task panicked, no session logs were imported until the app was restarted (where startup-time `rollup_and_prune` happened to flush pending data). 2. Even with sync working, the dashboard only polled every 30s and skipped polling when the window was unfocused, so freshly-imported data was invisible until the next poll or window refocus. Fixes ----- * `normalize_codex_model`: guard the 11-byte ISO-date suffix slice with `is_char_boundary` + `is_ascii` checks. ASCII-only suffix means the date-stripping logic is correct, and non-ASCII names (which can never be valid date suffixes anyway) now bypass the slice safely. * New `usage_events` module that emits `usage-log-recorded` to the frontend whenever `proxy_request_logs` actually gains a new row. Sources covered: proxy `log_request`, Claude/Codex/Gemini session sync, and startup `rollup_and_prune`. Notifications use a global `OnceLock<AppHandle>` so call sites that don't already hold an `AppHandle` (e.g. `UsageLogger`) can notify without signature churn. * 200ms debounce in `notify_log_recorded` collapses bursts (a single Codex sync importing 3000+ entries triggers ~2 emits, not 3000) so the frontend's `invalidateQueries` is never spammed. * Frontend `useUsageEventBridge` listens for the event and invalidates `usageKeys.all`. Hook is mounted only on `UsageDashboard`, so the listener is unsubscribed automatically when the user navigates away. Verification ------------ * `cargo check` passes (existing 25 dead-code warnings in `commands/misc.rs` are pre-existing and unrelated). * `tsc --noEmit` passes. * Manually verified end-to-end: a Codex sync run that imported 3145 entries produced 2 debounced emits, both logged as `emit usage-log-recorded 成功`, and the dashboard updated within ~200ms. Behaviour notes --------------- * `INSERT OR IGNORE` paths (Claude/Codex session sync) only notify when the row is actually inserted, so dedup-skipped writes don't trigger empty refreshes. * Gemini's `INSERT … ON CONFLICT … DO UPDATE` path reuses the existing `conn.changes() > 0` check and only notifies when token counts truly changed. * `rollup_and_prune` notifies once per pruning cycle (at most once per app start) so the dashboard reflects the new aggregate state. Co-authored-by: in30mn1a <[email protected]>
delta-lo
pushed a commit
to delta-lo/cc-switch-mod
that referenced
this pull request
May 31, 2026
…CII model names (farion1231#3027) The usage dashboard previously only refreshed on app restart for users who don't route through the cc-switch proxy. Two issues were involved: 1. The session-sync background task panicked when a Codex model name contained non-ASCII characters (e.g. `【官】glm-5.1`), because `normalize_codex_model` sliced `&name[name.len() - 11..]` without verifying char boundaries. Once the task panicked, no session logs were imported until the app was restarted (where startup-time `rollup_and_prune` happened to flush pending data). 2. Even with sync working, the dashboard only polled every 30s and skipped polling when the window was unfocused, so freshly-imported data was invisible until the next poll or window refocus. Fixes ----- * `normalize_codex_model`: guard the 11-byte ISO-date suffix slice with `is_char_boundary` + `is_ascii` checks. ASCII-only suffix means the date-stripping logic is correct, and non-ASCII names (which can never be valid date suffixes anyway) now bypass the slice safely. * New `usage_events` module that emits `usage-log-recorded` to the frontend whenever `proxy_request_logs` actually gains a new row. Sources covered: proxy `log_request`, Claude/Codex/Gemini session sync, and startup `rollup_and_prune`. Notifications use a global `OnceLock<AppHandle>` so call sites that don't already hold an `AppHandle` (e.g. `UsageLogger`) can notify without signature churn. * 200ms debounce in `notify_log_recorded` collapses bursts (a single Codex sync importing 3000+ entries triggers ~2 emits, not 3000) so the frontend's `invalidateQueries` is never spammed. * Frontend `useUsageEventBridge` listens for the event and invalidates `usageKeys.all`. Hook is mounted only on `UsageDashboard`, so the listener is unsubscribed automatically when the user navigates away. Verification ------------ * `cargo check` passes (existing 25 dead-code warnings in `commands/misc.rs` are pre-existing and unrelated). * `tsc --noEmit` passes. * Manually verified end-to-end: a Codex sync run that imported 3145 entries produced 2 debounced emits, both logged as `emit usage-log-recorded 成功`, and the dashboard updated within ~200ms. Behaviour notes --------------- * `INSERT OR IGNORE` paths (Claude/Codex session sync) only notify when the row is actually inserted, so dedup-skipped writes don't trigger empty refreshes. * Gemini's `INSERT … ON CONFLICT … DO UPDATE` path reuses the existing `conn.changes() > 0` check and only notifies when token counts truly changed. * `rollup_and_prune` notifies once per pruning cycle (at most once per app start) so the dashboard reflects the new aggregate state. Co-authored-by: in30mn1a <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR addresses a long-standing issue where the usage statistics dashboard only refreshed after restarting cc-switch. Diagnosing this surfaced two root causes — both fixed here.
Problem 1: Codex session sync panics on non-ASCII model names
normalize_codex_modelinservices/session_usage_codex.rsslices the last 11 bytes of the model name to detect an ISO date suffix:For a model name containing multi-byte UTF-8 characters (real-world example from my config:
【官】glm-5.1),name.len() - 11lands inside a multi-byte char, panicking the tokio worker:Once the background sync task panics, no Codex session logs are imported until the app is restarted (where
Database::init→rollup_and_prunehappens to flush pending data). This is the actual reason stats appear to "only refresh on restart" for users who don't route through the cc-switch proxy.Fix: Guard the slice with
is_char_boundary+is_ascii(a valid date suffix is always ASCII, so non-ASCII names can safely bypass the slicing).Problem 2: Dashboard doesn't reflect new logs in real time
Even after fixing Problem 1, the
UsageDashboardonly polls every 30s and disablesrefetchIntervalInBackground, so freshly-imported data is invisible until the next poll or window refocus.Fix: Push-based refresh.
usage_eventsmodule emits ausage-log-recordedevent wheneverproxy_request_logsactually gains a new row. Coverage:log_request(streaming + non-streaming, success + error)INSERT OR IGNOREskips don't trigger empty refreshes)rollup_and_prunenotify_log_recordedcollapses bursts. A Codex sync importing 3000+ entries produces ~2 emits, not 3000.OnceLock<AppHandle>lets call sites that don't already hold anAppHandle(e.g.UsageLogger) notify without signature churn.useUsageEventBridgelistens for the event and invalidatesusageKeys.all. Mounted only onUsageDashboardso the listener is unsubscribed automatically when navigating away.Verification
cargo checkpasses (existing 25 dead-code warnings incommands/misc.rsare pre-existing and unrelated)tsc --noEmitpassesemit usage-log-recorded 成功in logs), and the dashboard updated within ~200ms.Files
src-tauri/src/services/session_usage_codex.rs(the panic)src-tauri/src/usage_events.rs(event module)src/hooks/useUsageEventBridge.ts(frontend listener)src-tauri/src/lib.rs(init insetup)src-tauri/src/proxy/usage/logger.rs(notify onlog_request)src-tauri/src/services/session_usage{,_codex,_gemini}.rs(notify on insert)src-tauri/src/database/dao/usage_rollup.rs(notify on prune)src/components/usage/UsageDashboard.tsx(mount the bridge hook)Behaviour notes
INSERT … ON CONFLICT … DO UPDATEpath reuses the existingconn.changes() > 0check.cc-switch.log.