Repository navigation
fix: channel affinity - #2799
Conversation
WalkthroughAdds 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (2 warnings, 1 inconclusive)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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.
| 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}`; | ||
|
|
There was a problem hiding this comment.
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.
| 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.
There was a problem hiding this comment.
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 betweenGetandSetWithTTL, 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.
| 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:] | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 unusedasynckeyword.The function is marked
asyncbut doesn't useawait. SinceFileReaderis callback-based (not Promise-based), theasynckeyword has no effect here.♻️ Suggested change
const handlePaste = useCallback( - async (e) => { + (e) => { const items = e.clipboardData?.items;
41-41: UsestartsWithfor cleaner MIME type checking.Using
startsWith('image/')is more precise and idiomatic for MIME type validation thanindexOf.♻️ 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: AddrowKeyprop to Table for proper row identification.The Table is missing a
rowKeyprop. 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 redundantdefaultValueon controlled InputNumber.This
InputNumberis controlled via thevalueprop, sodefaultValue={4.49}has no effect after initial render. The initial value is actually0fromproductFormstate. 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 CSSwhite-spacepreservation.💡 Optional refactor if a true line break is intended
{t('价格')}:{selectedCreemProduct.currency === 'EUR' ? '€' : '$'} + <br /> {selectedCreemProduct.price}
| const { content: htmlContent, styles } = sanitizeHtml(content); | ||
|
|
||
| // 设置样式(如果有的话) | ||
| useEffect(() => { | ||
| if (styles && styles !== htmlStyles) { | ||
| setHtmlStyles(styles); | ||
| } | ||
| }, [content, styles, htmlStyles]); | ||
|
|
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
wc -l web/src/components/common/DocumentRenderer/index.jsxRepository: QuantumNous/new-api
Length of output: 119
🏁 Script executed:
sed -n '190,230p' web/src/components/common/DocumentRenderer/index.jsxRepository: QuantumNous/new-api
Length of output: 1336
🏁 Script executed:
cat -n web/src/components/common/DocumentRenderer/index.jsx | head -250 | tail -100Repository: QuantumNous/new-api
Length of output: 3618
🏁 Script executed:
rg -n "use[A-Z]" web/src/components/common/DocumentRenderer/index.jsxRepository: QuantumNous/new-api
Length of output: 509
🏁 Script executed:
sed -n '1,160p' web/src/components/common/DocumentRenderer/index.jsx | head -60Repository: QuantumNous/new-api
Length of output: 1846
🏁 Script executed:
sed -n '70,155p' web/src/components/common/DocumentRenderer/index.jsxRepository: QuantumNous/new-api
Length of output: 2374
🏁 Script executed:
rg -n "htmlStyles" web/src/components/common/DocumentRenderer/index.jsxRepository: 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.
| 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.
| <div | ||
| className='prose prose-lg max-w-none' | ||
| dangerouslySetInnerHTML={{ __html: htmlContent }} | ||
| /> |
There was a problem hiding this comment.
🧩 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 -100Repository: 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 20Repository: 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.jsxRepository: 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 -20Repository: 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 -40Repository: 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 5Repository: 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 -20Repository: 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.
| 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); | ||
| } |
There was a problem hiding this comment.
🧩 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
returninfinallyoverrides areturnintry/catch. [1]returninfinallyalso overrides a pendingthrow(the exception will not propagate). [1]
Examples
function a() {
try { return 1; }
finally { return 2; }
}
a(); // 2Because 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:
- 1: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/try...catch?utm_source=openai
🌐 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 1What to do instead:
- Don’t
returnfromfinally; usefinallyonly 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:
- 1: https://eslint.org/docs/latest/rules/no-unsafe-finally?utm_source=openai
- 2: https://eslint.org/docs/latest/rules/no-unsafe-finally?utm_source=openai
- 3: https://eslint.org/docs/latest/rules/no-unsafe-finally?utm_source=openai
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.
* 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
* 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
* 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
* 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
fix #2789 #2790

支持对单规则设置失败后跳过重试,默认关闭
日志优选弹出层增加查看详情,可查看该key下的对话的缓存命中率,例如codex。
Summary by CodeRabbit
New Features
UI
Bug Fixes
Refactor