Repository navigation
feat: channel affinity - #2669
Conversation
WalkthroughAdds a channel-affinity subsystem (settings, rule matching, hybrid Redis/in-memory cache), integrates affinity-aware channel selection in middleware, records and exposes cache stats via new endpoints, augments admin logs with affinity info, updates policy signatures to include channelType, and adds frontend UI and styles for managing affinity rules. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Distributor
participant AffinityService
participant AffinityCache
participant ModelLayer
participant Downstream
Client->>Distributor: request (model, usingGroup, ctx)
Distributor->>AffinityService: GetPreferredChannelByAffinity(ctx, model, usingGroup)
AffinityService->>AffinityCache: Get(cacheKey)
AffinityCache-->>AffinityService: channelID or miss
alt channelID found
AffinityService->>ModelLayer: IsChannelEnabledForGroupModel(selectedGroup, model, channelID)
ModelLayer-->>AffinityService: allowed / denied
alt allowed
AffinityService-->>Distributor: preferred channelID
Distributor->>Downstream: bind channel & c.Next()
else denied
Distributor->>Distributor: fallback selection (random)
Distributor->>Downstream: bind fallback & c.Next()
end
else miss
Distributor->>Distributor: fallback selection (random)
Distributor->>Downstream: bind fallback & c.Next()
end
Downstream-->>Distributor: response
alt success & channel selected
Distributor->>AffinityService: RecordChannelAffinity(ctx, channelID)
AffinityService->>AffinityCache: Set(cacheKey, channelID, TTL)
end
Distributor-->>Client: response
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
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: 2
🤖 Fix all issues with AI agents
In `@web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx`:
- Around line 200-212: Wrap the async onOk handler inside confirmClearAllCache
in a try-catch (and optionally finally) to handle API errors: call
API.delete('/api/option/channel_affinity_cache', { params: { all: true } })
inside try, keep the existing success path (destructure res.data,
showError(t(message)) on logical failure, showSuccess on success), and in catch
call showError with a useful message (e.g., t('清空缓存失败') plus error.message) and
ensure refreshCacheStats is called in finally or after success so the UI stays
consistent; reference the onOk callback, API.delete call, showError/showSuccess
and refreshCacheStats when applying the change.
- Around line 229-241: The onOk handler in confirmClearRuleCache currently calls
API.delete('/api/option/channel_affinity_cache', ...) without error handling;
wrap the async API.delete call and subsequent logic in a try-catch inside the
onOk async function (referencing confirmClearRuleCache -> onOk, API.delete,
refreshCacheStats), call showError with the caught error (or t(error.message)
when available) on failure, and only showSuccess and call refreshCacheStats when
the request succeeds; ensure any thrown errors are caught to prevent unhandled
rejections.
🧹 Nitpick comments (5)
service/channel_affinity.go (2)
54-71: Cache initialization is not reconfigurable at runtime.The cache is initialized once via
sync.Once, so changes toMaxEntriesorDefaultTTLSecondsin the settings won't take effect until service restart. This is a common trade-off for performance, but worth documenting or exposing a way to reinitialize.
201-223: Regex compilation errors are silently ignored.When a regex pattern fails to compile (line 212-214), it's silently skipped. Consider logging a warning so admins can identify misconfigured patterns.
Proposed fix
if !ok { compiled, err := regexp.Compile(pattern) if err != nil { + common.SysError(fmt.Sprintf("channel affinity: invalid regex pattern %q: %v", pattern, err)) continue } re = compiled channelAffinityRegexCache.Store(pattern, re) }web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx (3)
176-190: Missing error handling for network failures.The
catchblock at line 185 shows a generic error message without the actual error details. Consider loggingefor debugging purposes.Proposed fix
} catch (e) { + console.error('Failed to refresh cache stats:', e); showError(t('刷新缓存统计失败')); } finally {
554-566: Checking forundefinedin Promise results may not catch all failures.The check
res.includes(undefined)at lines 557 and 559 assumes that failed promises returnundefined. If the API wrapper throws or returns a different falsy value, errors may be silently ignored. Consider usingPromise.allSettledfor more robust error handling.Proposed improvement using Promise.allSettled
- Promise.all(requestQueue) - .then((res) => { - if (requestQueue.length === 1) { - if (res.includes(undefined)) return; - } else if (requestQueue.length > 1) { - if (res.includes(undefined)) - return showError(t('部分保存失败,请重试')); - } - showSuccess(t('保存成功')); - props.refresh(); - }) - .catch(() => showError(t('保存失败,请重试'))) - .finally(() => setLoading(false)); + Promise.allSettled(requestQueue) + .then((results) => { + const failed = results.filter((r) => r.status === 'rejected'); + if (failed.length > 0) { + if (failed.length === results.length) { + showError(t('保存失败,请重试')); + } else { + showError(t('部分保存失败,请重试')); + } + return; + } + showSuccess(t('保存成功')); + props.refresh(); + }) + .finally(() => setLoading(false));
569-598: Missing dependency in useEffect.The
useEffecthook referencesinputsincurrentInputs = { ...inputs }but doesn't includeinputsin the dependency array. However, since the intent is to reset inputs whenprops.optionschanges, this is actually correct behavior. Addinginputswould cause infinite loops. Consider adding a comment to clarify this intentional omission.
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
controller/channel_affinity_cache.gorouter/api-router.goservice/channel_affinity.gosetting/operation_setting/channel_affinity_setting.goweb/src/pages/Setting/Operation/SettingsChannelAffinity.jsx
🚧 Files skipped from review as they are similar to previous changes (1)
- setting/operation_setting/channel_affinity_setting.go
🧰 Additional context used
🧬 Code graph analysis (3)
web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx (1)
web/src/helpers/utils.jsx (4)
showError(122-151)showSuccess(157-159)showWarning(153-155)compareObjects(306-323)
controller/channel_affinity_cache.go (1)
service/channel_affinity.go (3)
GetChannelAffinityCacheStats(73-142)ClearChannelAffinityCacheAll(144-149)ClearChannelAffinityCacheByRuleName(151-199)
router/api-router.go (2)
controller/channel_affinity_cache.go (2)
GetChannelAffinityCacheStats(11-18)ClearChannelAffinityCache(20-60)service/channel_affinity.go (1)
GetChannelAffinityCacheStats(73-142)
🔇 Additional comments (7)
service/channel_affinity.go (3)
340-410: LGTM: Main affinity lookup logic is well-structured.The function correctly validates settings, iterates through rules with proper short-circuit logic, extracts affinity values, and handles cache lookup. The context metadata is properly populated for downstream logging.
447-467: LGTM: RecordChannelAffinity correctly persists cache entries.The function properly validates inputs, respects the enabled setting, and applies appropriate TTL fallbacks.
262-275: [No action needed. The performance concern is unfounded.]
GetRequestBodyalready implements request-level caching viac.Get(KeyRequestBody)andc.Set(KeyRequestBody, body). The body is read once and cached in the gin context for the lifetime of the request, so repeated calls toextractChannelAffinityValuewith differentgjsonsources will use the cached body rather than triggering additional reads.Likely an incorrect or invalid review comment.
controller/channel_affinity_cache.go (2)
11-18: LGTM: Simple and correct stats endpoint.The handler correctly delegates to the service layer and returns a consistent JSON response format.
20-60: LGTM: Clear cache endpoint with proper validation.The handler correctly handles both
all=trueandrule_nameparameters, returns appropriate error responses for invalid inputs, and delegates to the service layer. The response format is consistent with other endpoints.router/api-router.go (1)
126-127: LGTM: Routes correctly added under admin-protected group.The new cache management endpoints are appropriately placed under the
optionRoutegroup which requiresRootAuth, ensuring only administrators can access cache statistics and perform cache clearing operations.web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx (1)
889-949: LGTM: Key sources table implementation is well-structured.The nested table for managing key sources within the modal is correctly implemented with proper state management through
updateKeySource,addKeySource, andremoveKeySourcefunctions.
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
| onOk: async () => { | ||
| const res = await API.delete('/api/option/channel_affinity_cache', { | ||
| params: { all: true }, | ||
| }); | ||
| const { success, message } = res.data; | ||
| if (!success) { | ||
| showError(t(message)); | ||
| return; | ||
| } | ||
| showSuccess(t('已清空')); | ||
| await refreshCacheStats(); | ||
| }, | ||
| }); |
There was a problem hiding this comment.
Missing error handling for cache clear operation.
The onOk callback in confirmClearAllCache doesn't have a try-catch wrapper. If the API call fails, the error will be unhandled.
Proposed fix
onOk: async () => {
+ try {
const res = await API.delete('/api/option/channel_affinity_cache', {
params: { all: true },
});
const { success, message } = res.data;
if (!success) {
showError(t(message));
return;
}
showSuccess(t('已清空'));
await refreshCacheStats();
+ } catch (e) {
+ console.error('Failed to clear all cache:', e);
+ showError(t('清空缓存失败'));
+ }
},📝 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.
| onOk: async () => { | |
| const res = await API.delete('/api/option/channel_affinity_cache', { | |
| params: { all: true }, | |
| }); | |
| const { success, message } = res.data; | |
| if (!success) { | |
| showError(t(message)); | |
| return; | |
| } | |
| showSuccess(t('已清空')); | |
| await refreshCacheStats(); | |
| }, | |
| }); | |
| onOk: async () => { | |
| try { | |
| const res = await API.delete('/api/option/channel_affinity_cache', { | |
| params: { all: true }, | |
| }); | |
| const { success, message } = res.data; | |
| if (!success) { | |
| showError(t(message)); | |
| return; | |
| } | |
| showSuccess(t('已清空')); | |
| await refreshCacheStats(); | |
| } catch (e) { | |
| console.error('Failed to clear all cache:', e); | |
| showError(t('清空缓存失败')); | |
| } | |
| }, |
🤖 Prompt for AI Agents
In `@web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx` around lines 200
- 212, Wrap the async onOk handler inside confirmClearAllCache in a try-catch
(and optionally finally) to handle API errors: call
API.delete('/api/option/channel_affinity_cache', { params: { all: true } })
inside try, keep the existing success path (destructure res.data,
showError(t(message)) on logical failure, showSuccess on success), and in catch
call showError with a useful message (e.g., t('清空缓存失败') plus error.message) and
ensure refreshCacheStats is called in finally or after success so the UI stays
consistent; reference the onOk callback, API.delete call, showError/showSuccess
and refreshCacheStats when applying the change.
| onOk: async () => { | ||
| const res = await API.delete('/api/option/channel_affinity_cache', { | ||
| params: { rule_name: name }, | ||
| }); | ||
| const { success, message } = res.data; | ||
| if (!success) { | ||
| showError(t(message)); | ||
| return; | ||
| } | ||
| showSuccess(t('已清空')); | ||
| await refreshCacheStats(); | ||
| }, | ||
| }); |
There was a problem hiding this comment.
Same issue: Missing error handling for rule-specific cache clear.
The onOk callback in confirmClearRuleCache should also wrap the API call in try-catch.
Proposed fix
onOk: async () => {
+ try {
const res = await API.delete('/api/option/channel_affinity_cache', {
params: { rule_name: name },
});
const { success, message } = res.data;
if (!success) {
showError(t(message));
return;
}
showSuccess(t('已清空'));
await refreshCacheStats();
+ } catch (e) {
+ console.error('Failed to clear rule cache:', e);
+ showError(t('清空缓存失败'));
+ }
},📝 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.
| onOk: async () => { | |
| const res = await API.delete('/api/option/channel_affinity_cache', { | |
| params: { rule_name: name }, | |
| }); | |
| const { success, message } = res.data; | |
| if (!success) { | |
| showError(t(message)); | |
| return; | |
| } | |
| showSuccess(t('已清空')); | |
| await refreshCacheStats(); | |
| }, | |
| }); | |
| onOk: async () => { | |
| try { | |
| const res = await API.delete('/api/option/channel_affinity_cache', { | |
| params: { rule_name: name }, | |
| }); | |
| const { success, message } = res.data; | |
| if (!success) { | |
| showError(t(message)); | |
| return; | |
| } | |
| showSuccess(t('已清空')); | |
| await refreshCacheStats(); | |
| } catch (e) { | |
| console.error('Failed to clear rule cache:', e); | |
| showError(t('清空缓存失败')); | |
| } | |
| }, | |
| }); |
🤖 Prompt for AI Agents
In `@web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx` around lines 229
- 241, The onOk handler in confirmClearRuleCache currently calls
API.delete('/api/option/channel_affinity_cache', ...) without error handling;
wrap the async API.delete call and subsequent logic in a try-catch inside the
onOk async function (referencing confirmClearRuleCache -> onOk, API.delete,
refreshCacheStats), call showError with the caught error (or t(error.message)
when available) on failure, and only showSuccess and call refreshCacheStats when
the request succeeds; ensure any thrown errors are caught to prevent unhandled
rejections.
# Conflicts: # middleware/distributor.go # relay/compatible_handler.go
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Fix all issues with AI agents
In `@pkg/cachex/hybrid_cache.go`:
- Around line 69-78: The memCache() fallback currently builds an in-memory cache
with capacity 1 which is too small; update the fallback in
HybridCache[V].memCache() to use a sensible default capacity (e.g., 1000)
instead of 1, or make it configurable via a new field (e.g., memDefaultCapacity)
on HybridCache and use that when memInit is nil; adjust the
hot.NewHotCache[string, V](hot.LRU, <capacity>).Build() call accordingly and
ensure any new field has a documented default.
In `@service/channel_affinity.go`:
- Around line 164-176: ClearChannelAffinityCacheAll can panic because
getChannelAffinityCache dereferences channel-affinity settings; guard against
nil by checking the returned cache before using it. Update
ClearChannelAffinityCacheAll to call getChannelAffinityCache(), return 0
immediately if the cache is nil (or if it signals uninitialized settings), and
only call cache.Keys() / cache.DeleteMany when cache is non-nil; reference
functions: ClearChannelAffinityCacheAll and getChannelAffinityCache, and the
cache methods Keys and DeleteMany.
- Around line 352-423: GetPreferredChannelByAffinity can panic when c is nil
because later calls (e.g., extractChannelAffinityValue(c, ...),
setChannelAffinityContext(c, ...)) assume a non-nil *gin.Context; add an
explicit nil guard at the start of GetPreferredChannelByAffinity (if c == nil {
return 0, false }) so the function exits early instead of calling helpers with a
nil context, and ensure any helper functions you rely on
(extractChannelAffinityValue, setChannelAffinityContext) still handle nil
defensively if they may be called elsewhere.
🧹 Nitpick comments (1)
pkg/cachex/hybrid_cache.go (1)
208-226: Inconsistent error handling in memory path.Line 219 discards the error from
DeleteMany, while the Redis path (lines 196-197) checks and returns it. For consistency and defensive coding, consider handling the error:Proposed fix
// In memory, we filter keys and bulk delete. allKeys := c.memCache().Keys() keys := make([]string, 0, 128) for _, k := range allKeys { if strings.HasPrefix(k, fullPrefix) { keys = append(keys, k) } } if len(keys) == 0 { return 0, nil } - res, _ := c.DeleteMany(keys) + res, err := c.DeleteMany(keys) + if err != nil { + return 0, err + } deleted := 0 for _, ok := range res { if ok { deleted++ } } return deleted, nil }
| func (c *HybridCache[V]) memCache() *hot.HotCache[string, V] { | ||
| c.memOnce.Do(func() { | ||
| if c.memInit == nil { | ||
| c.mem = hot.NewHotCache[string, V](hot.LRU, 1).Build() | ||
| return | ||
| } | ||
| c.mem = c.memInit() | ||
| }) | ||
| return c.mem | ||
| } |
There was a problem hiding this comment.
Default in-memory cache with capacity 1 is likely too small.
When memInit is nil, the fallback creates a cache with capacity 1, which can only store a single entry. This effectively negates caching benefits since every new key evicts the previous one.
Consider using a more reasonable default capacity (e.g., 1000 or configurable):
Proposed fix
func (c *HybridCache[V]) memCache() *hot.HotCache[string, V] {
c.memOnce.Do(func() {
if c.memInit == nil {
- c.mem = hot.NewHotCache[string, V](hot.LRU, 1).Build()
+ c.mem = hot.NewHotCache[string, V](hot.LRU, 1000).Build()
return
}
c.mem = c.memInit()
})
return c.mem
}🤖 Prompt for AI Agents
In `@pkg/cachex/hybrid_cache.go` around lines 69 - 78, The memCache() fallback
currently builds an in-memory cache with capacity 1 which is too small; update
the fallback in HybridCache[V].memCache() to use a sensible default capacity
(e.g., 1000) instead of 1, or make it configurable via a new field (e.g.,
memDefaultCapacity) on HybridCache and use that when memInit is nil; adjust the
hot.NewHotCache[string, V](hot.LRU, <capacity>).Build() call accordingly and
ensure any new field has a documented default.
| func ClearChannelAffinityCacheAll() int { | ||
| cache := getChannelAffinityCache() | ||
| keys, err := cache.Keys() | ||
| if err != nil { | ||
| common.SysError(fmt.Sprintf("channel affinity cache list keys failed: err=%v", err)) | ||
| keys = nil | ||
| } | ||
| if len(keys) > 0 { | ||
| if _, err := cache.DeleteMany(keys); err != nil { | ||
| common.SysError(fmt.Sprintf("channel affinity cache delete many failed: err=%v", err)) | ||
| } | ||
| } | ||
| return len(keys) |
There was a problem hiding this comment.
Guard against nil channel-affinity settings before cache init.
ClearChannelAffinityCacheAll calls getChannelAffinityCache, which dereferences settings. Other entrypoints guard against nil settings; this one can panic if settings aren’t initialized yet.
🐛 Proposed fix
func ClearChannelAffinityCacheAll() int {
+ if operation_setting.GetChannelAffinitySetting() == nil {
+ return 0
+ }
cache := getChannelAffinityCache()
keys, err := cache.Keys()
if err != nil {
common.SysError(fmt.Sprintf("channel affinity cache list keys failed: err=%v", err))
keys = nil
}📝 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.
| func ClearChannelAffinityCacheAll() int { | |
| cache := getChannelAffinityCache() | |
| keys, err := cache.Keys() | |
| if err != nil { | |
| common.SysError(fmt.Sprintf("channel affinity cache list keys failed: err=%v", err)) | |
| keys = nil | |
| } | |
| if len(keys) > 0 { | |
| if _, err := cache.DeleteMany(keys); err != nil { | |
| common.SysError(fmt.Sprintf("channel affinity cache delete many failed: err=%v", err)) | |
| } | |
| } | |
| return len(keys) | |
| func ClearChannelAffinityCacheAll() int { | |
| if operation_setting.GetChannelAffinitySetting() == nil { | |
| return 0 | |
| } | |
| cache := getChannelAffinityCache() | |
| keys, err := cache.Keys() | |
| if err != nil { | |
| common.SysError(fmt.Sprintf("channel affinity cache list keys failed: err=%v", err)) | |
| keys = nil | |
| } | |
| if len(keys) > 0 { | |
| if _, err := cache.DeleteMany(keys); err != nil { | |
| common.SysError(fmt.Sprintf("channel affinity cache delete many failed: err=%v", err)) | |
| } | |
| } | |
| return len(keys) | |
| } |
🤖 Prompt for AI Agents
In `@service/channel_affinity.go` around lines 164 - 176,
ClearChannelAffinityCacheAll can panic because getChannelAffinityCache
dereferences channel-affinity settings; guard against nil by checking the
returned cache before using it. Update ClearChannelAffinityCacheAll to call
getChannelAffinityCache(), return 0 immediately if the cache is nil (or if it
signals uninitialized settings), and only call cache.Keys() / cache.DeleteMany
when cache is non-nil; reference functions: ClearChannelAffinityCacheAll and
getChannelAffinityCache, and the cache methods Keys and DeleteMany.
| func GetPreferredChannelByAffinity(c *gin.Context, modelName string, usingGroup string) (int, bool) { | ||
| setting := operation_setting.GetChannelAffinitySetting() | ||
| if setting == nil || !setting.Enabled { | ||
| return 0, false | ||
| } | ||
| path := "" | ||
| if c != nil && c.Request != nil && c.Request.URL != nil { | ||
| path = c.Request.URL.Path | ||
| } | ||
| userAgent := "" | ||
| if c != nil && c.Request != nil { | ||
| userAgent = c.Request.UserAgent() | ||
| } | ||
|
|
||
| for _, rule := range setting.Rules { | ||
| if !matchAnyRegexCached(rule.ModelRegex, modelName) { | ||
| continue | ||
| } | ||
| if len(rule.PathRegex) > 0 && !matchAnyRegexCached(rule.PathRegex, path) { | ||
| continue | ||
| } | ||
| if len(rule.UserAgentInclude) > 0 && !matchAnyIncludeFold(rule.UserAgentInclude, userAgent) { | ||
| continue | ||
| } | ||
| var affinityValue string | ||
| var usedSource operation_setting.ChannelAffinityKeySource | ||
| for _, src := range rule.KeySources { | ||
| affinityValue = extractChannelAffinityValue(c, src) | ||
| if affinityValue != "" { | ||
| usedSource = src | ||
| break | ||
| } | ||
| } | ||
| if affinityValue == "" { | ||
| continue | ||
| } | ||
| if rule.ValueRegex != "" && !matchAnyRegexCached([]string{rule.ValueRegex}, affinityValue) { | ||
| continue | ||
| } | ||
|
|
||
| ttlSeconds := rule.TTLSeconds | ||
| if ttlSeconds <= 0 { | ||
| ttlSeconds = setting.DefaultTTLSeconds | ||
| } | ||
| cacheKeySuffix := buildChannelAffinityCacheKeySuffix(rule, usingGroup, affinityValue) | ||
| cacheKeyFull := channelAffinityCacheNamespace + ":" + cacheKeySuffix | ||
| setChannelAffinityContext(c, channelAffinityMeta{ | ||
| CacheKey: cacheKeyFull, | ||
| TTLSeconds: ttlSeconds, | ||
| RuleName: rule.Name, | ||
| KeySourceType: strings.TrimSpace(usedSource.Type), | ||
| KeySourceKey: strings.TrimSpace(usedSource.Key), | ||
| KeySourcePath: strings.TrimSpace(usedSource.Path), | ||
| KeyFingerprint: affinityFingerprint(affinityValue), | ||
| UsingGroup: usingGroup, | ||
| ModelName: modelName, | ||
| RequestPath: path, | ||
| }) | ||
|
|
||
| cache := getChannelAffinityCache() | ||
| channelID, found, err := cache.Get(cacheKeySuffix) | ||
| if err != nil { | ||
| common.SysError(fmt.Sprintf("channel affinity cache get failed: key=%s, err=%v", cacheKeyFull, err)) | ||
| return 0, false | ||
| } | ||
| if found { | ||
| return channelID, true | ||
| } | ||
| return 0, false | ||
| } | ||
| return 0, false | ||
| } |
There was a problem hiding this comment.
Avoid nil-context panics in affinity lookup.
GetPreferredChannelByAffinity accepts a *gin.Context but later calls context helpers unconditionally. If c is nil, this will panic.
🐛 Proposed fix
func GetPreferredChannelByAffinity(c *gin.Context, modelName string, usingGroup string) (int, bool) {
setting := operation_setting.GetChannelAffinitySetting()
if setting == nil || !setting.Enabled {
return 0, false
}
+ if c == nil {
+ return 0, false
+ }
path := ""
if c != nil && c.Request != nil && c.Request.URL != nil {
path = c.Request.URL.Path
}🤖 Prompt for AI Agents
In `@service/channel_affinity.go` around lines 352 - 423,
GetPreferredChannelByAffinity can panic when c is nil because later calls (e.g.,
extractChannelAffinityValue(c, ...), setChannelAffinityContext(c, ...)) assume a
non-nil *gin.Context; add an explicit nil guard at the start of
GetPreferredChannelByAffinity (if c == nil { return 0, false }) so the function
exits early instead of calling helpers with a nil context, and ensure any helper
functions you rely on (extractChannelAffinityValue, setChannelAffinityContext)
still handle nil defensively if they may be called elsewhere.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx (1)
501-565: Guard JSON parsing ofrecord.otherto avoid render crashes.
JSON.parsecan throw on null/invalid payloads, which would break the logs table. UsegetLogOther(already imported) or wrap in try/catch before reading admin info.🛠️ Suggested fix (safe parse + array guard)
- if (record.other !== '') { - let other = JSON.parse(record.other); - if (other === null) { - return <></>; - } - if (other.admin_info !== undefined) { - if ( - other.admin_info.use_channel !== null && - other.admin_info.use_channel !== undefined && - other.admin_info.use_channel !== '' - ) { - let useChannel = other.admin_info.use_channel; - let useChannelStr = useChannel.join('->'); - content = t('渠道') + `:${useChannelStr}`; - } - if (other.admin_info.channel_affinity) { - affinity = other.admin_info.channel_affinity; - } - } - } + const other = getLogOther(record.other); + if (other?.admin_info) { + const useChannel = other.admin_info.use_channel; + if (Array.isArray(useChannel) && useChannel.length > 0) { + const useChannelStr = useChannel.join('->'); + content = t('渠道') + `:${useChannelStr}`; + } + if (other.admin_info.channel_affinity) { + affinity = other.admin_info.channel_affinity; + } + }
🤖 Fix all issues with AI agents
In `@web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx`:
- Around line 359-479: The TTL cell rendering in ruleColumns currently uses
Number(v || 0) || '-' which treats 0 as falsy and renders '-' instead of showing
0 (the "use default" signal); update the ttl_seconds render logic in ruleColumns
to explicitly treat null/undefined/empty as the placeholder ('-') and otherwise
render the actual numeric value (including 0) or a localized "默认" label if you
prefer; locate the render function for dataIndex 'ttl_seconds' and replace the
single falsy-coercing expression with an explicit check (e.g., v === null || v
=== undefined || v === '' => '-' else show Number(v) or '默认' for 0).
♻️ Duplicate comments (2)
web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx (2)
234-255: Handle API errors when clearing all cache.
Uncaught failures here will surface as unhandled rejections and leave users without feedback.🛠️ Suggested fix
onOk: async () => { - const res = await API.delete('/api/option/channel_affinity_cache', { - params: { all: true }, - }); - const { success, message } = res.data; - if (!success) { - showError(t(message)); - return; - } - showSuccess(t('已清空')); - await refreshCacheStats(); + try { + const res = await API.delete('/api/option/channel_affinity_cache', { + params: { all: true }, + }); + const { success, message } = res.data; + if (!success) { + showError(t(message)); + return; + } + showSuccess(t('已清空')); + await refreshCacheStats(); + } catch (e) { + console.error('Failed to clear all cache:', e); + showError(t('清空缓存失败')); + } },
257-286: Handle API errors when clearing rule cache.
Same unhandled-rejection risk as the clear-all path.🛠️ Suggested fix
onOk: async () => { - const res = await API.delete('/api/option/channel_affinity_cache', { - params: { rule_name: name }, - }); - const { success, message } = res.data; - if (!success) { - showError(t(message)); - return; - } - showSuccess(t('已清空')); - await refreshCacheStats(); + try { + const res = await API.delete('/api/option/channel_affinity_cache', { + params: { rule_name: name }, + }); + const { success, message } = res.data; + if (!success) { + showError(t(message)); + return; + } + showSuccess(t('已清空')); + await refreshCacheStats(); + } catch (e) { + console.error('Failed to clear rule cache:', e); + showError(t('清空缓存失败')); + } },
| const ruleColumns = [ | ||
| { | ||
| title: t('名称'), | ||
| dataIndex: 'name', | ||
| render: (text) => <Text>{text || '-'}</Text>, | ||
| }, | ||
| { | ||
| title: t('模型正则'), | ||
| dataIndex: 'model_regex', | ||
| render: (list) => | ||
| (list || []).length > 0 | ||
| ? (list || []).slice(0, 3).map((v, idx) => ( | ||
| <Tag key={`${v}-${idx}`} style={{ marginRight: 4 }}> | ||
| {v} | ||
| </Tag> | ||
| )) | ||
| : '-', | ||
| }, | ||
| { | ||
| title: t('路径正则'), | ||
| dataIndex: 'path_regex', | ||
| render: (list) => | ||
| (list || []).length > 0 | ||
| ? (list || []).slice(0, 2).map((v, idx) => ( | ||
| <Tag key={`${v}-${idx}`} style={{ marginRight: 4 }}> | ||
| {v} | ||
| </Tag> | ||
| )) | ||
| : '-', | ||
| }, | ||
| { | ||
| title: t('User-Agent include'), | ||
| dataIndex: 'user_agent_include', | ||
| render: (list) => | ||
| (list || []).length > 0 | ||
| ? (list || []).slice(0, 2).map((v, idx) => ( | ||
| <Tag key={`${v}-${idx}`} style={{ marginRight: 4 }}> | ||
| {v} | ||
| </Tag> | ||
| )) | ||
| : '-', | ||
| }, | ||
| { | ||
| title: t('Key 来源'), | ||
| dataIndex: 'key_sources', | ||
| render: (list) => { | ||
| const xs = list || []; | ||
| if (xs.length === 0) return '-'; | ||
| return xs.slice(0, 3).map((src, idx) => { | ||
| const s = normalizeKeySource(src); | ||
| const detail = s.type === 'gjson' ? s.path : s.key; | ||
| return ( | ||
| <Tag key={`${s.type}-${idx}`} style={{ marginRight: 4 }}> | ||
| {s.type}:{detail} | ||
| </Tag> | ||
| ); | ||
| }); | ||
| }, | ||
| }, | ||
| { | ||
| title: t('TTL(秒)'), | ||
| dataIndex: 'ttl_seconds', | ||
| render: (v) => <Text>{Number(v || 0) || '-'}</Text>, | ||
| }, | ||
| { | ||
| title: t('缓存条目数'), | ||
| render: (_, record) => { | ||
| const name = (record?.name || '').trim(); | ||
| if (!name || !record?.include_rule_name) { | ||
| return <Text type='tertiary'>N/A</Text>; | ||
| } | ||
| const n = Number(cacheStats?.by_rule_name?.[name] || 0); | ||
| return <Text>{n}</Text>; | ||
| }, | ||
| }, | ||
| { | ||
| title: t('作用域'), | ||
| render: (_, record) => { | ||
| const tags = []; | ||
| if (record?.include_using_group) tags.push('分组'); | ||
| if (record?.include_rule_name) tags.push('规则'); | ||
| if (tags.length === 0) return '-'; | ||
| return tags.map((x) => ( | ||
| <Tag key={x} style={{ marginRight: 4 }}> | ||
| {x} | ||
| </Tag> | ||
| )); | ||
| }, | ||
| }, | ||
| { | ||
| title: t('操作'), | ||
| render: (_, record) => ( | ||
| <Space> | ||
| <Button | ||
| icon={<IconClose />} | ||
| theme='borderless' | ||
| type='warning' | ||
| disabled={!record?.include_rule_name} | ||
| title={t('清空该规则缓存')} | ||
| aria-label={t('清空该规则缓存')} | ||
| onClick={() => confirmClearRuleCache(record)} | ||
| /> | ||
| <Button | ||
| icon={<IconEdit />} | ||
| theme='borderless' | ||
| title={t('编辑规则')} | ||
| aria-label={t('编辑规则')} | ||
| onClick={() => handleEditRule(record)} | ||
| /> | ||
| <Button | ||
| icon={<IconDelete />} | ||
| theme='borderless' | ||
| type='danger' | ||
| title={t('删除规则')} | ||
| aria-label={t('删除规则')} | ||
| onClick={() => handleDeleteRule(record.id)} | ||
| /> | ||
| </Space> | ||
| ), | ||
| }, | ||
| ]; |
There was a problem hiding this comment.
TTL 0 renders as “-”, which hides the “use default” signal.
Number(v || 0) || '-' treats 0 as falsy. Show 0 (or a “默认” label) explicitly.
🛠️ Suggested fix
- render: (v) => <Text>{Number(v || 0) || '-'}</Text>,
+ render: (v) => {
+ const ttl = Number(v ?? 0);
+ return <Text>{Number.isFinite(ttl) ? ttl : '-'}</Text>;
+ },🤖 Prompt for AI Agents
In `@web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx` around lines 359
- 479, The TTL cell rendering in ruleColumns currently uses Number(v || 0) ||
'-' which treats 0 as falsy and renders '-' instead of showing 0 (the "use
default" signal); update the ttl_seconds render logic in ruleColumns to
explicitly treat null/undefined/empty as the placeholder ('-') and otherwise
render the actual numeric value (including 0) or a localized "默认" label if you
prefer; locate the render function for dataIndex 'ttl_seconds' and replace the
single falsy-coercing expression with an explicit check (e.g., v === null || v
=== undefined || v === '' => '-' else show Number(v) or '默认' for 0).
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@web/src/components/table/channels/modals/CodexUsageModal.jsx`:
- Around line 192-218: In fetchUsage, ensure you reset per-call state and always
clear loading on early return: at the start of fetchUsage set
hasShownErrorRef.current = false and initialize payload/loading (e.g.,
setPayload(null); setLoading(true)); then if (!recordId) do an early return
after setting setLoading(false) (and setPayload(null) if needed) so the spinner
is cleared; keep the existing try/catch/finally but rely on the final cleanup
and the reset of hasShownErrorRef to allow errors to surface on subsequent
calls. Reference fetchUsage, recordId, hasShownErrorRef, mountedRef, setLoading,
setPayload, and showError.
| const fetchUsage = useCallback(async () => { | ||
| if (!recordId) { | ||
| if (mountedRef.current) setPayload(null); | ||
| return; | ||
| } | ||
|
|
||
| if (mountedRef.current) setLoading(true); | ||
| try { | ||
| const res = await API.get(`/api/channel/${recordId}/codex/usage`, { | ||
| skipErrorHandler: true, | ||
| }); | ||
| if (!mountedRef.current) return; | ||
| setPayload(res?.data ?? null); | ||
| if (!res?.data?.success && !hasShownErrorRef.current) { | ||
| hasShownErrorRef.current = true; | ||
| showError(tt('获取用量失败')); | ||
| } | ||
| } catch (error) { | ||
| if (!mountedRef.current) return; | ||
| if (!hasShownErrorRef.current) { | ||
| hasShownErrorRef.current = true; | ||
| showError(tt('获取用量失败')); | ||
| } | ||
| setPayload({ success: false, message: String(error) }); | ||
| } finally { | ||
| if (mountedRef.current) setLoading(false); | ||
| } |
There was a problem hiding this comment.
Prevent silent refresh failures and a stuck spinner.
If recordId is missing (Line 193), loading remains true, leaving the spinner up indefinitely. Also, hasShownErrorRef never resets, so subsequent refresh failures won’t surface an error. Consider resetting state at the start of each fetch and clearing loading on early return.
🔧 Proposed fix
const fetchUsage = useCallback(async () => {
if (!recordId) {
- if (mountedRef.current) setPayload(null);
+ if (mountedRef.current) {
+ setLoading(false);
+ setPayload(null);
+ }
return;
}
- if (mountedRef.current) setLoading(true);
+ if (mountedRef.current) {
+ setLoading(true);
+ hasShownErrorRef.current = false;
+ }
try {
const res = await API.get(`/api/channel/${recordId}/codex/usage`, {
skipErrorHandler: true,
});🤖 Prompt for AI Agents
In `@web/src/components/table/channels/modals/CodexUsageModal.jsx` around lines
192 - 218, In fetchUsage, ensure you reset per-call state and always clear
loading on early return: at the start of fetchUsage set hasShownErrorRef.current
= false and initialize payload/loading (e.g., setPayload(null);
setLoading(true)); then if (!recordId) do an early return after setting
setLoading(false) (and setPayload(null) if needed) so the spinner is cleared;
keep the existing try/catch/finally but rely on the final cleanup and the reset
of hasShownErrorRef to allow errors to surface on subsequent calls. Reference
fetchUsage, recordId, hasShownErrorRef, mountedRef, setLoading, setPayload, and
showError.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx`:
- Around line 660-672: The current Promise.all handling treats a single failed
request silently but shows an error for multiple failures; update the resolution
logic in the Promise.all(...).then callback (the code manipulating requestQueue,
res, showError, showSuccess, props.refresh, setLoading) so that any
res.includes(undefined) triggers showError(...) and returns early regardless of
requestQueue length; only call showSuccess(...) and props.refresh() when all
responses are defined. Ensure setLoading(false) remains in finally.
🧹 Nitpick comments (2)
web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx (2)
558-610: Consider guarding against null form ref.Line 560 accesses
modalFormRef.current.validate()without a null check. While unlikely in practice (the form should be mounted when modal is visible), a defensive check would prevent potential runtime errors.Proposed fix
const handleModalSave = async () => { try { + if (!modalFormRef.current) { + return showError(t('表单未就绪,请重试')); + } const values = await modalFormRef.current.validate();
179-211: Component is well-structured but consider extraction for maintainability.The component handles a lot of functionality (~1100 lines). For long-term maintainability, consider extracting the modal form (lines 872-1109) and the rules table (lines 376-496) into separate components. This is optional and can be deferred.
| Promise.all(requestQueue) | ||
| .then((res) => { | ||
| if (requestQueue.length === 1) { | ||
| if (res.includes(undefined)) return; | ||
| } else if (requestQueue.length > 1) { | ||
| if (res.includes(undefined)) | ||
| return showError(t('部分保存失败,请重试')); | ||
| } | ||
| showSuccess(t('保存成功')); | ||
| props.refresh(); | ||
| }) | ||
| .catch(() => showError(t('保存失败,请重试'))) | ||
| .finally(() => setLoading(false)); |
There was a problem hiding this comment.
Inconsistent error handling for single vs multiple requests.
When a single request fails (line 663), it silently returns without user feedback. For multiple requests (line 665-666), it shows an error. Both cases should provide user feedback.
Proposed fix
Promise.all(requestQueue)
.then((res) => {
- if (requestQueue.length === 1) {
- if (res.includes(undefined)) return;
- } else if (requestQueue.length > 1) {
- if (res.includes(undefined))
- return showError(t('部分保存失败,请重试'));
+ if (res.includes(undefined)) {
+ return showError(t('部分保存失败,请重试'));
}
showSuccess(t('保存成功'));
props.refresh();
})
.catch(() => showError(t('保存失败,请重试')))
.finally(() => setLoading(false));📝 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.
| Promise.all(requestQueue) | |
| .then((res) => { | |
| if (requestQueue.length === 1) { | |
| if (res.includes(undefined)) return; | |
| } else if (requestQueue.length > 1) { | |
| if (res.includes(undefined)) | |
| return showError(t('部分保存失败,请重试')); | |
| } | |
| showSuccess(t('保存成功')); | |
| props.refresh(); | |
| }) | |
| .catch(() => showError(t('保存失败,请重试'))) | |
| .finally(() => setLoading(false)); | |
| Promise.all(requestQueue) | |
| .then((res) => { | |
| if (res.includes(undefined)) { | |
| return showError(t('部分保存失败,请重试')); | |
| } | |
| showSuccess(t('保存成功')); | |
| props.refresh(); | |
| }) | |
| .catch(() => showError(t('保存失败,请重试'))) | |
| .finally(() => setLoading(false)); |
🤖 Prompt for AI Agents
In `@web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx` around lines 660
- 672, The current Promise.all handling treats a single failed request silently
but shows an error for multiple failures; update the resolution logic in the
Promise.all(...).then callback (the code manipulating requestQueue, res,
showError, showSuccess, props.refresh, setLoading) so that any
res.includes(undefined) triggers showError(...) and returns early regardless of
requestQueue length; only call showSuccess(...) and props.refresh() when all
responses are defined. Ensure setLoading(false) remains in finally.
…r channel, update the affinity to the successful channel
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@service/channel_affinity.go`:
- Around line 460-487: RecordChannelAffinity calls getChannelAffinityContext(c)
without ensuring c is non-nil, which can panic; modify the function to guard
against a nil context before calling getChannelAffinityContext (either return
early if c == nil when context is required, or make getChannelAffinityContext
handle a nil *gin.Context). Specifically, in RecordChannelAffinity (and around
the setting.SwitchOnSuccess branch) add a nil check for c before invoking
getChannelAffinityContext or update getChannelAffinityContext to safely handle
nil by returning ok=false when c is nil so RecordChannelAffinity will return
gracefully.
♻️ Duplicate comments (6)
service/channel_affinity.go (2)
164-177: Guard against nil settings before cache initialization.
ClearChannelAffinityCacheAllcan still panic ifoperation_setting.GetChannelAffinitySetting()returns nil, sincegetChannelAffinityCache()dereferences settings unconditionally.🐛 Proposed fix
func ClearChannelAffinityCacheAll() int { + if operation_setting.GetChannelAffinitySetting() == nil { + return 0 + } cache := getChannelAffinityCache() keys, err := cache.Keys()
352-423: Guard against nil context to prevent panics.
GetPreferredChannelByAffinitydefensively extractspathanduserAgentwhencis non-nil, but later callsextractChannelAffinityValue(c, src)andsetChannelAffinityContext(c, meta)unconditionally, which will panic ifcis nil.🐛 Proposed fix
func GetPreferredChannelByAffinity(c *gin.Context, modelName string, usingGroup string) (int, bool) { setting := operation_setting.GetChannelAffinitySetting() if setting == nil || !setting.Enabled { return 0, false } + if c == nil { + return 0, false + } path := "" if c != nil && c.Request != nil && c.Request.URL != nil {web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx (4)
261-273: Missing error handling for cache clear operation.The
onOkcallback lacks try-catch. If the API call fails, the error propagates unhandled.🐛 Proposed fix
onOk: async () => { + try { const res = await API.delete('/api/option/channel_affinity_cache', { params: { all: true }, }); const { success, message } = res.data; if (!success) { showError(t(message)); return; } showSuccess(t('已清空')); await refreshCacheStats(); + } catch (e) { + showError(t('清空缓存失败')); + } },
292-304: Same issue: Missing error handling for rule-specific cache clear.The
onOkcallback should also wrap the API call in try-catch for consistency.🐛 Proposed fix
onOk: async () => { + try { const res = await API.delete('/api/option/channel_affinity_cache', { params: { rule_name: name }, }); const { success, message } = res.data; if (!success) { showError(t(message)); return; } showSuccess(t('已清空')); await refreshCacheStats(); + } catch (e) { + showError(t('清空缓存失败')); + } },
439-443: TTL0incorrectly renders as "-".
Number(v || 0) || '-'treats0as falsy, displaying "-" instead of "0" (which indicates "use default TTL"). This hides the intentional setting.🛠️ Proposed fix
render: (v) => { - return <Text>{Number(v || 0) || '-'}</Text>; + const ttl = v == null ? null : Number(v); + return <Text>{ttl != null && Number.isFinite(ttl) ? ttl : '-'}</Text>; },
664-677: Inconsistent error handling for single vs multiple requests.When a single request fails (line 667), it silently returns without user feedback. For multiple requests (lines 669-670), it shows an error. Both cases should inform the user.
🐛 Proposed fix
Promise.all(requestQueue) .then((res) => { - if (requestQueue.length === 1) { - if (res.includes(undefined)) return; - } else if (requestQueue.length > 1) { - if (res.includes(undefined)) - return showError(t('部分保存失败,请重试')); + if (res.includes(undefined)) { + return showError(t('部分保存失败,请重试')); } showSuccess(t('保存成功')); props.refresh(); })
| func RecordChannelAffinity(c *gin.Context, channelID int) { | ||
| if channelID <= 0 { | ||
| return | ||
| } | ||
| setting := operation_setting.GetChannelAffinitySetting() | ||
| if setting == nil || !setting.Enabled { | ||
| return | ||
| } | ||
| if setting.SwitchOnSuccess && c != nil { | ||
| if successChannelID := c.GetInt("channel_id"); successChannelID > 0 { | ||
| channelID = successChannelID | ||
| } | ||
| } | ||
| cacheKey, ttlSeconds, ok := getChannelAffinityContext(c) | ||
| if !ok { | ||
| return | ||
| } | ||
| if ttlSeconds <= 0 { | ||
| ttlSeconds = setting.DefaultTTLSeconds | ||
| } | ||
| if ttlSeconds <= 0 { | ||
| ttlSeconds = 3600 | ||
| } | ||
| cache := getChannelAffinityCache() | ||
| if err := cache.SetWithTTL(cacheKey, channelID, time.Duration(ttlSeconds)*time.Second); err != nil { | ||
| common.SysError(fmt.Sprintf("channel affinity cache set failed: key=%s, err=%v", cacheKey, err)) | ||
| } | ||
| } |
There was a problem hiding this comment.
Potential nil context dereference in getChannelAffinityContext.
RecordChannelAffinity only guards c != nil inside the SwitchOnSuccess block (line 468), but getChannelAffinityContext(c) at line 473 is called unconditionally. If c is nil, c.Get(...) inside getChannelAffinityContext will panic.
🐛 Proposed fix
func RecordChannelAffinity(c *gin.Context, channelID int) {
- if channelID <= 0 {
+ if c == nil || channelID <= 0 {
return
}
setting := operation_setting.GetChannelAffinitySetting()🤖 Prompt for AI Agents
In `@service/channel_affinity.go` around lines 460 - 487, RecordChannelAffinity
calls getChannelAffinityContext(c) without ensuring c is non-nil, which can
panic; modify the function to guard against a nil context before calling
getChannelAffinityContext (either return early if c == nil when context is
required, or make getChannelAffinityContext handle a nil *gin.Context).
Specifically, in RecordChannelAffinity (and around the setting.SwitchOnSuccess
branch) add a nil check for c before invoking getChannelAffinityContext or
update getChannelAffinityContext to safely handle nil by returning ok=false when
c is nil so RecordChannelAffinity will return gracefully.
主要更新: - feat: 磁盘请求体缓存 (QuantumNous#2780) - feat: OpenAI Response API /v1/response/compact (QuantumNous#2644) - feat: 渠道亲和性 (Channel Affinity) (QuantumNous#2669) - feat: Codex渠道支持 (QuantumNous#2652) - feat: Claude/Grok refusal reason显示 - feat: 性能监控和GC控制API - fix: 用户配额获取逻辑 (QuantumNous#2749) - fix: Gemini多工具调用索引问题 - fix: 错误时仍本地计费 冲突解决: - README.md: 保留中文版本 - go.mod: 采用上游较新版本 Co-Authored-By: Claude Opus 4.5 <[email protected]>
* feat: channel affinity * feat: channel affinity -> model setting * fix: channel affinity * feat: channel affinity op * feat: channel_type setting * feat: clean * feat: cache supports both memory and Redis. * feat: Optimise ui/ux * feat: Optimise ui/ux * feat: Optimise codex usage ui/ux * feat: Optimise ui/ux * feat: Optimise ui/ux * feat: Optimise ui/ux * feat: If the affinitized channel fails and a retry succeeds on another channel, update the affinity to the successful channel
* feat: channel affinity * feat: channel affinity -> model setting * fix: channel affinity * feat: channel affinity op * feat: channel_type setting * feat: clean * feat: cache supports both memory and Redis. * feat: Optimise ui/ux * feat: Optimise ui/ux * feat: Optimise codex usage ui/ux * feat: Optimise ui/ux * feat: Optimise ui/ux * feat: Optimise ui/ux * feat: If the affinitized channel fails and a retry succeeds on another channel, update the affinity to the successful channel
#2660


Summary by CodeRabbit
New Features
Refactor
Chores
✏️ Tip: You can customize this high-level summary in your review settings.