Skip to content

feat: channel affinity - #2669

Merged
Calcium-Ion merged 15 commits into
QuantumNous:mainfrom
seefs001:feature/channel-affinity-codex
Jan 26, 2026
Merged

Calcium-Ion merged 15 commits into
QuantumNous:mainfrom
seefs001:feature/channel-affinity-codex

Conversation

@seefs001

@seefs001 seefs001 commented Jan 15, 2026 •

Copy link
Copy Markdown
Collaborator

#2660
image
image

Summary by CodeRabbit

  • New Features

    • Channel affinity routing with preferred-channel selection, recording, and admin-visible affinity metadata (shown as an “优选” badge in logs/UI).
    • Channel Affinity settings UI: visual/JSON rule editor, TTL/max entries, per-rule cache controls, and cache statistics.
    • New API endpoints to view and clear channel-affinity cache.
    • Admin logs now include channel affinity details.
  • Refactor

    • New hybrid Redis+in-memory caching with namespacing and flexible codecs.
  • Chores

    • Dependency updates and module version bumps.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Jan 15, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds 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

Cohort / File(s) Summary
Service (channel affinity)
service/channel_affinity.go, service/log_info_generate.go
New channel-affinity service: hybrid cache, rule matching, GetPreferredChannelByAffinity, RecordChannelAffinity, MarkChannelAffinityUsed, AppendChannelAffinityAdminInfo, cache stats/clear; log generation now appends affinity admin info.
Middleware / Distributor
middleware/distributor.go
Affinity-aware selection: try GetPreferredChannelByAffinity, validate with IsChannelEnabledForGroupModel, handle auto/group rules, mark/record affinity usage; fallback to previous random selection; records affinity after successful responses.
Controller / Relay changes
controller/relay.go, controller/channel_affinity_cache.go
processChannelError now calls AppendChannelAffinityAdminInfo; new handlers GetChannelAffinityCacheStats and ClearChannelAffinityCache.
Model validation
model/channel_satisfy.go
New exported funcs IsChannelEnabledForGroupModel and IsChannelEnabledForAnyGroupModel with cache/DB fallback and model-name normalization.
Settings / Config
setting/operation_setting/channel_affinity_setting.go
New ChannelAffinitySetting, ChannelAffinityRule, ChannelAffinityKeySource types, defaults, registration, and accessor GetChannelAffinitySetting().
API Router
router/api-router.go
Added routes: GET /api/option/channel_affinity_cache and DELETE /api/option/channel_affinity_cache.
Frontend (UI)
web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx, web/src/components/settings/ModelSetting.jsx, web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx, web/src/index.css
New SettingsChannelAffinity UI (visual/JSON rule editor, cache controls) integrated into ModelSetting; usage logs render affinity metadata for admins; styles for affinity tag added.
Cache primitives
pkg/cachex/hybrid_cache.go, pkg/cachex/namespace.go, pkg/cachex/codec.go
New generic HybridCache (Redis + in-memory hot fallback), Namespace helper, and ValueCodec implementations (Int/String/JSON).
Policy / Compatibility
relay/compatible_handler.go, service/openai_chat_responses_mode.go, service/openaicompat/policy.go, setting/model_setting/global.go, web/src/pages/Setting/Model/SettingGlobalModel.jsx
Propagate channelType through chat-completions→responses checks; add ChannelTypes and update IsChannelEnabled signature and example policy.
Relay / UX minor
web/src/components/table/channels/modals/CodexUsageModal.jsx, web/src/hooks/channels/useChannelsData.jsx
Codex usage modal refactor (loader/view split); removed inline API fetch on channel update and now opens modal without payload for certain channel types.
Deps / build
go.mod
Adds/updates multiple indirect dependencies (Prometheus libs, samber/*, others) and bumps several transitive versions.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • Calcium-Ion
  • creamlike1024

Poem

🐰 I hop through rules with a twinkle and map,
I stash preferred channels in cache for a snap,
Regex whiskers twitch while TTLs I mind,
Admin logs glow with the tracks I find,
I celebrate affinities with a carrot clap. 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: channel affinity' accurately describes the main feature being added across multiple files. The changeset introduces a comprehensive channel affinity subsystem with configuration, caching, UI components, and integration throughout the codebase.

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

✨ Finishing touches
  • 📝 Generate docstrings

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.

@seefs001 seefs001 linked an issue Jan 15, 2026 that may be closed by this pull request

@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 `@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 to MaxEntries or DefaultTTLSeconds in 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 catch block at line 185 shows a generic error message without the actual error details. Consider logging e for debugging purposes.

Proposed fix
     } catch (e) {
+      console.error('Failed to refresh cache stats:', e);
       showError(t('刷新缓存统计失败'));
     } finally {

554-566: Checking for undefined in Promise results may not catch all failures.

The check res.includes(undefined) at lines 557 and 559 assumes that failed promises return undefined. If the API wrapper throws or returns a different falsy value, errors may be silently ignored. Consider using Promise.allSettled for 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 useEffect hook references inputs in currentInputs = { ...inputs } but doesn't include inputs in the dependency array. However, since the intent is to reset inputs when props.options changes, this is actually correct behavior. Adding inputs would cause infinite loops. Consider adding a comment to clarify this intentional omission.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7768a22 and da80df4.

📒 Files selected for processing (5)
  • controller/channel_affinity_cache.go
  • router/api-router.go
  • service/channel_affinity.go
  • setting/operation_setting/channel_affinity_setting.go
  • web/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.]

GetRequestBody already implements request-level caching via c.Get(KeyRequestBody) and c.Set(KeyRequestBody, body). The body is read once and cached in the gin context for the lifetime of the request, so repeated calls to extractChannelAffinityValue with different gjson sources 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=true and rule_name parameters, 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 optionRoute group which requires RootAuth, 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, and removeKeySource functions.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Comment on lines +200 to +212
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();
},
});

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

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.

Suggested change
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.

Comment on lines +229 to +241
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();
},
});

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

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.

Suggested 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();
},
});
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.

@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 `@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
 }

Comment on lines +69 to +78
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
}

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

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.

Comment on lines +164 to +176
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)

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

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.

Suggested change
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.

Comment on lines +352 to +423
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
}

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

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.

@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

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 of record.other to avoid render crashes.
JSON.parse can throw on null/invalid payloads, which would break the logs table. Use getLogOther (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('清空缓存失败'));
+        }
       },

Comment on lines +359 to +479
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>
),
},
];

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

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).

@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/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.

Comment on lines +192 to +218
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);
}

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

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.

@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/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.

Comment on lines +660 to +672
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));

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

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.

Suggested change
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.

@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 `@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.

ClearChannelAffinityCacheAll can still panic if operation_setting.GetChannelAffinitySetting() returns nil, since getChannelAffinityCache() 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.

GetPreferredChannelByAffinity defensively extracts path and userAgent when c is non-nil, but later calls extractChannelAffinityValue(c, src) and setChannelAffinityContext(c, meta) unconditionally, which will panic if c is 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 onOk callback 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 onOk callback 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: TTL 0 incorrectly renders as "-".

Number(v || 0) || '-' treats 0 as 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();
       })

Comment on lines +460 to +487
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))
}
}

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

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.

@Calcium-Ion
Calcium-Ion merged commit d7d3a2f into QuantumNous:main Jan 26, 2026
dreamlx pushed a commit to dreamlx/new-api that referenced this pull request Feb 1, 2026
主要更新:
- 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]>
@coderabbitai coderabbitai Bot mentioned this pull request Feb 2, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Apr 18, 2026
9 tasks
@coderabbitai coderabbitai Bot mentioned this pull request Jun 27, 2026
11 tasks
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
* 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
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
* 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
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.

新版本在claudecode中使用遇到的signature报错问题

2 participants