Skip to content

fix(dify): initialize file pointer before remote-image field assignment - #5134

Merged
seefs001 merged 1 commit into
QuantumNous:mainfrom
Pluviobyte:fix/dify-remote-image-nil-pointer-panic
Jun 4, 2026
Merged

fix(dify): initialize file pointer before remote-image field assignment#5134
seefs001 merged 1 commit into
QuantumNous:mainfrom
Pluviobyte:fix/dify-remote-image-nil-pointer-panic

Conversation

@Pluviobyte

@Pluviobyte Pluviobyte commented May 27, 2026

Copy link
Copy Markdown
Contributor

📝 变更描述 / Description

relay/channel/dify/relay-dify.gorequestOpenAI2Dify() 在第 160 行声明了 var file *DifyFile(值为 nil),随后在 media.IsRemoteImage() 分支里没有初始化 file 就直接写入字段:

var file *DifyFile
if media.IsRemoteImage() {
    file.Type = media.MimeType        // <-- nil pointer dereference
    file.TransferMode = "remote_url"
    file.URL = media.Url
}

任何包含 image_url 且 URL 以 http 开头的消息经过 Dify 渠道时都会触发:

runtime error: invalid memory address or nil pointer dereference

并被全局 panic recover 包装成 500 返回客户端。

修复方法是把字段赋值改成 composite literal,让指针在写入前指向一个真实对象,else 分支里 uploadDifyFile 返回 &DifyFile{...} 的方式一致

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)
  • ✨ 新功能 (New feature)
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

✅ 提交前检查项 / Checklist

  • 人工确认: 描述由人工撰写,未粘贴未经处理的 AI 输出。
  • 非重复提交: 已搜索 #2083 —— 无任何 open / merged PR 在修。
  • Bug fix 说明: Nil pointer dereference 是确定无争议的 bug,已关联 issue。
  • 变更理解: 改动 5 行,只把 nil 指针的字段赋值改成 composite literal;行为语义保持不变(远程图片仍以 transfer_mode=remote_url + url=... 形式被加入 difyReq.Files)。
  • 范围聚焦: 单文件、8 行新增 / 3 行删除,无其它无关改动。
  • 本地验证: go build ./relay/channel/dify/ ✅;gofmt -l 干净;go vet 输出与 main 分支一致(adaptor.go 那 2 条 unreachable code warning 是先前就存在的,本 PR 未引入新 warning)。
  • 安全合规: 不引入新凭据,不改变信任边界。

📸 运行证明 / Proof of Work

Bug 现场(来自 #2083

请求 body:

{
  "model": "your-dify-model",
  "messages": [
    {
      "role": "user",
      "content": [
        {"type": "text", "text": "describe this image"},
        {"type": "image_url", "image_url": {"url": "https://example.com/cat.png"}}
      ]
    }
  ]
}

修复前响应(500):

{
  "error": {
    "message": "Panic detected, error: runtime error: invalid memory address or nil pointer dereference",
    "type": "new_api_error"
  }
}

修复点

relay/channel/dify/relay-dify.go

-                       var file *DifyFile
-                       if media.IsRemoteImage() {
-                               file.Type = media.MimeType
-                               file.TransferMode = "remote_url"
-                               file.URL = media.Url
-                       } else {
+                       var file *DifyFile
+                       if media.IsRemoteImage() {
+                               file = &DifyFile{
+                                       Type:         media.MimeType,
+                                       TransferMode: "remote_url",
+                                       URL:          media.Url,
+                               }
+                       } else {
                                file = uploadDifyFile(c, info, difyReq.User, mediaContent)
                        }

边界行为

场景 行为
远程图片(URL 以 http:// / https:// 开头) ✅ 不再 panic;按 transfer_mode=remote_url 透传给 Dify
本地 / Base64 图片 未改动(继续走 uploadDifyFile
单条消息含多张图片 每张独立追加进 files,行为不变
无图片消息 完全不触及此代码路径

本地验证

$ GOTOOLCHAIN=go1.25.1 go build ./relay/channel/dify/
(success)
$ GOTOOLCHAIN=go1.25.1 gofmt -l relay/channel/dify/relay-dify.go
(no output)
$ GOTOOLCHAIN=go1.25.1 go vet ./relay/channel/dify/
relay/channel/dify/adaptor.go:36:2: unreachable code
relay/channel/dify/adaptor.go:112:2: unreachable code
(pre-existing on main; not introduced by this PR)

备注

dify 包内目前没有单元测试基础设施(无 *_test.go),且 requestOpenAI2Dify 依赖 gin.Contextrelaycommon.RelayInfo,单测改造成本超出本 PR 的范围。如果维护者希望补回归测试,我可以另起 PR 引入 httptest + mock。

Made with Cursor

Summary by CodeRabbit

  • Bug Fixes
    • Fixed a crash that could occur when processing remote images, improving application stability and ensuring uninterrupted image uploads.

Review Change Stack

`requestOpenAI2Dify()` declared `var file *DifyFile` and then, in the
`media.IsRemoteImage()` branch, wrote directly to `file.Type`,
`file.TransferMode`, and `file.URL` without ever pointing `file` at a
real value. Any chat completion sent through a Dify channel that
contained an `image_url` whose URL starts with `http` therefore
triggered:

  runtime error: invalid memory address or nil pointer dereference

and was returned to the caller as:

  {"error":{"message":"Panic detected, ...","type":"new_api_error"}}

The fix mirrors the upload path (which already returns a `*DifyFile`
via `uploadDifyFile`): construct the value explicitly with a
composite literal so the pointer is non-nil before the field writes.

Fixes QuantumNous#2083

Co-authored-by: Cursor <cursoragent@cursor.com>
@coderabbitai

coderabbitai Bot commented May 27, 2026

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a805ec89-485d-4b71-81a2-b57658bdee62

📥 Commits

Reviewing files that changed from the base of the PR and between 5b86ce0 and 99b5d34.

📒 Files selected for processing (1)
  • relay/channel/dify/relay-dify.go

Walkthrough

The pull request fixes a runtime panic in the Dify relay handler. When processing remote images in OpenAI-format requests, the code now properly initializes the DifyFile struct before populating its fields, preventing a nil-pointer dereference that occurred in the previous uninitialized-variable approach.

Changes

Remote Image Handling in Dify Relay

Layer / File(s) Summary
Remote image DifyFile initialization
relay/channel/dify/relay-dify.go
The remote-image branch in requestOpenAI2Dify constructs a DifyFile instance with Type, TransferMode, and URL fields populated from the remote image metadata, fixing a nil-pointer dereference that occurred when assigning to an uninitialized variable.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

🐰 A pointer once wandered, uninitialized and lost,
Through Dify's remote images it stumbled and tossed,
But now it's constructed with proper care,
The struct is born before dereferencing there! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 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 (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main fix: initializing a file pointer before assigning remote-image fields in the Dify relay, which directly addresses the nil pointer dereference issue.
Linked Issues check ✅ Passed The code change directly resolves the nil pointer panic reported in issue #2083 by initializing the file pointer with the DifyFile struct for remote images, preventing runtime errors on image_url requests.
Out of Scope Changes check ✅ Passed All changes are narrowly focused on fixing the nil pointer dereference in the remote-image handling path; no unrelated modifications or scope creep is present.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@panjinhe panjinhe left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reviewed by Codex: small focused fix, checks passing.

@panjinhe

Copy link
Copy Markdown

Please disregard my previous approval on this PR. It was submitted by mistake while I was checking the wrong repository.

@seefs001
seefs001 merged commit 3aa113b into QuantumNous:main Jun 4, 2026
2 checks passed
Soein added a commit to Soein/new-api that referenced this pull request Jun 6, 2026
… id 等)

主要变更(QuantumNous/new-api → adc390c):
- feat: 渠道被禁用后可配置是否清空渠道粘性 (QuantumNous#5306)
- feat(web): profile 页显示 user id (QuantumNous#5317)
- fix: 复用 channel handler 的 stream scanner buffer (QuantumNous#5225)
- fix: 收窄 OpenAI o 系列模型适配范围 (QuantumNous#5293)
- fix(relay): GLM Anthropic 兼容避免 chunked encoding (QuantumNous#5307)
- fix: 新增 relay idle 连接超时配置 (QuantumNous#5309)
- fix: 限制匿名请求体大小 (QuantumNous#5244)
- fix(distributor): 修复 video generations task_id 模型解析 (QuantumNous#5133)
- fix(dify): 远程图片字段赋值前初始化 file pointer (QuantumNous#5134)
- fix(i18n): 优化 thinking adapter 文案 (QuantumNous#5242)

去合规一致性:上游未触及任何合规文件,合并完整保留本地去合规状态
(payment_setting.go / payment-settings-section.tsx / recharge-form-card.tsx /
risk-acknowledgement-dialog.tsx 均未被改动)。

i18n:web/default 6 语言(en/zh/fr/ja/ru/vi)key 并集三路合并 + i18n:sync
规范化,4584 keys/语言,missing/extras/untranslated 全为 0。

验证:go build ./... ✅ + bun run typecheck ✅
Ember-Moth pushed a commit to Ember-Moth/new-api that referenced this pull request Jun 7, 2026
szxufan pushed a commit to szxufan/new-api that referenced this pull request Jun 9, 2026
OuYang-HX pushed a commit to OuYang-HX/new-api that referenced this pull request Jun 13, 2026
ruanhangjian pushed a commit to ruanhangjian/new-api that referenced this pull request Jul 11, 2026
zhaodechao2008 pushed a commit to zhaodechao2008/new-api that referenced this pull request Jul 27, 2026
330079598 pushed a commit to 330079598/new-api that referenced this pull request Aug 19, 2026
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.

请求配置在newapi中的dify接口报错new_api_panic

3 participants