Skip to content

chore(sync): merge upstream - #16

Merged
Chloemlla merged 6 commits into
Chloemlla:mainfrom
QuantumNous:main
Aug 18, 2026
Merged

Chloemlla merged 6 commits into
Chloemlla:mainfrom
QuantumNous:main

Conversation

@Chloemlla

Copy link
Copy Markdown
Owner

Automated upstream sync by fork-sync.

  • Parent: QuantumNous main
  • Base: Chloemlla/new-api main

If this PR has conflicts, please resolve manually. Clean PRs are auto-merged.

* test(web): standardize frontend tests on Vitest

- configure Vitest, jsdom, and React Testing Library with shared test scripts.
- migrate existing node:test suites to the Vitest runner.
- rewrite JsonCodeEditor component tests with RTL and remove the direct happy-dom dependency.

* fix(ci): run frontend tests with Vitest

- invoke the configured Vitest script so browser test setup loads in CI.
- migrate remaining node:test suites to Vitest lifecycle APIs.

* test(web): use shared jsdom environment for component tests

- migrate usage cost and tool price tests to React Testing Library.
- remove duplicate happy-dom globals and rely on the configured Vitest setup.

* test(web): verify behavior with shared vitest setup

- replace Node test assertions with Vitest expect across frontend suites.
- migrate Keys component tests to React Testing Library interactions.
- centralize jsdom browser mocks for consistent component execution.

* fix(web): unblock frozen installs and Vitest CI

- sync dompurify 3.4.13 metadata into the Bun lockfile.
- replace the bun:test and happy-dom redemption harness with Vitest and RTL.
- preserve quota conversion, error feedback, and stale-response coverage in jsdom.
@coderabbitai

coderabbitai Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Important

Review available on request

  • 🔍 Trigger review

Reviews should be triggered manually for repositories with fewer than 10 stars. Select Trigger review above or comment @coderabbitai review to review the latest changes. For a full review, comment @coderabbitai full review.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 908c4358-7c36-4b1b-b08c-4a7ed15edd9a


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.

@monkeyscan

monkeyscan Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

PR Title: chore(sync): merge upstream

Commit: 3dda1d5

本次变更将 OpenAI 函数工具 parameters 到 Claude input_schema 的归一化逻辑抽取为共享函数 FunctionParametersToInputSchema(位于 relaykit/relayconvert/internal/shared/claude/schema.go),oai_chat 与 oai_responses 两条转换路径均改用它,并删除了 oai_responses 中行为等价的本地实现;同时调整了 oai_chat 的工具过滤条件,使无参数(parameters 为 nil)的 function 类型工具不再被丢弃,并新增了对应回归测试。

整体评估:归一化逻辑合理,修复了旧 oai_chat 实现中 params["type"].(string) 在非字符串 type 下的 panic,并为缺失 type/properties 时生成 Claude 要求的默认值(object/空 properties);oai_responses 路径行为等价,无回归。新增文件仅依赖标准库,且 shared/claude 包已存在(已导出 MapOpenAIToolChoice、ErrMissingMaxTokens),不影响 relaykit 模块独立性。测试使用 require/assert,符合项目规范。

主要关注点:oai_chat 新的过滤条件 if _, ok := tool.Function.Parameters.(map[string]any); !ok && tool.Type != "function" 意味着当 tool.Type=="function" 且 Parameters 为非 map 非 nil(如 JSON 字符串形式的 schema)时,工具会被保留,但共享 helper 会静默丢弃该参数定义并生成空 schema {type:object, properties:{}}。旧行为是直接丢弃该工具。新行为可能让上游 Claude 误以为该工具无参数,并在模型调用时以空参数执行,导致工具执行失败。建议仅对 nil 参数(真正无参)或 map 参数保留工具。

* refactor: advanced custom channel route editor

* fix(channels): show raw balance response from balance cell
@monkeyscan

monkeyscan Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

PR Title: chore(sync): merge upstream

Commit: 2b0efd8

本 PR 为 advanced custom(渠道类型 58)新增余额查询能力,并重构了前端高级自定义路由编辑器。

后端改动:

  • controller/channel-billing.go 新增 fetchAdvancedCustomBalance:通过 advancedcustom.Adaptor.BuildBalanceRequest 访问管理员配置的 /v1/dashboard/billing/credit_grants 余额路由;解析 OpenAI credit_summary 格式,校验 total_available(>=0、非 NaN/Inf)、响应上限 256KB;格式无法识别时回退返回缩进后的原始 JSON(raw_response)。updateChannelBalance 返回值改为 channelBalanceResult{Balance, RawResponse},UpdateChannelBalance 接口在 raw_response 存在时不再返回 balance 字段;updateAllChannelsBalance 仅在 RawResponse 为空时才按 Balance<=0 触发自动禁用。
  • controller/channel_upstream_update.go 新增 sanitizeAdvancedCustomRequestError,对请求错误中 URL 查询参数(可能内嵌扩展后的 api_key)进行脱敏,并接入通用 fetchChannelUpstreamModelIDs 错误路径(对无查询参数的标准渠道行为不变)。
  • relaykit/dto/channel_settings.go 新增 AdvancedCustomBalancePath 常量、BalanceRoute() 查找,以及 Validate() 对余额路由的约束(唯一、models 为空、converter=none、upstream_path 不含 {model}),与 model list 路由对称;relaykit 仍保持独立可构建。
  • relay/channel/advancedcustom/adaptor.go 通过共享 buildManagementRequest 实现 BuildModelListRequest/BuildBalanceRequest,Query 类型鉴权由 buildRouteURL 处理(有测试覆盖)。

前端改动:

  • advanced-custom-editor-dialog.tsx 重构为 Forwarding/Model List/Balance/Full JSON 四个标签页;模板替换改为 replaceAdvancedCustomForwardingRoutes(保留管理路由);新增 ManagementRouteEditor;validateAdvancedCustomConfig 同步支持余额路由约束(balanceRouteIndex 已正确声明)。
  • balance-query-dialog.tsx 支持展示 raw_response(CodeBlock + Alert);BalanceCell 在收到 raw_response 时打开对话框并 setCurrentRow。
  • 各语言 i18n 同步更新。

整体评估:改动结构清晰,后端/前端对管理路由的约束一致,错误脱敏与响应上限处理到位,新增测试覆盖了路由校验与 URL 构建。主要缺口是新的 fetchAdvancedCustomBalance 响应解析/边界逻辑(credit_summary 识别、total_available 校验、256KB 上限、raw 回退、条件落库)没有任何直接单元测试,存在明确的回归风险。

claudeTool.InputSchema[key] = value
}
claudeTools = append(claudeTools, &claudeTool)
if _, ok := tool.Function.Parameters.(map[string]any); !ok && tool.Type != "function" {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

oai_chat 转换:type=="function" 且 parameters 为非 map 非 nil 时,工具被保留但参数 schema 被静默丢弃

新过滤条件 if _, ok := tool.Function.Parameters.(map[string]any); !ok && tool.Type != "function" { continue } 只在 parameters 非 map 且 type 非 function 时才跳过工具。因此当 tool.Type == "function" 且 Parameters 是 JSON 字符串/数组等非 map、非 nil 值时,工具会被保留;随后 sharedclaude.FunctionParametersToInputSchema 对非 map 输入直接返回空 schema {type:"object", properties:{}},原始参数定义被静默丢弃。旧实现遇到非 map parameters 会直接丢弃该工具。行为差异:此前模型完全看不到该工具(安全降级);现在 Claude 会收到一个 input_schema 为空的工具,认为其无参数,模型可能以空参数调用它,导致下游工具执行失败或产生错误行为。鉴于本 PR 正是为兼容客户端发送的非标准工具形态(无参工具)而设,同属非标准形态的字符串化 schema 输入也是真实可达的。

Problem code:

Changed code at relaykit/relayconvert/internal/oai_chat/to_claude_messages_req.go:35-36

Recommendation:
将"保留无参工具"的范围限定在 Parameters 为 nil(真正无参)或 map 的情形:当 parameters 非 map 且非 nil 时沿用旧行为丢弃,避免以伪造的空 schema 把工具暴露给上游。若希望兼容字符串化 schema,应在 FunctionParametersToInputSchema 中对字符串参数尝试反序列化,而非静默忽略。建议补充 tool.Type=="function" 且 parameters 为字符串时的用例,锁定期望行为。

Suggested diff:

for _, tool := range textRequest.Tools {
    if _, ok := tool.Function.Parameters.(map[string]any); !ok &&
        (tool.Function.Parameters != nil || tool.Type != "function") {
        continue
    }
    claudeTools = append(claudeTools, &dto.Tool{
        Name:        tool.Function.Name,
        Description: tool.Function.Description,
        InputSchema: sharedclaude.FunctionParametersToInputSchema(tool.Function.Parameters),
    })
}

}

func updateChannelBalance(channel *model.Channel) (float64, error) {
func fetchAdvancedCustomBalance(channel *model.Channel) (channelBalanceResult, error) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

新增的 fetchAdvancedCustomBalance 响应解析与边界逻辑缺少直接单元测试

本 PR 新增的 fetchAdvancedCustomBalance 包含非平凡且有回归风险的逻辑:credit_summary 对象识别、total_available 数值校验(>=0、非 NaN/Inf)、256KB 响应上限(LimitReader+1 的边界判断)、解析失败时回退返回缩进后的原始 JSON、以及仅在成功解析时调用 channel.UpdateBalance。这些逻辑完全没有任何单元测试——PR 只添加了 relaykit 路由约束测试和 adaptor 的 URL 构建测试,均未触及该函数的解析/回退/上限行为。按 AGENTS.md 的测试标准,这类解析与边界逻辑(例如误判 credit_summary 格式、超大/负数 total_available 的落库、响应尺寸上限的 off-by-one)出现回归会直接影响真实用户的余额展示与后台自动禁用行为,具有明确的回归风险。

Problem code:

Changed code at controller/channel-billing.go:372

Recommendation:
为 fetchAdvancedCustomBalance 的解析/回退逻辑补充表驱动单元测试(可将响应解析部分抽取为纯函数便于测试),覆盖:合法 credit_summary(total_available 数值)→ 正确解析并触发 UpdateBalance;非 credit_summary 但合法 JSON → 返回 raw_response 且不更新余额;total_available 为负数/NaN/Inf/超大数值 → 回退 raw_response;响应超过 256KB → 返回明确错误;非法 JSON → 返回明确错误。

* feat: channel test

* fix: code smell
@monkeyscan

monkeyscan Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

PR Title: chore(sync): merge upstream

Commit: 4add708

本 PR 为渠道自动测试(channel test)引入可配置的并发数(1–32,默认 1)。后端:新增 MonitorSetting.ChannelTestConcurrency 字段、NormalizeChannelTestConcurrency 归一化、ValidateChannelTestConcurrency 校验,并在 option 更新路径(model/option.go)挂钩校验;将原先顺序执行的 performChannelTests 重构为有界并发工作池 runChannelTestWorkers,保留 ctx 取消语义、RequestInterval 节流与进度上报,并把单条渠道健康检查逻辑抽取为 testChannelForHealthCheck。前端:路由可靠性设置区新增并发数字段,zod 校验 1–32,同步更新默认值、类型、分区注册表与 en/fr/ja/ru/vi/zh-TW/zh 多语言文件。测试:新增工作池并发上限与取消行为测试、配置归一化/校验测试,均为确定性测试。评估:整体实现质量高。工作池并发/取消逻辑经推演正确(无死锁、结果聚合串行化);配置流转(前端 number → 控制器转字符串 → Atoi 校验 → config 反射写入 int 字段)一致;前端类型流与现有数值型字段一致;i18n key 齐全。仅发现一个低严重度并发问题:GetMonitorSetting() 每次调用都对包级全局 monitorSetting 做无锁写入(本次新增 ChannelTestConcurrency 字段的写回),与任务运行器读取、option 更新路径的反射写入并发执行,构成 Go 数据竞争(延续既有模式但新增了该字段的读/写点)。

default:
monitorSetting.ChannelTestMode = ChannelTestModeScheduledAll
}
monitorSetting.ChannelTestConcurrency = NormalizeChannelTestConcurrency(monitorSetting.ChannelTestConcurrency)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

GetMonitorSetting() 对全局 monitorSetting 的无锁写入扩展至新字段,构成数据竞争

GetMonitorSetting() 每次被调用都会在无任何同步的情况下直接改写包级全局变量 monitorSetting:本次改动新增 monitorSetting.ChannelTestConcurrency = NormalizeChannelTestConcurrency(monitorSetting.ChannelTestConcurrency) 这一写回语句,且 runChannelTestTask 在系统任务运行器 goroutine 中读取该字段。同时,配置更新路径 model/option.go 的 handleConfigUpdate -> UpdateConfigFromMap 会在不加锁的情况下通过反射写入同一个 monitorSetting 结构体(setting/config/config.go 的 updateConfigFromMap 未持有配置管理器互斥锁,GetMonitorSetting 也未使用该锁)。系统任务运行器、定时调度器、手动触发与 HTTP 配置更新可并发执行,因此该新增字段存在真实的读-写/写-写数据竞争(Go 内存模型下为未定义行为)。虽然该无锁可变模式在 PR 之前已存在(ChannelTestMode 等字段),但本次改动为该函数新增了一处无锁写回和一处并发读取点。实际影响有限:可能读到过期或撕裂的并发值,随后会被 NormalizeChannelTestConcurrency 钳制到 [1,32],但仍属于本次改动引入的并发正确性缺陷。

Problem code:

Changed code at setting/operation_setting/monitor_setting.go:61

Recommendation:
不要在 GetMonitorSetting() 中原地修改全局 monitorSetting。建议改为在函数内构造副本并在副本上完成归一化后返回(或仅返回归一化结果而不写回全局),使每次调用不再产生写操作,从而消除该字段上的数据竞争;同时避免返回值指向全局可变结构体。

Suggested diff:

func GetMonitorSetting() *MonitorSetting {
	// ... env 覆盖逻辑不变 ...
	normalized := monitorSetting
	switch normalized.ChannelTestMode {
	case ChannelTestModeAutoBanOnly, ChannelTestModePassiveRecovery:
	default:
		normalized.ChannelTestMode = ChannelTestModeScheduledAll
	}
	normalized.ChannelTestConcurrency = NormalizeChannelTestConcurrency(normalized.ChannelTestConcurrency)
	return &normalized
}

…or (#6895)

* feat(web): fade in newly streamed response words

Animate only new word-level deltas while markdown is still streaming, and
cache markdown-it instances per parser id so concurrent Response trees do
not rebuild or reparse on every render.

* fix(web): keep CodeMirror editor alive across keystroke re-renders

Deliver onKeyDown through a ref instead of the extensions memo so a new
handler identity no longer tears down the EditorView, which reset the
cursor to the document start and made typing appear right-to-left.

* feat(web): add unsaved changes confirmation dialog in PlaygroundMessageEditor

Implement a confirmation dialog to warn users about unsaved changes when attempting to leave the editor. This includes handling the beforeunload event to prevent accidental navigation away from the editor. Additionally, add tests to verify the dialog's behavior under various scenarios.

* test(web): cover beforeunload guard and fade hydration suppression

Address review feedback: add regression tests for the unsaved-changes
beforeunload guard and the first-render fade suppression of hydrated
content, and annotate getCachedMarkdown's return type.
@monkeyscan

monkeyscan Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

PR Title: chore(sync): merge upstream

Commit: 137d117

本 PR 为流式响应文本新增逐词淡入动画(response-fade.ts 状态机 + response-renderer/response.tsx 集成 + CSS keyframes),并为 playground 消息编辑器加固未保存更改保护(ConfirmDialog 离开确认 + beforeunload 拦截),同时修复 CodeMirror 编辑器因 onKeyDown 每次渲染重建导致的光标重置问题(改为 ref 传递 handler),并为 reasoning 内容引入独立 parserId 缓存与 final 联动。

整体设计质量较高:fade 状态机采用 render 阶段 stage、layout effect 阶段 commit 的两阶段提交,可容忍 React 丢弃渲染;偏移量驱动的分段在追加型流式场景下工作正常;skip-list(代码/数学/HTML/图片/details)子树不计入偏移量,使偏移空间在多数场景下保持稳定;新增测试覆盖了核心分类逻辑、渲染行为与编辑器防抖。code-block.tsx 的 onKeyDown ref 修复正确,readOnly 代码块通过可空 ref 安全降级。

提交了 1 条功能性发现:Response 的 fade 状态在 final=true(流式结束)后从不重置,同一组件实例被复用于新一轮流式(如同一消息重新生成/重试)时,新内容会被残留的 prevCount 误判为已展示而不触发淡入;建议在非动画渲染路径中重置 fade 状态。

@monkeyscan

monkeyscan Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

PR Title: chore(sync): merge upstream

Commit: f116414

本次变更聚焦于修复 OpenAI Responses 格式下缓存 token 未计入缓存折扣的计费问题(QuantumNous#6892)。

改动内容:

  1. service/billing_usage.go 的 usageFromOpenAIBillingUsage:新增对 InputTokensDetails(Responses 格式的 input_tokens_details)的归一化,将 cached/cached_creation/cache_write/text/image/audio token 明细回填到 PromptTokensDetails(仅在对应字段为 0 时回填,避免覆盖 canonical 值);并在 PromptTokensDetails.CachedTokens 为 0 时回退使用 PromptCacheHitTokens。
  2. service/text_quota_test.go:新增 3 个测试,覆盖 Responses 主路径配额计算(40 cached → 90 quota)、混合 canonical/input 明细的“不覆盖 canonical”语义、以及 Chat 路径 PromptCacheHitTokens 回退。

审查评估:

  • 主路径正确:Responses usage 的 input_tokens 含缓存命中,将其计入 CacheTokens 并在配额计算中按缓存比例计费、从基数中扣减,语义与既有 Chat 路径的 prompt_tokens_details.cached_tokens 一致。
  • 计费安全:新引入的 CachedTokens/CacheWriteTokens 由上游控制,calculateTextQuotaSummary 中既有的负余量钳制(max(...,0),已有测试 TestCalculateTextQuotaSummaryBillsOpenAICacheWriteTokens 验证)可防止负 charge;配额转换走 common.*Checked 助手,符合计费安全不变量。
  • 测试质量:使用 require/assert,断言精确,覆盖了不覆盖 canonical、回退、配额算术等多条路径。
  • 未发现高置信度的正确性、安全或回归问题。混合来源(PromptTokensDetails 与 InputTokensDetails 同时非零)的逐字段合并仅在异常上游数据下可达,且该语义已被测试显式固化为“不覆盖 canonical”设计,属于防御性处理,不构成可报告的缺陷。


return parseMarkdownToStructure(content, markdown, {
final: props.final ?? true,
final: isFinal,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Response 的 fade 状态在流式结束(final=true)后不重置,实例复用进入新一轮流式时新内容不会淡入

Response 的 fadeStateRef 在组件实例首次渲染时创建后从不重置;useLayoutEffect 仅在 shouldAnimate(final=false)时提交,而 commitRun 只更新 prevCount/active/firstRun,没有任何清空逻辑。因此当一个已挂载的 Response 实例先以 final=false 流式播放、随后以 final=true 渲染为已结束内容(此时 render 走非动画分支且 layout effect 直接 return,状态被完整保留),再因同一消息的重新生成/重试而以 final=false 开始新一轮流式时,classifyValue 会把新内容中 start 小于旧 prevCount 的所有词判定为已展示(start >= state.prevCount 不成立、state.active 中旧条目已被裁剪),全部走 animated=false 分支——新一轮流式的文字不会淡入,直到新内容长度超过旧内容。这与本 PR 在 reasoning.tsx 中引入 final={!isStreaming} 的切换路径直接相关,且 fade 状态机没有为跨流式生命周期提供重置入口。

Problem code:

Changed code at web/src/components/ai-elements/response.tsx:73

Recommendation:
在流式生命周期边界处重置 fade 状态。最小改动:在 useLayoutEffect 中 when !shouldAnimate(即 final=true,渲染已结束内容)时,将 fadeState 重置为初始值(prevCount=0、active.clear()、firstRun=true、pending=null),因为已结束渲染不使用 fade 状态;或在新一轮流式开始时(检测到 final 由 true 变 false 且内容不是上一轮提交内容的严格后缀)重置。这样同一实例被复用于重新生成/重试时,新内容会按全新流式正确淡入。

Suggested diff:

diff --git a/web/src/components/ai-elements/response.tsx b/web/src/components/ai-elements/response.tsx
--- a/web/src/components/ai-elements/response.tsx
+++ b/web/src/components/ai-elements/response.tsx
@@ -86,6 +86,16 @@ export const Response = memo((props: ResponseProps) => {
   useLayoutEffect(() => {
     if (!shouldAnimate) {
+      // 已结束渲染不使用 fade 状态:重置以避免实例被复用(如同一消息重新生成)
+      // 时,新一轮流式内容被残留的 prevCount 误判为已展示而不淡入。
+      const fadeState = fadeStateRef.current
+      if (fadeState != null) {
+        fadeState.prevCount = 0
+        fadeState.active.clear()
+        fadeState.firstRun = true
+        fadeState.pending = null
+      }
       return
     }
     const fadeState = fadeStateRef.current
     if (fadeState == null) {
       return
     }
     commitRun(fadeState)
   })

@Chloemlla
Chloemlla merged commit 92dc724 into Chloemlla:main Aug 18, 2026
1 check passed
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.

5 participants