Skip to content

fix: channel affinity - #2799

Merged
Calcium-Ion merged 8 commits into
QuantumNous:mainfrom
seefs001:fix/channel-affinity
Feb 2, 2026
Merged

Calcium-Ion merged 8 commits into
QuantumNous:mainfrom
seefs001:fix/channel-affinity

Conversation

@seefs001

@seefs001 seefs001 commented Feb 1, 2026 •

Copy link
Copy Markdown
Collaborator

fix #2789 #2790
支持对单规则设置失败后跳过重试,默认关闭
日志优选弹出层增加查看详情,可查看该key下的对话的缓存命中率,例如codex。
image

Summary by CodeRabbit

  • New Features

    • Admin modal to view channel affinity usage statistics from logs.
    • New rule option to skip retry on failure in channel affinity rules.
  • UI

    • Enhanced affinity tooltip in usage logs with a “查看详情” button to open the new modal.
  • Bug Fixes

    • Prevents retry attempts when channel-affinity failure conditions apply.
  • Refactor

    • Collection and reporting of channel-affinity usage metrics improved.

@coderabbitai

coderabbitai Bot commented Feb 1, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a channel-affinity usage stats subsystem (service types, in-memory cache, observation APIs, lock/keys), server endpoints and controller, integrates observation and skip-retry guards in relay paths, extends backend rule schema with skip_retry, and adds an admin-facing modal and table UI to view per-affinity cache stats.

Changes

Cohort / File(s) Summary
Service: channel affinity core
service/channel_affinity.go
New types, cache store, per-entry locks, stats aggregation/observation functions, GetChannelAffinityUsageCacheStats accessor, ShouldSkipRetryAfterChannelAffinityFailure, KeyHint/SkipRetry propagation and helpers.
Controller & Router
controller/channel_affinity_cache.go, router/api-router.go
New handler GetChannelAffinityUsageCacheStats and registered GET /api/log/channel_affinity_usage_cache (AdminAuth).
Relay / Quota integration
controller/relay.go, relay/compatible_handler.go
Guard added to skip retry when channel-affinity SkipRetry set; postConsumeQuota observes usage into stats cache.
Backend setting struct
setting/operation_setting/channel_affinity_setting.go
Added SkipRetryOnFailure bool field to ChannelAffinityRule.
Frontend: usage-logs UI & modal
web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx, web/src/components/table/usage-logs/UsageLogsTable.jsx, web/src/components/table/usage-logs/index.jsx, web/src/components/table/usage-logs/modals/ChannelAffinityUsageCacheModal.jsx, web/src/hooks/usage-logs/useUsageLogsData.jsx
Added buildChannelAffinityTooltip, Button to open ChannelAffinityUsageCacheModal, threaded openChannelAffinityUsageCacheModal through hook→table→modal; new modal fetches /api/log/channel_affinity_usage_cache and renders stats with loading/error states.
Frontend: settings editor
web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx
Added skip_retry_on_failure to templates, JSON placeholder, modal form values, save payload and UI switch; updated normalizeKeySource to clear/preserve key/path depending on gjson source.
Integration & wiring
web/src/components/table/usage-logs/*, web/src/hooks/usage-logs/*, controller/..., main.go, minor web files
Prop propagation (openChannelAffinityUsageCacheModal), useMemo deps, imports, small formatting and UI placement tweaks; misc small controller formatting fixes.

Sequence Diagram(s)

sequenceDiagram
    participant AdminUI as Admin UI (Modal)
    participant Frontend as Frontend Hook/Table
    participant API as HTTP API (/api/log/channel_affinity_usage_cache)
    participant Controller as Controller.GetChannelAffinityUsageCacheStats
    participant Service as service.GetChannelAffinityUsageCacheStats
    participant Cache as channelAffinityUsageCacheStatsCache

    AdminUI->>Frontend: openChannelAffinityUsageCacheModal(affinity)
    Frontend->>API: GET /api/log/channel_affinity_usage_cache?rule_name&key_fp&using_group
    API->>Controller: HTTP request
    Controller->>Service: GetChannelAffinityUsageCacheStats(params)
    Service->>Cache: lookup stats by entry key
    Cache-->>Service: return counters/stats
    Service-->>Controller: ChannelAffinityUsageCacheStats
    Controller-->>API: 200 JSON(stats)
    API-->>Frontend: JSON(stats)
    Frontend->>AdminUI: render stats in modal
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • fix: merge conflict #1955 — Modifies web/src/components/table/channels/modals/EditChannelModal.jsx, overlapping UI modal/button placement changes.
  • feat: channel affinity #2669 — Related channel-affinity subsystem and admin tooling changes (service/controller/ui) that likely overlap in cache/handler/endpoint logic.

Suggested reviewers

  • Calcium-Ion
  • creamlike1024

Poem

🐰 I nibble logs beneath the moon,

Tokens counted, numbers tune,
A tiny button, "查看详情" to peep,
Cache and hints awake from sleep.
Hops of code — the stats I keep.

🚥 Pre-merge checks | ✅ 2 | ❌ 3
❌ Failed checks (2 warnings, 1 inconclusive)
Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning PR contains significant out-of-scope changes including new channel affinity usage cache stats features, UI/modal components, API endpoints, and extensive formatting changes unrelated to issue #2789. Remove out-of-scope changes: ChannelAffinityUsageCacheModal, usage cache stats logic in service/channel_affinity.go, API endpoints, and skip_retry_on_failure feature. Keep only the gjson path clearing fix from SettingsChannelAffinity.jsx.
Docstring Coverage ⚠️ Warning Docstring coverage is 9.80% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'fix: channel affinity' is vague and lacks specificity about which aspect of channel affinity is being fixed. Consider using a more descriptive title that specifies the fix, such as 'fix: clear gjson path when rule type changes in channel affinity' to better convey the main change.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed The PR addresses issue #2789 by fixing the frontend logic in SettingsChannelAffinity.jsx to clear the path field when rule type changes from gjson to another type.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

🤖 Fix all issues with AI agents
In `@web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx`:
- Around line 79-83: The tooltip construction uses affinity.key_path or
affinity.key_key but misses normalized non-gjson keys stored in affinity.key, so
update the fallback for keyPath to check affinity.key_path || affinity.key_key
|| affinity.key before falling back to '-' (i.e., change the keyPath resolution
used in keyPath and consequently keyText); preserve existing keySource and keyFp
logic (keySource, keyFp, keyText) but include affinity.key as an additional
candidate when resolving keyPath to ensure the tooltip shows the actual key for
non-gjson sources.

Comment on lines +79 to +83
const keySource = affinity.key_source || '-';
const keyPath = affinity.key_path || affinity.key_key || '-';
const keyFp = affinity.key_fp ? `#${affinity.key_fp}` : '';
const keyText = `${keySource}:${keyPath}${keyFp}`;

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

Tooltip may hide non‑gjson keys after key-source normalization.

Line 80 only checks key_path / key_key. With the new normalization, non‑gjson sources keep the key in affinity.key, so the tooltip could show - for context keys. Consider falling back to affinity.key.

Proposed fix
-  const keyPath = affinity.key_path || affinity.key_key || '-';
+  const keyPath =
+    affinity.key_path || affinity.key || affinity.key_key || '-';
📝 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
const keySource = affinity.key_source || '-';
const keyPath = affinity.key_path || affinity.key_key || '-';
const keyFp = affinity.key_fp ? `#${affinity.key_fp}` : '';
const keyText = `${keySource}:${keyPath}${keyFp}`;
const keySource = affinity.key_source || '-';
const keyPath =
affinity.key_path || affinity.key || affinity.key_key || '-';
const keyFp = affinity.key_fp ? `#${affinity.key_fp}` : '';
const keyText = `${keySource}:${keyPath}${keyFp}`;
🤖 Prompt for AI Agents
In `@web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx` around lines 79
- 83, The tooltip construction uses affinity.key_path or affinity.key_key but
misses normalized non-gjson keys stored in affinity.key, so update the fallback
for keyPath to check affinity.key_path || affinity.key_key || affinity.key
before falling back to '-' (i.e., change the keyPath resolution used in keyPath
and consequently keyText); preserve existing keySource and keyFp logic
(keySource, keyFp, keyText) but include affinity.key as an additional candidate
when resolving keyPath to ensure the tooltip shows the actual key for non-gjson
sources.

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

🤖 Fix all issues with AI agents
In `@service/channel_affinity.go`:
- Around line 394-405: The function buildChannelAffinityKeyHint currently slices
the string by bytes (s[:4], s[len(s)-4:]) which can break UTF-8 for multi-byte
characters; change the logic to operate on runes: after trimming and normalizing
whitespace, convert s to a rune slice (runes := []rune(s)), use rune length
checks (e.g., if len(runes) <= 12 return s), and construct the hint using
rune-safe slices (string(runes[:4]) + "..." + string(runes[len(runes)-4:])) so
the returned hint is always valid UTF-8 and preserves full characters.

In
`@web/src/components/table/usage-logs/modals/ChannelAffinityUsageCacheModal.jsx`:
- Around line 61-93: The effect in useEffect is re-triggering due to including
loading in its dependency array and using !loading in the shouldFetch guard;
update the effect so it only depends on showChannelAffinityUsageCacheModal,
params, and t (remove loading from the dependencies) and remove the !loading
check from the shouldFetch condition; keep the existing cancelled flag, await
API.get('/api/log/channel_affinity_usage_cache') logic, and setLoading/setStats
handling unchanged so fetch runs only when modal visibility or params change.
🧹 Nitpick comments (1)
service/channel_affinity.go (1)

656-680: Potential race condition when Redis is enabled.

The striped locking protects in-memory operations, but when Redis is enabled in HybridCache, concurrent instances may race between Get and SetWithTTL, potentially causing lost counter increments.

For usage statistics (non-critical observability data), this is acceptable, but be aware counters may undercount under high concurrency across multiple instances.

Comment on lines +394 to +405
func buildChannelAffinityKeyHint(s string) string {
s = strings.TrimSpace(s)
if s == "" {
return ""
}
s = strings.ReplaceAll(s, "\n", " ")
s = strings.ReplaceAll(s, "\r", " ")
if len(s) <= 12 {
return s
}
return s[:4] + "..." + s[len(s)-4:]
}

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

Potential invalid UTF-8 when truncating multi-byte strings.

s[:4] and s[len(s)-4:] slice by bytes, not runes. For non-ASCII input (e.g., Chinese characters), this could produce invalid UTF-8 sequences in the hint.

🛠️ Proposed fix using rune-safe slicing
 func buildChannelAffinityKeyHint(s string) string {
 	s = strings.TrimSpace(s)
 	if s == "" {
 		return ""
 	}
 	s = strings.ReplaceAll(s, "\n", " ")
 	s = strings.ReplaceAll(s, "\r", " ")
-	if len(s) <= 12 {
+	runes := []rune(s)
+	if len(runes) <= 12 {
 		return s
 	}
-	return s[:4] + "..." + s[len(s)-4:]
+	return string(runes[:4]) + "..." + string(runes[len(runes)-4:])
 }
🤖 Prompt for AI Agents
In `@service/channel_affinity.go` around lines 394 - 405, The function
buildChannelAffinityKeyHint currently slices the string by bytes (s[:4],
s[len(s)-4:]) which can break UTF-8 for multi-byte characters; change the logic
to operate on runes: after trimming and normalizing whitespace, convert s to a
rune slice (runes := []rune(s)), use rune length checks (e.g., if len(runes) <=
12 return s), and construct the hint using rune-safe slices (string(runes[:4]) +
"..." + string(runes[len(runes)-4:])) so the returned hint is always valid UTF-8
and preserves full characters.

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

🤖 Fix all issues with AI agents
In `@web/src/components/common/DocumentRenderer/index.jsx`:
- Around line 210-218: The conditional useEffect that runs when
isHtmlContent(content) is true should be removed because hooks must be called
unconditionally; instead rely on processContent() to call setHtmlStyles() and
the existing unconditional useEffect that watches htmlStyles to inject styles.
Delete the conditional useEffect block that uses sanitizeHtml(content) and
setHtmlStyles, ensure processContent() continues to call setHtmlStyles(html)
when isHtmlContent(content) is true, and keep the unconditional useEffect (the
one with htmlStyles in its dependency array) to handle style injection.
- Around line 226-229: The component is assigning untrusted API HTML to
htmlContent and rendering it with dangerouslySetInnerHTML (DocumentRenderer);
update the sanitation pipeline so that the output of sanitizeHtml (or the raw
API string) is passed through a proper sanitizer such as DOMPurify before
assigning htmlContent. Import DOMPurify, call DOMPurify.sanitize(...) with an
appropriate config (e.g., disallow scripts, event handlers, and unsafe tags)
inside the sanitizeHtml function or just prior to setting htmlContent, and
ensure the component uses that sanitized string when rendering with
dangerouslySetInnerHTML to prevent script/event handler injection.

In
`@web/src/components/table/usage-logs/modals/ChannelAffinityUsageCacheModal.jsx`:
- Around line 62-99: The issue is that the anonymous async useEffect handler
uses "if (reqSeq !== requestSeqRef.current) return;" inside the finally block
which violates no-unsafe-finally; update the finally block in the useEffect
async function (the closure using reqSeq, requestSeqRef, setLoading, setStats)
to remove any return statements and instead conditionally perform side-effects:
check "if (reqSeq === requestSeqRef.current)" and only then call
setLoading(false) (and any other state updates), so earlier return paths in
try/catch still exit the handler while the finally block only executes
non-control-flow guarded updates when the request is still current.
🧹 Nitpick comments (7)
web/src/pages/Setting/Model/SettingModelDeployment.jsx (1)

239-239: Quote style changed from double to single quotes.

The JSX string attributes were changed from double quotes ("outline") to single quotes ('outline'). Both are valid in JSX, but ensure this aligns with the project's style guide or linter configuration for consistency across the codebase.

Also applies to: 243-244, 309-310, 324-324

web/src/components/playground/CustomInputRender.jsx (2)

33-34: Consider removing unused async keyword.

The function is marked async but doesn't use await. Since FileReader is callback-based (not Promise-based), the async keyword has no effect here.

♻️ Suggested change
  const handlePaste = useCallback(
-    async (e) => {
+    (e) => {
      const items = e.clipboardData?.items;

41-41: Use startsWith for cleaner MIME type checking.

Using startsWith('image/') is more precise and idiomatic for MIME type validation than indexOf.

♻️ Suggested change
-        if (item.type.indexOf('image') !== -1) {
+        if (item.type.startsWith('image/')) {
web/src/pages/Setting/Payment/SettingsPaymentGatewayCreem.jsx (3)

92-101: Simplify redundant truthy checks.

The conditions inputs.CreemApiKey && inputs.CreemApiKey !== '' are redundant—if a string is truthy, it's already non-empty.

♻️ Suggested simplification
-      if (inputs.CreemApiKey && inputs.CreemApiKey !== '') {
+      if (inputs.CreemApiKey) {
         options.push({ key: 'CreemApiKey', value: inputs.CreemApiKey });
       }
 
-      if (inputs.CreemWebhookSecret && inputs.CreemWebhookSecret !== '') {
+      if (inputs.CreemWebhookSecret) {
         options.push({
           key: 'CreemWebhookSecret',
           value: inputs.CreemWebhookSecret,
         });
       }

312-321: Add rowKey prop to Table for proper row identification.

The Table is missing a rowKey prop. Without it, React may produce console warnings and experience suboptimal reconciliation when rows are added, removed, or reordered.

♻️ Proposed fix
             <Table
               columns={columns}
               dataSource={products}
               pagination={false}
+              rowKey="productId"
               empty={
                 <div className='text-center py-8'>
                   <Text type='tertiary'>{t('暂无产品配置')}</Text>
                 </div>
               }
             />

389-400: Remove redundant defaultValue on controlled InputNumber.

This InputNumber is controlled via the value prop, so defaultValue={4.49} has no effect after initial render. The initial value is actually 0 from productForm state. This is misleading and should be removed.

♻️ Proposed fix
             <InputNumber
               value={productForm.price}
               onChange={(value) =>
                 setProductForm({ ...productForm, price: value })
               }
               placeholder={t('例如:4.99')}
               min={0.01}
               precision={2}
               size='large'
               className='w-full'
-              defaultValue={4.49}
             />
web/src/components/topup/index.jsx (1)

654-655: Confirm intent: JSX newline will collapse to space; add <br /> if line break is desired.

At lines 654–655, the newline between the currency expression and price will collapse during JSX compilation per whitespace normalization rules. If a visual line break is intended, add <br /> or use CSS white-space preservation.

💡 Optional refactor if a true line break is intended
              {t('价格')}:{selectedCreemProduct.currency === 'EUR' ? '€' : '$'}
+             <br />
              {selectedCreemProduct.price}

Comment on lines 210 to +218
const { content: htmlContent, styles } = sanitizeHtml(content);

// 设置样式(如果有的话)
useEffect(() => {
if (styles && styles !== htmlStyles) {
setHtmlStyles(styles);
}
}, [content, styles, htmlStyles]);

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

🧩 Analysis chain

🏁 Script executed:

wc -l web/src/components/common/DocumentRenderer/index.jsx

Repository: QuantumNous/new-api

Length of output: 119


🏁 Script executed:

sed -n '190,230p' web/src/components/common/DocumentRenderer/index.jsx

Repository: QuantumNous/new-api

Length of output: 1336


🏁 Script executed:

cat -n web/src/components/common/DocumentRenderer/index.jsx | head -250 | tail -100

Repository: QuantumNous/new-api

Length of output: 3618


🏁 Script executed:

rg -n "use[A-Z]" web/src/components/common/DocumentRenderer/index.jsx

Repository: QuantumNous/new-api

Length of output: 509


🏁 Script executed:

sed -n '1,160p' web/src/components/common/DocumentRenderer/index.jsx | head -60

Repository: QuantumNous/new-api

Length of output: 1846


🏁 Script executed:

sed -n '70,155p' web/src/components/common/DocumentRenderer/index.jsx

Repository: QuantumNous/new-api

Length of output: 2374


🏁 Script executed:

rg -n "htmlStyles" web/src/components/common/DocumentRenderer/index.jsx

Repository: QuantumNous/new-api

Length of output: 311


Remove the conditional useEffect hook (Rules of Hooks violation).

Line 213 calls useEffect inside the if (isHtmlContent(content)) branch, which violates React's Rules of Hooks. When content toggles between HTML and non-HTML formats, this breaks hook ordering.

The hook is also redundant—processContent() already handles HTML detection and updates htmlStyles via setHtmlStyles(). The existing unconditional useEffect at line 130 (with htmlStyles in its dependency array) is designed to handle style injection whenever styles change. Remove the conditional hook:

Suggested fix
  if (isHtmlContent(content)) {
-   const { content: htmlContent, styles } = sanitizeHtml(content);
-
-   // 设置样式(如果有的话)
-   useEffect(() => {
-     if (styles && styles !== htmlStyles) {
-       setHtmlStyles(styles);
-     }
-   }, [content, styles, htmlStyles]);
+   const { content: htmlContent } = sanitizeHtml(content);

    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
const { content: htmlContent, styles } = sanitizeHtml(content);
// 设置样式(如果有的话)
useEffect(() => {
if (styles && styles !== htmlStyles) {
setHtmlStyles(styles);
}
}, [content, styles, htmlStyles]);
const { content: htmlContent } = sanitizeHtml(content);
🤖 Prompt for AI Agents
In `@web/src/components/common/DocumentRenderer/index.jsx` around lines 210 - 218,
The conditional useEffect that runs when isHtmlContent(content) is true should
be removed because hooks must be called unconditionally; instead rely on
processContent() to call setHtmlStyles() and the existing unconditional
useEffect that watches htmlStyles to inject styles. Delete the conditional
useEffect block that uses sanitizeHtml(content) and setHtmlStyles, ensure
processContent() continues to call setHtmlStyles(html) when
isHtmlContent(content) is true, and keep the unconditional useEffect (the one
with htmlStyles in its dependency array) to handle style injection.

Comment on lines +226 to 229
<div
className='prose prose-lg max-w-none'
dangerouslySetInnerHTML={{ __html: htmlContent }}
/>

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

🧩 Analysis chain

🏁 Script executed:

# First, let's look at the file structure and locate the component
fd -e jsx -e js | grep -i "DocumentRenderer"

Repository: QuantumNous/new-api

Length of output: 115


🏁 Script executed:

# Now let's examine the content around the flagged lines
cat -n web/src/components/common/DocumentRenderer/index.jsx | head -250 | tail -100

Repository: QuantumNous/new-api

Length of output: 3618


🏁 Script executed:

# Let's also search for the sanitizeHtml function definition in this file
rg "const sanitizeHtml|function sanitizeHtml" web/src/components/common/DocumentRenderer/index.jsx -A 20

Repository: QuantumNous/new-api

Length of output: 594


🏁 Script executed:

# Look at the beginning of the file to see imports and the full sanitizeHtml function
head -100 web/src/components/common/DocumentRenderer/index.jsx

Repository: QuantumNous/new-api

Length of output: 3107


🏁 Script executed:

# Search for any CSP or security headers in the codebase
rg "Content-Security-Policy|csp" web/src/ --type jsx --type js -i | head -20

Repository: QuantumNous/new-api

Length of output: 90


🏁 Script executed:

# Search for where the API data is fetched from
rg "fetch|axios|api" web/src/components/common/DocumentRenderer/index.jsx -i -A 3 | head -40

Repository: QuantumNous/new-api

Length of output: 743


🏁 Script executed:

# Check if there's any validation on the API data before rendering
rg "isHtmlContent" web/src/components/common/DocumentRenderer/index.jsx -B 5 -A 5

Repository: QuantumNous/new-api

Length of output: 855


🏁 Script executed:

# Search for any DOMPurify or similar sanitization library already in the project
rg "DOMPurify|sanitize|xss" web/src/ --type js -l | head -20

Repository: QuantumNous/new-api

Length of output: 224


Sanitize HTML before dangerouslySetInnerHTML.

The sanitizeHtml function does not sanitize; it only parses and extracts HTML. Line 54 directly assigns untrusted API content to innerHTML, and the result is rendered via dangerouslySetInnerHTML on line 228. This allows script execution and event handlers from the API response.

Use DOMPurify to remove dangerous content:

🛡️ Example hardening with DOMPurify
-import React, { useEffect, useState } from 'react';
+import React, { useEffect, useState } from 'react';
+import DOMPurify from 'dompurify';

 const sanitizeHtml = (html) => {
+  const safeHtml = DOMPurify.sanitize(html, { ADD_TAGS: ['style'], ADD_ATTR: ['style'] });
   // 创建一个临时元素来解析HTML
   const tempDiv = document.createElement('div');
-  tempDiv.innerHTML = html;
+  tempDiv.innerHTML = safeHtml;

   // 提取样式
   const styles = Array.from(tempDiv.querySelectorAll('style'))
     .map((style) => style.innerHTML)
     .join('\n');

   // 提取body内容,如果没有body标签则使用全部内容
   const bodyContent = tempDiv.querySelector('body');
-  const content = bodyContent ? bodyContent.innerHTML : html;
+  const content = bodyContent ? bodyContent.innerHTML : safeHtml;

   return { content, styles };
 };
🤖 Prompt for AI Agents
In `@web/src/components/common/DocumentRenderer/index.jsx` around lines 226 - 229,
The component is assigning untrusted API HTML to htmlContent and rendering it
with dangerouslySetInnerHTML (DocumentRenderer); update the sanitation pipeline
so that the output of sanitizeHtml (or the raw API string) is passed through a
proper sanitizer such as DOMPurify before assigning htmlContent. Import
DOMPurify, call DOMPurify.sanitize(...) with an appropriate config (e.g.,
disallow scripts, event handlers, and unsafe tags) inside the sanitizeHtml
function or just prior to setting htmlContent, and ensure the component uses
that sanitized string when rendering with dangerouslySetInnerHTML to prevent
script/event handler injection.

Comment on lines +62 to +99
useEffect(() => {
if (!showChannelAffinityUsageCacheModal) {
requestSeqRef.current += 1; // invalidate inflight request
setLoading(false);
setStats(null);
return;
}
if (!params.rule_name || !params.key_fp) {
setLoading(false);
setStats(null);
return;
}

const reqSeq = (requestSeqRef.current += 1);
setStats(null);
setLoading(true);
(async () => {
try {
const res = await API.get('/api/log/channel_affinity_usage_cache', {
params,
disableDuplicate: true,
});
if (reqSeq !== requestSeqRef.current) return;
const { success, message, data } = res.data || {};
if (!success) {
setStats(null);
showError(t(message || '请求失败'));
return;
}
setStats(data || {});
} catch (e) {
if (reqSeq !== requestSeqRef.current) return;
setStats(null);
showError(t('请求失败'));
} finally {
if (reqSeq !== requestSeqRef.current) return;
setLoading(false);
}

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

🧩 Analysis chain

🌐 Web query:

JavaScript return inside finally block override try catch throw

💡 Result:

In JavaScript, the finally block always runs before control leaves a try/catch construct—even if the try/catch is about to return or throw. If finally itself executes a control-flow statement (return, throw, break, continue), it “masks” (overrides) whatever the try/catch was going to do. [1]

What “override” means

  • return in finally overrides a return in try/catch. [1]
  • return in finally also overrides a pending throw (the exception will not propagate). [1]

Examples

function a() {
  try { return 1; }
  finally { return 2; }
}
a(); // 2

Because the finally return becomes the whole statement’s return value. [1]

function b() {
  try { throw new Error("boom"); }
  finally { return 123; }
}
b(); // 123 (no exception thrown)

The throw is masked by the return in finally. [1]

Practical rule: use finally for cleanup, and avoid return/throw inside it unless you intentionally want to override earlier returns/errors. [1]

Sources: MDN try...catch...finally docs (see “The finally block” and “Returning from a finally block”). [1]

[1] (developer.mozilla.org)

Citations:


🌐 Web query:

ESLint no-unsafe-finally rule return in finally

💡 Result:

ESLint’s no-unsafe-finally rule flags return (and also throw, break, continue) inside a finally block because it can override whatever control flow was supposed to happen from the try/catch (including overriding a prior return or even swallowing an exception). (eslint.org)

Example (unsafe):

function f() {
  try {
    return 1;
  } finally {
    return 3; // ESLint: no-unsafe-finally
  }
}
// f() returns 3, not 1

What to do instead:

  • Don’t return from finally; use finally only for cleanup (close handles, reset state, etc.). (eslint.org)
  • Put the return after the try/finally:
function f() {
  let result;
  try {
    result = 1;
  } finally {
    cleanup();
  }
  return result;
}

The rule allows indirect returns inside nested function/class definitions within finally (because that’s not a control-flow statement of the finally block itself). (eslint.org)

Citations:


Avoid return inside finally to prevent control-flow override.

At lines 96–99, the return statement inside the finally block can override prior returns from try/catch, which is flagged by the ESLint no-unsafe-finally rule. Use a conditional instead:

Suggested fix
      } finally {
-       if (reqSeq !== requestSeqRef.current) return;
+       if (reqSeq === requestSeqRef.current) {
+         setLoading(false);
+       }
      }
🧰 Tools
🪛 Biome (2.3.13)

[error] 98-98: Unsafe usage of 'return'.

'return' in 'finally' overwrites the control flow statements inside 'try' and 'catch'.

(lint/correctness/noUnsafeFinally)

🤖 Prompt for AI Agents
In
`@web/src/components/table/usage-logs/modals/ChannelAffinityUsageCacheModal.jsx`
around lines 62 - 99, The issue is that the anonymous async useEffect handler
uses "if (reqSeq !== requestSeqRef.current) return;" inside the finally block
which violates no-unsafe-finally; update the finally block in the useEffect
async function (the closure using reqSeq, requestSeqRef, setLoading, setStats)
to remove any return statements and instead conditionally perform side-effects:
check "if (reqSeq === requestSeqRef.current)" and only then call
setLoading(false) (and any other state updates), so earlier return paths in
try/catch still exit the handler while the finally block only executes
non-control-flow guarded updates when the request is still current.

@Calcium-Ion
Calcium-Ion merged commit 540cf6c into QuantumNous:main Feb 2, 2026
dreamlx pushed a commit to dreamlx/new-api that referenced this pull request Mar 3, 2026
* fix: channel affinity log styles

* fix: Issue with incorrect data storage when switching key sources

* feat: support not retrying after a single rule configuration fails

* fix: render channel affinity tooltip as multiline content

* feat: channel affinity cache hit

* fix: prevent ChannelAffinityUsageCacheModal infinite loading and hide data before fetch

* chore: format backend with gofmt and frontend with prettier/eslint autofix
ennnnny pushed a commit to ennnnny/new-api that referenced this pull request Mar 17, 2026
* fix: channel affinity log styles

* fix: Issue with incorrect data storage when switching key sources

* feat: support not retrying after a single rule configuration fails

* fix: render channel affinity tooltip as multiline content

* feat: channel affinity cache hit

* fix: prevent ChannelAffinityUsageCacheModal infinite loading and hide data before fetch

* chore: format backend with gofmt and frontend with prettier/eslint autofix
@coderabbitai coderabbitai Bot mentioned this pull request Apr 7, 2026
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
* fix: channel affinity log styles

* fix: Issue with incorrect data storage when switching key sources

* feat: support not retrying after a single rule configuration fails

* fix: render channel affinity tooltip as multiline content

* feat: channel affinity cache hit

* fix: prevent ChannelAffinityUsageCacheModal infinite loading and hide data before fetch

* chore: format backend with gofmt and frontend with prettier/eslint autofix
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
* fix: channel affinity log styles

* fix: Issue with incorrect data storage when switching key sources

* feat: support not retrying after a single rule configuration fails

* fix: render channel affinity tooltip as multiline content

* feat: channel affinity cache hit

* fix: prevent ChannelAffinityUsageCacheModal infinite loading and hide data before fetch

* chore: format backend with gofmt and frontend with prettier/eslint autofix
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.

渠道亲和性 UI 不清晰,看不清文字 渠道亲和性设置前端逻辑问题

2 participants