Skip to content

feat: collect model performance metrics - #4635

Merged
Calcium-Ion merged 1 commit into
mainfrom
cursor/model-performance-metrics
May 6, 2026
Merged

Calcium-Ion merged 1 commit into
mainfrom
cursor/model-performance-metrics

Conversation

@Calcium-Ion

@Calcium-Ion Calcium-Ion commented May 6, 2026 •

Copy link
Copy Markdown
Member

⚠️ 提交说明 / PR Notice

Important

  • 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。

📝 变更描述 / Description

新增模型性能指标采集链路,用内存热聚合并定期持久化到数据库,提供模型广场可读取的真实 TTFT、延迟和成功率数据。前端性能页改为调用真实接口,并在维护设置中增加独立的性能指标配置项。

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix) - 请关联对应 Issue,避免将设计取舍、理解偏差或预期不一致直接归类为 bug
  • ✨ 新功能 (New feature) - 重大特性建议先通过 Issue 沟通
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

  • Closes # (如有)

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

  • go test ./model ./controller ./service ./pkg/perf_metrics ./setting/perf_metrics_setting ./router
  • cd web/default && bun run typecheck
  • cd web/default && bun run i18n:sync

Summary by CodeRabbit

  • New Features
    • Added a model performance metrics system with queryable API, dashboard charts, and configurable aggregation & retention settings.
  • User Settings
    • New "Model performance metrics" controls in System Settings: enable, flush interval, aggregation bucket, retention days (defaults added).
  • UI Changes
    • Updated performance chart date formatting; uptime sparkline removed from model overview.
  • Localization
    • Added translations for new performance/metrics UI text in multiple locales.

@coderabbitai

coderabbitai Bot commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 31b9c55f-42da-49d7-ac15-c04e63b7e2d5

📥 Commits

Reviewing files that changed from the base of the PR and between 4038ed8 and 5dd413a.

📒 Files selected for processing (26)
  • controller/perf_metrics.go
  • controller/relay.go
  • main.go
  • model/main.go
  • model/perf_metric.go
  • pkg/perf_metrics/flush.go
  • pkg/perf_metrics/metrics.go
  • pkg/perf_metrics/types.go
  • router/api-router.go
  • service/quota.go
  • service/text_quota.go
  • setting/perf_metrics_setting/config.go
  • web/default/src/features/pricing/api.ts
  • web/default/src/features/pricing/components/model-details-charts.tsx
  • web/default/src/features/pricing/components/model-details-performance.tsx
  • web/default/src/features/pricing/components/model-details.tsx
  • web/default/src/features/system-settings/maintenance/config.ts
  • web/default/src/features/system-settings/maintenance/performance-section.tsx
  • web/default/src/features/system-settings/maintenance/section-registry.tsx
  • web/default/src/features/system-settings/types.ts
  • web/default/src/i18n/locales/en.json
  • web/default/src/i18n/locales/fr.json
  • web/default/src/i18n/locales/ja.json
  • web/default/src/i18n/locales/ru.json
  • web/default/src/i18n/locales/vi.json
  • web/default/src/i18n/locales/zh.json

Walkthrough

Adds an end-to-end model performance metrics system: in-memory hot buckets + Redis counters, periodic flush to DB, new PerfMetric ORM and migrations, GET /api/perf-metrics handler, backend instrumentation points, settings and UI for aggregation/flush/retention, plus frontend types and translations.

Changes

Model Performance Metrics (single cohesive DAG)

Layer / File(s) Summary
Data Shape & Types
pkg/perf_metrics/types.go, web/default/src/features/pricing/api.ts
Introduces Sample/QueryParams/BucketPoint/GroupResult/QueryResult and atomicBucket/counters; adds TypeScript types PerformanceSeriesPoint, PerformanceGroup, PerformanceMetricsData.
ORM Model & Migrations
model/perf_metric.go, model/main.go
Adds PerfMetric GORM model with Upsert/Get/Delete helpers; registers &PerfMetric{} in AutoMigrate and fast migrations.
Configuration
setting/perf_metrics_setting/config.go, web/default/src/features/system-settings/...
Adds PerfMetricsSetting (enabled, flush_interval, bucket_time, retention_days), default values, bucket-second mapping, and frontend form schema/UI wiring and types.
Core Collection & Query API
pkg/perf_metrics/metrics.go
Implements Init(), RecordRelaySample(), Record(), Query(); manages hotBuckets, merges counters from memory/Redis/DB, and composes QueryResult.
Periodic Flush & Cleanup
pkg/perf_metrics/flush.go
Background flushLoop drains hot buckets on interval, upserts aggregated buckets to DB, removes old empty buckets, and prunes expired DB metrics.
Backend Instrumentation
controller/relay.go, service/quota.go, service/text_quota.go
Imports perfmetrics and records relay samples asynchronously on relay failures and after quota consumption.
Initialization & HTTP API
main.go, controller/perf_metrics.go, router/api-router.go
Calls perfmetrics.Init() during InitResources; adds controller.GetPerfMetrics handler parsing model/hours and calling perfmetrics.Query; registers GET /perf-metrics with TryUserAuth.
Frontend: Client & UI
web/default/src/features/pricing/components/model-details-performance.tsx, .../model-details-charts.tsx, web/default/src/features/pricing/api.ts
Adds getPerfMetrics client; refactors ModelDetailsPerformance to fetch live metrics, compute latency/uptime series and per-group table; adjusts date formatting for ISO timestamps.
Settings Defaults & Registry
web/default/src/features/system-settings/maintenance/*, web/default/src/features/system-settings/types.ts
Adds perf_metrics_setting defaults, form schema, UI section, and MaintenanceSettings fields for frontend.
Localization
web/default/src/i18n/locales/*.json
Adds translations (en, fr, ja, ru, vi, zh) for metrics labels, aggregation bucket, flush/retention controls, time units, availability/latency strings.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant QueryAPI as Query API
    participant Metrics as MetricsCollector
    participant Hot as HotBucket
    participant Redis
    participant DB as Database
    participant Relay

    Relay->>Metrics: RecordRelaySample(relayInfo, success)
    activate Metrics
    Metrics->>Hot: Record(sample) (atomicBucket.add)
    Hot-->>Metrics: ack
    Metrics->>Redis: recordRedis(sample) (incr per-bucket counters)
    Redis-->>Metrics: ack
    deactivate Metrics

    loop Periodic flush
        Metrics->>Hot: flushCompletedBuckets (drain)
        activate Hot
        Hot->>DB: UpsertPerfMetric(metric)
        DB-->>Hot: ack
        Hot-->>Metrics: ack
        deactivate Hot
        Metrics->>DB: DeletePerfMetricsBefore(cutoff)
        DB-->>Metrics: ack
    end

    Client->>QueryAPI: GET /api/perf-metrics?model=X&hours=24
    activate QueryAPI
    QueryAPI->>Metrics: Query(params)
    activate Metrics
    Metrics->>DB: GetPerfMetrics(start,end)
    DB-->>Metrics: []PerfMetric
    Metrics->>Redis: merge active buckets
    Metrics->>Hot: snapshot in-memory buckets
    Metrics-->>QueryAPI: QueryResult (groups, series)
    deactivate Metrics
    QueryAPI-->>Client: 200 JSON
    deactivate QueryAPI
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • QuantumNous/new-api#4635: Appears to modify the same perf metrics feature set (controller, pkg/perf_metrics, model PerfMetric, router, integrations).

Suggested reviewers

  • seefs001

Poem

🐰 I hopped through buckets, counters bright,

Redis hummed and kept things tight,
Flush at dawn, the DB aglow,
Charts and groups in tidy rows,
Rabbit cheers — metrics in flight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 2.13% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat: collect model performance metrics' clearly and accurately describes the main feature being added across the entire changeset—a comprehensive model performance metrics collection pipeline.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch cursor/model-performance-metrics

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 15

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
web/default/src/i18n/locales/ru.json (1)

32-3549: 🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift

Migrate newly added i18n keys to a hierarchical namespace instead of flat English sentences.

The newly added keys continue the flat-key pattern (e.g., Line 226, Line 1309, Line 2238), which conflicts with the repo’s i18n key-structure rule. Please add these under a scoped namespace (for example performance.metrics.*) and wire usages accordingly.

As per coding guidelines, use hierarchical and semantically clear translation key names such as dashboard.overview.title and maintain naming consistency.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/i18n/locales/ru.json` around lines 32 - 3549, Several newly
added i18n entries use flat English-sentence keys (e.g., "Average latency",
"Average TTFT", "Success rate") which violates our hierarchical key convention;
move these keys into a scoped namespace like performance.metrics.averageLatency,
performance.metrics.averageTTFT, performance.metrics.successRate (or similar
semantic names under performance.metrics.*), update the ru.json entries to use
those new keys, and then update all references in the codebase that consume the
old flat keys (components/pages that call the i18n lookup for "Average latency",
"Average TTFT", "Success rate", etc.) to use the new namespaced keys; also add
temporary fallback mappings (or keep the old flat keys referencing the new keys)
to avoid runtime breakage during rollout and ensure naming consistency with
existing keys such as dashboard.overview.title.
service/quota.go (1)

159-258: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

PostWssConsumeQuota is missing the perf-metric recording.

PostAudioConsumeQuota (line 379) and PostTextConsumeQuota both end with gopool.Go(func() { perfmetrics.RecordRelaySample(relayInfo, true) }), but the realtime/WSS success path here does not. As a result, successful realtime sessions will not contribute to TTFT/latency/success-rate aggregates surfaced by /api/perf-metrics, which is the same gap noted on the relay error path. If the omission is intentional (e.g., realtime semantics differ), please confirm; otherwise mirror the same async record at the end of this function.

♻️ Suggested addition (mirrors PostAudioConsumeQuota)
 	model.RecordConsumeLog(ctx, relayInfo.UserId, model.RecordConsumeLogParams{
 		...
 		Other:            other,
 	})
+	gopool.Go(func() {
+		perfmetrics.RecordRelaySample(relayInfo, true)
+	})
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@service/quota.go` around lines 159 - 258, PostWssConsumeQuota is missing the
async perf-metric recording done in PostAudioConsumeQuota/PostTextConsumeQuota;
add the same non-blocking call after the successful flow (after
model.RecordConsumeLog returns) by invoking gopool.Go(func() {
perfmetrics.RecordRelaySample(relayInfo, true) }) so successful realtime/WSS
sessions are included in TTFT/latency/success-rate aggregates.
🧹 Nitpick comments (5)
web/default/src/i18n/locales/fr.json (1)

226-226: 🏗️ Heavy lift

Use hierarchical i18n keys for the newly added performance-metrics entries.

These additions keep sentence-style keys instead of semantic hierarchical keys, which makes key reuse and maintenance harder over time.

♻️ Suggested direction
- "Model performance metrics": "Indicateurs de performance des modèles",
- "Average latency": "Latence moyenne",
- "Success rate": "Taux de réussite",
+ "performance.metrics.model.title": "Indicateurs de performance des modèles",
+ "performance.metrics.latency.average": "Latence moyenne",
+ "performance.metrics.successRate": "Taux de réussite",

As per coding guidelines, "Use hierarchical and semantically clear translation key names such as dashboard.overview.title and maintain naming consistency".

Also applies to: 432-443, 724-724, 1309-1309, 1675-1675, 2238-2238, 3125-3126, 3175-3175, 3549-3549

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/i18n/locales/fr.json` at line 226, The translation key
"Aggregation bucket" (and the other listed sentence-style keys) should be
renamed to hierarchical, semantic keys (e.g.
performanceMetrics.aggregationBucket or dashboard.performance.aggregationBucket)
and the corresponding references updated where used; locate the key string
"Aggregation bucket" in fr.json and replace it with a semantically-nested key
(follow existing naming pattern such as performanceMetrics.* or dashboard.*),
update the matching keys for the other ranges (432-443, 724, 1309, 1675, 2238,
3125-3126, 3175, 3549) to use the same hierarchical convention, and ensure any
code or components referencing these keys are updated to the new key names
(search for literal usages of "Aggregation bucket" and the other sentence-style
keys and replace with the new dotted keys).
setting/perf_metrics_setting/config.go (1)

27-37: ⚡ Quick win

Validate/normalize BucketTime instead of silently defaulting on unknown values.

At Line 35–36, unsupported values quietly map to 3600, which can hide config mistakes. Consider normalizing input (strings.ToLower) and validating against allowed values at load time so bad config is visible early.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@setting/perf_metrics_setting/config.go` around lines 27 - 37,
GetBucketSeconds currently silently returns 3600 for any unknown
perfMetricsSetting.BucketTime; instead validate and normalize the value early:
normalize perfMetricsSetting.BucketTime with strings.ToLower and either return
an explicit error or panic/log and fallback when loading the configuration
(e.g., in the config loader that sets perfMetricsSetting) if the value is not
one of the allowed set {"minute","5min","hour"}; update GetBucketSeconds to
assume a validated value (or return an error/ok pair) and document allowed
values so misconfiguration surfaces at startup rather than quietly mapping to
3600.
web/default/src/i18n/locales/ja.json (1)

226-226: ⚡ Quick win

Namespace the new performance-metrics translation keys.

These additions keep using English display strings as keys. Please move the new perf-metrics entries under a dedicated namespace such as perfMetrics.* so this feature follows the repo’s i18n convention and stays maintainable as the surface grows.

As per coding guidelines, "Use hierarchical and semantically clear translation key names such as dashboard.overview.title and maintain naming consistency".

Also applies to: 432-443, 724-725, 1309-1309, 1675-1675, 2238-2238, 2414-2414, 3125-3126, 3175-3175, 3549-3549

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/i18n/locales/ja.json` at line 226, Several new i18n entries
(e.g., the key "Aggregation bucket" and the other keys referenced at lines
432-443, 724-725, 1309, 1675, 2238, 2414, 3125-3126, 3175, 3549) are using
English display strings as top-level keys; rename and nest them under a
dedicated namespace like perfMetrics (for example perfMetrics.aggregationBucket)
to follow the repo convention. Update the JSON keys in
web/default/src/i18n/locales/ja.json accordingly (replace the raw English keys
with perfMetrics.* keys) and ensure any code referencing these keys (components
rendering performance-metrics UI) is updated to use the new perfMetrics.<key>
names so translations resolve correctly.
web/default/src/features/pricing/components/model-details-performance.tsx (2)

142-142: 💤 Low value

Defensive optional chaining on the inner data envelope.

metricsQuery.data?.data.groups only guards the outer metricsQuery.data. The backend response is a { success, message?, data: { ... } } envelope, and on certain failure shapes (e.g., the handler returns { success: false, message } with HTTP 500 — see controller/perf_metrics.go) the data field will be absent. If response interceptors ever resolve such payloads instead of throwing, this access will throw on .groups. A second ?. is essentially free.

-  const groups = metricsQuery.data?.data.groups ?? []
+  const groups = metricsQuery.data?.data?.groups ?? []
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/features/pricing/components/model-details-performance.tsx` at
line 142, The assignment to groups uses only metricsQuery.data?.data.groups
which can throw if the inner response envelope lacks data; update the expression
that defines the const groups (the line binding the variable named groups from
metricsQuery) to defensively optional-chain the inner envelope (use
metricsQuery.data?.data?.groups) and keep the fallback (?? []) so groups is
always an array; locate the const groups assignment in the component (reference
symbols: metricsQuery and groups) and apply the extra ?. to the inner data
access.

137-141: ⚡ Quick win

Include hours in queryKey to avoid stale-cache bugs if it becomes dynamic.

hours is hardcoded to 24 today, but the queryKey only contains model_name. If a caller later parameterizes hours (e.g., 1h/24h/7d toggles), React Query will return cached data from a previous range until staleTime elapses. Cheap to make the key fully describe the request now.

♻️ Suggested change
-  const metricsQuery = useQuery({
-    queryKey: ['perf-metrics', props.model.model_name],
-    queryFn: () => getPerfMetrics(props.model.model_name, 24),
-    staleTime: 60 * 1000,
-  })
+  const hours = 24
+  const metricsQuery = useQuery({
+    queryKey: ['perf-metrics', props.model.model_name, hours],
+    queryFn: () => getPerfMetrics(props.model.model_name, hours),
+    staleTime: 60 * 1000,
+  })

As per coding guidelines: "configure a unique queryKey (preferably as an array with consistent hierarchy)".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/features/pricing/components/model-details-performance.tsx`
around lines 137 - 141, The useQuery call for metricsQuery currently keys only
by ['perf-metrics', props.model.model_name] while getPerfMetrics is called with
a hardcoded 24; make the key fully describe the request by adding an hours
variable into the queryKey (e.g., ['perf-metrics', props.model.model_name,
hours]) and use that same hours variable in the queryFn call to getPerfMetrics
so the cache updates correctly if hours becomes dynamic; update the metricsQuery
initialization (useQuery, metricsQuery, getPerfMetrics, props.model.model_name)
to reflect this change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@controller/perf_metrics.go`:
- Around line 22-27: Validate the parsed hours value after strconv.Atoi: if
rawHours is provided, ensure the resulting hours is within an acceptable
positive range (e.g., >=1 and <= a max like 168 or another configured cap) and
reject invalid values instead of silently using them; return a 400 Bad Request
(using the controller's context response methods) for non-positive or oversized
inputs so perfmetrics.Query never receives -/zero/huge ranges. Check/adjust the
variable named hours (and rawHours) in controller/perf_metrics.go where you call
strconv.Atoi and before passing hours to perfmetrics.Query.
- Around line 34-39: The handler currently returns err.Error() to the client (in
the c.JSON block) which can leak internal DB/redis details; instead log the
original error server-side (e.g., using your existing logger or log.Printf) and
respond with a generic message like "internal server error" or "failed to fetch
performance metrics"; update the error branch surrounding perfmetrics.Query and
the c.JSON call to emit the generic message to the client while preserving the
full err in server logs for debugging.

In `@model/perf_metric.go`:
- Around line 13-15: Add a non-unique composite index on (model_name, bucket_ts)
so queries filtering by ModelName and BucketTs can use an efficient range scan;
update the GORM tags on the ModelName and BucketTs struct fields (ModelName and
BucketTs) to include a shared index name (e.g. index:idx_perf_model_bucket) with
appropriate priorities (priority:1 on ModelName, priority:2 on BucketTs) while
keeping the existing uniqueIndex idx_perf_model_group_bucket unchanged.

In `@pkg/perf_metrics/flush.go`:
- Around line 36-38: After a successful flush we must remove empty bucket
entries immediately to avoid growing dead sync.Map entries: in the branch that
checks drained.requestCount == 0 (and the similar branch around the 57-65
range), call deleteOldEmptyBucket(k, key) and return true right after confirming
drained.requestCount is zero so the (model, group, bucketTs) entry is removed
instead of being left for 24h; ensure you update both places that currently
leave empty buckets alive so they both delete and return immediately.

In `@pkg/perf_metrics/metrics.go`:
- Around line 18-20: Init currently only starts the background flushLoop so
there's no way to synchronously drain hotBuckets on shutdown; add an exported
FlushNow or Shutdown function that triggers an immediate flush and waits for
completion. Implement this by giving flushLoop a control channel (e.g.,
flushTrigger chan struct{} and done chan struct{}) or a context/WaitGroup so
flushLoop listens for a trigger and signals when the flush finished; export
FlushNow/Shutdown to send on that channel or cancel the context and block until
the flush completes, then return; update Init to initialize the control
channels/ctx so callers can call FlushNow before closing the DB. Ensure the
flush routine that reads hotBuckets is reused by both periodic ticks and the
synchronous trigger so no metrics are lost.
- Around line 221-235: The Redis TTL is hard-coded to time.Hour in the pipeline
(pipe.Expire(ctx, redisKey, time.Hour)); update this to use a configured TTL or
compute it from your existing bucket/flush settings instead: retrieve the
configured TTL (or compute e.g. based on bucket size and flush interval) and
replace the literal with that variable before calling pipe.Expire so
redisBucketKey counters won't expire prematurely; update code paths that build
the pipeline in the function using redisBucketKey/TxPipeline/Expire to reference
the new ttl value.
- Around line 74-105: The Query implementation builds a merged map from DB rows
and in-process hotBuckets but never incorporates Redis-backed active counters;
call mergeRedisActiveBuckets with the same params and merged map (e.g.
mergeRedisActiveBuckets(params.Model, params.Group, startTs, endTs, merged))
after the hotBuckets.Range merge and before calling buildQueryResult, handle and
return any error from mergeRedisActiveBuckets so the Query returns the combined
in-memory+Redis data.

In `@pkg/perf_metrics/types.go`:
- Around line 73-105: The bucket methods (atomicBucket.add, snapshot, drain)
race because hotBuckets holds pointers but the five fields are updated/loaded
separately; fix by making updates and reads atomic across all fields—either add
a sync.Mutex (e.g., put mu in atomicBucket and lock in add, snapshot, drain) or
replace the five atomics with a single atomic.Value holding a counters struct
and use Load/Store/CompareAndSwap to update; ensure Record(), Query(), and the
flush loop use the new atomicBucket API so each sample is applied or drained as
a single atomic operation and no fields can be split across flushes.

In `@web/default/src/features/pricing/components/model-details-performance.tsx`:
- Around line 164-170: The current check conflates loading, empty, and error
states; update the render logic in model-details-performance.tsx to branch
explicitly on metricsQuery.isLoading (show a spinner or skeleton),
metricsQuery.isError (call handleServerError(metricsQuery.error) and render an
i18n error message with a retry affordance that calls metricsQuery.refetch), and
finally when performances.length === 0 render the existing "Performance data is
not yet available" copy; reference metricsQuery, performances,
handleServerError, and metricsQuery.refetch when implementing these branches and
use i18n keys for any user-facing text.

In `@web/default/src/features/system-settings/maintenance/config.ts`:
- Around line 78-81: The default perf metrics config currently enables metrics
collection ('perf_metrics_setting.enabled' = true) and sets
'perf_metrics_setting.retention_days' = 0 which causes indefinite retention;
change the defaults to avoid unbounded storage growth by either disabling
collection by default (set 'perf_metrics_setting.enabled' = false) or assigning
a finite retention window (e.g., set 'perf_metrics_setting.retention_days' to a
sensible default like 30) and keep 'perf_metrics_setting.flush_interval' and
'perf_metrics_setting.bucket_time' as-is; update the config in config.ts where
these keys are defined and add a short comment clarifying the rationale for the
new default.

In
`@web/default/src/features/system-settings/maintenance/performance-section.tsx`:
- Around line 62-65: The schema currently allows decimals for
'perf_metrics_setting.flush_interval' and 'perf_metrics_setting.retention_days'
so change their validators to use z.coerce.number().int().min(...) (i.e., make
both .int()) to enforce integer input, and update the corresponding number input
components in performance-section.tsx for those fields to include step={1} (and
keep min={1} for flush_interval and min={0} for retention_days) so the UI and
schema match the backend int contract.

In `@web/default/src/i18n/locales/en.json`:
- Line 32: Replace the source-text translation key "{{count}} incidents in the
last 24 hours" with a hierarchical, semantic key (e.g.,
"incidents.recent.count24h") and keep the English sentence as the value; update
any consumers to use the new key. Do the same for the other listed keys (lines
referenced: occurrences at 63, 67, 70, 93, 226, 432, 437-438, 440, 443, 724,
1309, 1675, 2238, 2414, 3125-3126, 3175, 3549) using consistent namespaced
patterns like "incidents.*", "dashboard.*" or "performance.*" as appropriate,
and ensure translation lookups (e.g., calls reading these JSON keys) are updated
to the new semantic keys.
- Line 724: Update the user-facing string that currently reads "Collect relay
latency and success-rate metrics for the model square." to use the product name
capitalized: "Collect relay latency and success-rate metrics for the Model
Square." Locate and edit the matching JSON entry where the key/value contains
"Collect relay latency and success-rate metrics for the model square." and
replace the lowercase "model square" with "Model Square" so both key and value
reflect the corrected product-name capitalization.

In `@web/default/src/i18n/locales/ru.json`:
- Line 1675: The translation for the key "Flush interval (minutes)" uses
"Интервал записи" which implies a write interval; update the value in ru.json
for the string "Flush interval (minutes)" to a more accurate term like "Интервал
сброса (минуты)" or "Интервал выгрузки (минуты)" to reflect flush/drain
semantics while preserving the original key exactly.

In `@web/default/src/i18n/locales/vi.json`:
- Line 226: The translation key "Aggregation bucket" in vi.json uses a raw
English sentence key; rename it to a hierarchical semantic key (e.g.,
performance.metrics.aggregationBucket) and update the corresponding key in all
other locale files and components that reference the old key (see other affected
ranges noted) so lookups use performance.metrics.aggregationBucket instead of
"Aggregation bucket"; ensure you adjust any code that calls the string (e.g.,
components or hooks that reference "Aggregation bucket") to the new hierarchical
key and keep the same Vietnamese value.

---

Outside diff comments:
In `@service/quota.go`:
- Around line 159-258: PostWssConsumeQuota is missing the async perf-metric
recording done in PostAudioConsumeQuota/PostTextConsumeQuota; add the same
non-blocking call after the successful flow (after model.RecordConsumeLog
returns) by invoking gopool.Go(func() { perfmetrics.RecordRelaySample(relayInfo,
true) }) so successful realtime/WSS sessions are included in
TTFT/latency/success-rate aggregates.

In `@web/default/src/i18n/locales/ru.json`:
- Around line 32-3549: Several newly added i18n entries use flat
English-sentence keys (e.g., "Average latency", "Average TTFT", "Success rate")
which violates our hierarchical key convention; move these keys into a scoped
namespace like performance.metrics.averageLatency,
performance.metrics.averageTTFT, performance.metrics.successRate (or similar
semantic names under performance.metrics.*), update the ru.json entries to use
those new keys, and then update all references in the codebase that consume the
old flat keys (components/pages that call the i18n lookup for "Average latency",
"Average TTFT", "Success rate", etc.) to use the new namespaced keys; also add
temporary fallback mappings (or keep the old flat keys referencing the new keys)
to avoid runtime breakage during rollout and ensure naming consistency with
existing keys such as dashboard.overview.title.

---

Nitpick comments:
In `@setting/perf_metrics_setting/config.go`:
- Around line 27-37: GetBucketSeconds currently silently returns 3600 for any
unknown perfMetricsSetting.BucketTime; instead validate and normalize the value
early: normalize perfMetricsSetting.BucketTime with strings.ToLower and either
return an explicit error or panic/log and fallback when loading the
configuration (e.g., in the config loader that sets perfMetricsSetting) if the
value is not one of the allowed set {"minute","5min","hour"}; update
GetBucketSeconds to assume a validated value (or return an error/ok pair) and
document allowed values so misconfiguration surfaces at startup rather than
quietly mapping to 3600.

In `@web/default/src/features/pricing/components/model-details-performance.tsx`:
- Line 142: The assignment to groups uses only metricsQuery.data?.data.groups
which can throw if the inner response envelope lacks data; update the expression
that defines the const groups (the line binding the variable named groups from
metricsQuery) to defensively optional-chain the inner envelope (use
metricsQuery.data?.data?.groups) and keep the fallback (?? []) so groups is
always an array; locate the const groups assignment in the component (reference
symbols: metricsQuery and groups) and apply the extra ?. to the inner data
access.
- Around line 137-141: The useQuery call for metricsQuery currently keys only by
['perf-metrics', props.model.model_name] while getPerfMetrics is called with a
hardcoded 24; make the key fully describe the request by adding an hours
variable into the queryKey (e.g., ['perf-metrics', props.model.model_name,
hours]) and use that same hours variable in the queryFn call to getPerfMetrics
so the cache updates correctly if hours becomes dynamic; update the metricsQuery
initialization (useQuery, metricsQuery, getPerfMetrics, props.model.model_name)
to reflect this change.

In `@web/default/src/i18n/locales/fr.json`:
- Line 226: The translation key "Aggregation bucket" (and the other listed
sentence-style keys) should be renamed to hierarchical, semantic keys (e.g.
performanceMetrics.aggregationBucket or dashboard.performance.aggregationBucket)
and the corresponding references updated where used; locate the key string
"Aggregation bucket" in fr.json and replace it with a semantically-nested key
(follow existing naming pattern such as performanceMetrics.* or dashboard.*),
update the matching keys for the other ranges (432-443, 724, 1309, 1675, 2238,
3125-3126, 3175, 3549) to use the same hierarchical convention, and ensure any
code or components referencing these keys are updated to the new key names
(search for literal usages of "Aggregation bucket" and the other sentence-style
keys and replace with the new dotted keys).

In `@web/default/src/i18n/locales/ja.json`:
- Line 226: Several new i18n entries (e.g., the key "Aggregation bucket" and the
other keys referenced at lines 432-443, 724-725, 1309, 1675, 2238, 2414,
3125-3126, 3175, 3549) are using English display strings as top-level keys;
rename and nest them under a dedicated namespace like perfMetrics (for example
perfMetrics.aggregationBucket) to follow the repo convention. Update the JSON
keys in web/default/src/i18n/locales/ja.json accordingly (replace the raw
English keys with perfMetrics.* keys) and ensure any code referencing these keys
(components rendering performance-metrics UI) is updated to use the new
perfMetrics.<key> names so translations resolve correctly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1a7b42c4-6fee-4f7a-929a-50b95d3e9be5

📥 Commits

Reviewing files that changed from the base of the PR and between 8b2b03d and 4038ed8.

📒 Files selected for processing (26)
  • controller/perf_metrics.go
  • controller/relay.go
  • main.go
  • model/main.go
  • model/perf_metric.go
  • pkg/perf_metrics/flush.go
  • pkg/perf_metrics/metrics.go
  • pkg/perf_metrics/types.go
  • router/api-router.go
  • service/quota.go
  • service/text_quota.go
  • setting/perf_metrics_setting/config.go
  • web/default/src/features/pricing/api.ts
  • web/default/src/features/pricing/components/model-details-charts.tsx
  • web/default/src/features/pricing/components/model-details-performance.tsx
  • web/default/src/features/pricing/components/model-details.tsx
  • web/default/src/features/system-settings/maintenance/config.ts
  • web/default/src/features/system-settings/maintenance/performance-section.tsx
  • web/default/src/features/system-settings/maintenance/section-registry.tsx
  • web/default/src/features/system-settings/types.ts
  • web/default/src/i18n/locales/en.json
  • web/default/src/i18n/locales/fr.json
  • web/default/src/i18n/locales/ja.json
  • web/default/src/i18n/locales/ru.json
  • web/default/src/i18n/locales/vi.json
  • web/default/src/i18n/locales/zh.json
💤 Files with no reviewable changes (1)
  • web/default/src/features/pricing/components/model-details.tsx

Comment on lines +22 to +27
hours := 24
if rawHours := c.Query("hours"); rawHours != "" {
if parsed, err := strconv.Atoi(rawHours); err == nil {
hours = parsed
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Validate hours bounds (and reject non-positive / oversized values).

hours is parsed via strconv.Atoi without any range check, so values like -1, 0, or 999999 are accepted and forwarded into perfmetrics.Query. Combined with the route being protected by TryUserAuth (anonymous-friendly), this lets unauthenticated callers issue arbitrarily expensive lookups against PerfMetric, and also produces undefined behavior for non-positive ranges depending on Query's assumptions.

🛡️ Suggested clamp
 	hours := 24
 	if rawHours := c.Query("hours"); rawHours != "" {
-		if parsed, err := strconv.Atoi(rawHours); err == nil {
-			hours = parsed
-		}
+		if parsed, err := strconv.Atoi(rawHours); err == nil && parsed > 0 {
+			if parsed > 24*7 { // cap to a week (or your retention window)
+				parsed = 24 * 7
+			}
+			hours = parsed
+		}
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
hours := 24
if rawHours := c.Query("hours"); rawHours != "" {
if parsed, err := strconv.Atoi(rawHours); err == nil {
hours = parsed
}
}
hours := 24
if rawHours := c.Query("hours"); rawHours != "" {
if parsed, err := strconv.Atoi(rawHours); err == nil && parsed > 0 {
if parsed > 24*7 { // cap to a week (or your retention window)
parsed = 24 * 7
}
hours = parsed
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/perf_metrics.go` around lines 22 - 27, Validate the parsed hours
value after strconv.Atoi: if rawHours is provided, ensure the resulting hours is
within an acceptable positive range (e.g., >=1 and <= a max like 168 or another
configured cap) and reject invalid values instead of silently using them; return
a 400 Bad Request (using the controller's context response methods) for
non-positive or oversized inputs so perfmetrics.Query never receives -/zero/huge
ranges. Check/adjust the variable named hours (and rawHours) in
controller/perf_metrics.go where you call strconv.Atoi and before passing hours
to perfmetrics.Query.

Comment on lines +34 to +39
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
"message": err.Error(),
})
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Avoid leaking raw internal errors to the client.

err.Error() from perfmetrics.Query may surface DB driver text, table/column names, or redis details to anonymous callers (route uses TryUserAuth). Log the original error server-side and respond with a generic message.

🔒️ Suggested change
-	if err != nil {
-		c.JSON(http.StatusInternalServerError, gin.H{
-			"success": false,
-			"message": err.Error(),
-		})
-		return
-	}
+	if err != nil {
+		common.SysError("perf-metrics query failed: " + err.Error())
+		c.JSON(http.StatusInternalServerError, gin.H{
+			"success": false,
+			"message": "failed to query performance metrics",
+		})
+		return
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
"message": err.Error(),
})
return
if err != nil {
common.SysError("perf-metrics query failed: " + err.Error())
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
"message": "failed to query performance metrics",
})
return
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/perf_metrics.go` around lines 34 - 39, The handler currently
returns err.Error() to the client (in the c.JSON block) which can leak internal
DB/redis details; instead log the original error server-side (e.g., using your
existing logger or log.Printf) and respond with a generic message like "internal
server error" or "failed to fetch performance metrics"; update the error branch
surrounding perfmetrics.Query and the c.JSON call to emit the generic message to
the client while preserving the full err in server logs for debugging.

Comment thread model/perf_metric.go
Comment on lines +13 to +15
ModelName string `json:"model_name" gorm:"size:128;uniqueIndex:idx_perf_model_group_bucket,priority:1"`
Group string `json:"group" gorm:"column:group;size:64;uniqueIndex:idx_perf_model_group_bucket,priority:2"`
BucketTs int64 `json:"bucket_ts" gorm:"uniqueIndex:idx_perf_model_group_bucket,priority:3;index:idx_perf_bucket_ts"`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add a (model_name, bucket_ts) index for the main query path.

GetPerfMetrics always filters by model_name and bucket_ts, but the only composite index here is (model_name, group, bucket_ts). When group is omitted, MySQL/PostgreSQL cannot use the bucket_ts range efficiently, so model-wide reads will degrade as retention grows.

Suggested index change
 type PerfMetric struct {
 	Id             int    `json:"id" gorm:"primaryKey"`
-	ModelName      string `json:"model_name" gorm:"size:128;uniqueIndex:idx_perf_model_group_bucket,priority:1"`
+	ModelName      string `json:"model_name" gorm:"size:128;uniqueIndex:idx_perf_model_group_bucket,priority:1;index:idx_perf_model_bucket,priority:1"`
 	Group          string `json:"group" gorm:"column:group;size:64;uniqueIndex:idx_perf_model_group_bucket,priority:2"`
-	BucketTs       int64  `json:"bucket_ts" gorm:"uniqueIndex:idx_perf_model_group_bucket,priority:3;index:idx_perf_bucket_ts"`
+	BucketTs       int64  `json:"bucket_ts" gorm:"uniqueIndex:idx_perf_model_group_bucket,priority:3;index:idx_perf_bucket_ts;index:idx_perf_model_bucket,priority:2"`
 	RequestCount   int64  `json:"request_count" gorm:"default:0"`
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
ModelName string `json:"model_name" gorm:"size:128;uniqueIndex:idx_perf_model_group_bucket,priority:1"`
Group string `json:"group" gorm:"column:group;size:64;uniqueIndex:idx_perf_model_group_bucket,priority:2"`
BucketTs int64 `json:"bucket_ts" gorm:"uniqueIndex:idx_perf_model_group_bucket,priority:3;index:idx_perf_bucket_ts"`
type PerfMetric struct {
Id int `json:"id" gorm:"primaryKey"`
ModelName string `json:"model_name" gorm:"size:128;uniqueIndex:idx_perf_model_group_bucket,priority:1;index:idx_perf_model_bucket,priority:1"`
Group string `json:"group" gorm:"column:group;size:64;uniqueIndex:idx_perf_model_group_bucket,priority:2"`
BucketTs int64 `json:"bucket_ts" gorm:"uniqueIndex:idx_perf_model_group_bucket,priority:3;index:idx_perf_bucket_ts;index:idx_perf_model_bucket,priority:2"`
RequestCount int64 `json:"request_count" gorm:"default:0"`
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@model/perf_metric.go` around lines 13 - 15, Add a non-unique composite index
on (model_name, bucket_ts) so queries filtering by ModelName and BucketTs can
use an efficient range scan; update the GORM tags on the ModelName and BucketTs
struct fields (ModelName and BucketTs) to include a shared index name (e.g.
index:idx_perf_model_bucket) with appropriate priorities (priority:1 on
ModelName, priority:2 on BucketTs) while keeping the existing uniqueIndex
idx_perf_model_group_bucket unchanged.

Comment thread pkg/perf_metrics/flush.go Resolved
Comment on lines +18 to +20
func Init() {
go flushLoop()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Expose a shutdown flush for the perf-metrics worker.

Init only starts the background loop. There is no way to drain hotBuckets before process exit, so every deploy/restart can drop up to one full flush interval of metrics. Please add a synchronous FlushNow/Shutdown path and call it during server shutdown before the DB is closed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/perf_metrics/metrics.go` around lines 18 - 20, Init currently only starts
the background flushLoop so there's no way to synchronously drain hotBuckets on
shutdown; add an exported FlushNow or Shutdown function that triggers an
immediate flush and waits for completion. Implement this by giving flushLoop a
control channel (e.g., flushTrigger chan struct{} and done chan struct{}) or a
context/WaitGroup so flushLoop listens for a trigger and signals when the flush
finished; export FlushNow/Shutdown to send on that channel or cancel the context
and block until the flush completes, then return; update Init to initialize the
control channels/ctx so callers can call FlushNow before closing the DB. Ensure
the flush routine that reads hotBuckets is reused by both periodic ticks and the
synchronous trigger so no metrics are lost.

Comment on lines +62 to +65
'perf_metrics_setting.enabled': z.boolean(),
'perf_metrics_setting.flush_interval': z.coerce.number().min(1),
'perf_metrics_setting.bucket_time': z.enum(['minute', '5min', 'hour']),
'perf_metrics_setting.retention_days': z.coerce.number().min(0),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Validate flush_interval and retention_days as integers.

The backend contract models both fields as int, but this schema accepts decimals. Values like 1.5 will pass client validation and then be truncated or rejected server-side. Please make these .int() here and set step={1} on the corresponding inputs.

🛠️ Proposed fix
-  'perf_metrics_setting.flush_interval': z.coerce.number().min(1),
+  'perf_metrics_setting.flush_interval': z.coerce.number().int().min(1),
   'perf_metrics_setting.bucket_time': z.enum(['minute', '5min', 'hour']),
-  'perf_metrics_setting.retention_days': z.coerce.number().min(0),
+  'perf_metrics_setting.retention_days': z.coerce.number().int().min(0),
<Input type='number' min={1} step={1} {...field} disabled={!perfMetricsEnabled} />
<Input type='number' min={0} step={1} {...field} disabled={!perfMetricsEnabled} />
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/features/system-settings/maintenance/performance-section.tsx`
around lines 62 - 65, The schema currently allows decimals for
'perf_metrics_setting.flush_interval' and 'perf_metrics_setting.retention_days'
so change their validators to use z.coerce.number().int().min(...) (i.e., make
both .int()) to enforce integer input, and update the corresponding number input
components in performance-section.tsx for those fields to include step={1} (and
keep min={1} for flush_interval and min={0} for retention_days) so the UI and
schema match the backend int contract.

"{{count}} disabled channel(s) deleted": "{{count}} disabled channel(s) deleted",
"{{count}} hours ago": "{{count}} hours ago",
"{{count}} incidents": "{{count}} incidents",
"{{count}} incidents in the last 24 hours": "{{count}} incidents in the last 24 hours",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift

Use hierarchical semantic i18n keys for new entries

These new keys are source-text phrases instead of semantic keys, which makes localization maintenance and cross-locale consistency brittle. Please add new keys using a namespaced pattern (e.g., performance.metrics.averageLatency) and keep the English string in the value.

As per coding guidelines, web/default/src/i18n/**/*.{ts,tsx,json}: "Use hierarchical and semantically clear translation key names such as dashboard.overview.title and maintain naming consistency".

Also applies to: 63-63, 67-67, 70-70, 93-93, 226-226, 432-432, 437-438, 440-440, 443-443, 724-724, 1309-1309, 1675-1675, 2238-2238, 2414-2414, 3125-3126, 3175-3175, 3549-3549

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/i18n/locales/en.json` at line 32, Replace the source-text
translation key "{{count}} incidents in the last 24 hours" with a hierarchical,
semantic key (e.g., "incidents.recent.count24h") and keep the English sentence
as the value; update any consumers to use the new key. Do the same for the other
listed keys (lines referenced: occurrences at 63, 67, 70, 93, 226, 432, 437-438,
440, 443, 724, 1309, 1675, 2238, 2414, 3125-3126, 3175, 3549) using consistent
namespaced patterns like "incidents.*", "dashboard.*" or "performance.*" as
appropriate, and ensure translation lookups (e.g., calls reading these JSON
keys) are updated to the new semantic keys.

"Cohere": "Cohere",
"Collapse": "Collapse",
"Collapse All": "Collapse All",
"Collect relay latency and success-rate metrics for the model square.": "Collect relay latency and success-rate metrics for the model square.",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Capitalize product name in user-facing copy

The sentence uses model square in lowercase; this should be Model Square for product-name consistency.

✏️ Proposed text fix
-    "Collect relay latency and success-rate metrics for the model square.": "Collect relay latency and success-rate metrics for the model square.",
+    "Collect relay latency and success-rate metrics for the Model Square.": "Collect relay latency and success-rate metrics for the Model Square.",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"Collect relay latency and success-rate metrics for the model square.": "Collect relay latency and success-rate metrics for the model square.",
"Collect relay latency and success-rate metrics for the Model Square.": "Collect relay latency and success-rate metrics for the Model Square.",
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/i18n/locales/en.json` at line 724, Update the user-facing
string that currently reads "Collect relay latency and success-rate metrics for
the model square." to use the product name capitalized: "Collect relay latency
and success-rate metrics for the Model Square." Locate and edit the matching
JSON entry where the key/value contains "Collect relay latency and success-rate
metrics for the model square." and replace the lowercase "model square" with
"Model Square" so both key and value reflect the corrected product-name
capitalization.

"Fixed price (USD)": "Фиксированная цена (USD)",
"Floating": "Плавающая",
"FluentRead extension not detected. Please ensure it is installed and active.": "Расширение FluentRead не обнаружено. Убедитесь, что оно установлено и активно.",
"Flush interval (minutes)": "Интервал записи (минуты)",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Adjust wording of “Flush interval” translation for technical accuracy.

At Line 1675, "Интервал записи" reads as write interval; for flush/drain semantics, "Интервал сброса" (or "Интервал выгрузки") is clearer.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/i18n/locales/ru.json` at line 1675, The translation for the
key "Flush interval (minutes)" uses "Интервал записи" which implies a write
interval; update the value in ru.json for the string "Flush interval (minutes)"
to a more accurate term like "Интервал сброса (минуты)" or "Интервал выгрузки
(минуты)" to reflect flush/drain semantics while preserving the original key
exactly.

"Aggregated traffic by upstream model provider": "Lưu lượng tổng hợp theo nhà cung cấp mô hình",
"Aggregated usage metrics and trend charts.": "Chỉ số sử dụng tổng hợp và biểu đồ xu hướng.",
"aggregates 50+ AI providers behind one unified API. Manage access, track costs, and scale effortlessly.": "tổng hợp hơn 50 nhà cung cấp AI sau một API thống nhất. Quản lý truy cập, theo dõi chi phí và mở rộng dễ dàng.",
"Aggregation bucket": "Khoảng tổng hợp",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift

Use hierarchical i18n keys for newly introduced metrics strings

These newly added keys continue the raw-English-sentence key pattern instead of hierarchical semantic keys (e.g., performance.metrics.successRate). Please align new entries to hierarchical naming and keep naming consistent across locales/components for this feature slice.

As per coding guidelines, web/default/src/i18n/**/*.{ts,tsx,json}: Use hierarchical and semantically clear translation key names such as dashboard.overview.title and maintain naming consistency.

Also applies to: 432-443, 724-724, 1309-1309, 1675-1675, 2238-2238, 3125-3126, 3175-3175, 3549-3549

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/i18n/locales/vi.json` at line 226, The translation key
"Aggregation bucket" in vi.json uses a raw English sentence key; rename it to a
hierarchical semantic key (e.g., performance.metrics.aggregationBucket) and
update the corresponding key in all other locale files and components that
reference the old key (see other affected ranges noted) so lookups use
performance.metrics.aggregationBucket instead of "Aggregation bucket"; ensure
you adjust any code that calls the string (e.g., components or hooks that
reference "Aggregation bucket") to the new hierarchical key and keep the same
Vietnamese value.

@Calcium-Ion
Calcium-Ion force-pushed the cursor/model-performance-metrics branch from 4038ed8 to 5dd413a Compare May 6, 2026 05:47
@Calcium-Ion
Calcium-Ion marked this pull request as ready for review May 6, 2026 05:47
@Calcium-Ion
Calcium-Ion merged commit 9acf5fe into main May 6, 2026
Jinxuans referenced this pull request in TokFlux-Org/TokFlux May 9, 2026
@Calcium-Ion
Calcium-Ion deleted the cursor/model-performance-metrics branch May 12, 2026 08:45
xyfacai pushed a commit to xyfacai/new-api that referenced this pull request May 30, 2026
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
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.

1 participant