Skip to content

Conversation

@dingyi222666
Copy link
Member

This PR introduces file message transformation support specifically for the OneBot platform, allowing the system to handle file elements in chat messages.

New Features

  • OneBot File Support: Implemented readPlatformFile to fetch file URLs from OneBot (both private and group chats).
  • File Interceptor: Added a file interceptor to the message transformer that downloads files and stores them via chatluna_storage.
  • Message Content Enhancement: Automatically appends the filename and stored URL to the chat message content.

Bug fixes

None

Other Changes

  • Added koishi-plugin-adapter-onebot to packages/core devDependencies for type support.

- Add file interceptor to message transformer
- Support downloading files from OneBot platform (group and private)
- Integrate with chatluna_storage for temporary file handling
- Add koishi-plugin-adapter-onebot to devDependencies
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 29, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

在聊天消息读取中间件中新增对文件元素的拦截与处理:根据元素确定文件名,使用平台适配器(OneBot)获取文件 URL 或直接读取 URL,通过 HTTP 拉取并转为 Buffer 与 Base64,存为临时文件并在消息内容中追加 File 引用。

Changes

内聚组 / 文件(s) 变更摘要
文件元素处理与辅助函数
packages/core/src/middlewares/chat/read_chat_message.ts
新增文件拦截逻辑:识别文件元素、调用 readPlatformFile(ctx, session, element) 获取平台文件 URL(OneBot 支持群组/直连路径),新增 readFile(ctx, url) 执行 HTTP GET 并返回 { buffer, base64Source };将读取到的文件写入临时存储并在消息内容中追加 File: 引用。扩展导入以包含 SessionOneBotBot 类型;在读取失败时记录告警并安全返回。

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Msg as 消息处理器
    participant Detect as 元素检测器
    participant Platform as 平台适配器\n(OneBot)
    participant HTTP as HTTP 客户端
    participant Storage as 临时存储
    participant Output as 消息输出

    Msg->>Detect: 遍历消息元素
    Detect->>Detect: 识别到文件元素
    Detect->>Platform: readPlatformFile(ctx, session, element)
    Note right of Platform: 根据 session/element\n决定 OneBot 直连或群组 URL
    Platform->>HTTP: 请求文件 URL(若需通过 HTTP)
    HTTP-->>Platform: 返回文件数据/流
    Platform->>Detect: 返回 { buffer, base64Source } 或 null
    alt 成功读取
        Detect->>Storage: 写入临时文件
        Storage-->>Detect: 返回临时路径
        Detect->>Output: 在消息内容追加 `File: <path>` 引用
        Output-->>Msg: 返回更新后的消息
    else 读取失败
        Detect-->>Msg: 记录警告并跳过该元素
    end
Loading

代码审查工作量

🎯 3 (Moderate) | ⏱️ ~20 分钟

Possibly related PRs

庆祝诗

🐰✨ 文件轻敲木门来,
平台桥接把路开,
HTTP 流化成苞米,
暂存窩里暖又在,
消息里藏小小彩带 🥕🎉

Pre-merge checks and finishing touches

❌ 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%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed PR标题准确总结了主要变更:为OneBot平台添加文件消息转换功能支持,与代码更改完全一致。
Description check ✅ Passed PR描述清晰详细地关联到所有代码变更,包括OneBot文件支持、文件拦截器、消息内容增强和依赖项添加,全部相关且无误。
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/message-transformer

📜 Recent review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ff80261 and 6da2621.

📒 Files selected for processing (1)
  • packages/core/src/middlewares/chat/read_chat_message.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-12-04T20:25:49.237Z
Learnt from: dingyi222666
Repo: ChatLunaLab/chatluna PR: 653
File: packages/core/src/llm-core/platform/model.ts:169-176
Timestamp: 2025-12-04T20:25:49.237Z
Learning: In packages/core/src/llm-core/platform/model.ts, the code intentionally uses unsafe nested property access (e.g., options?.variables_hide['built']['conversationId']) without full optional chaining to enable explicit TypeErrors for debugging and diagnosis when the expected structure is missing. This fail-fast approach is preferred over silently returning undefined.

Applied to files:

  • packages/core/src/middlewares/chat/read_chat_message.ts
🧬 Code graph analysis (1)
packages/core/src/middlewares/chat/read_chat_message.ts (2)
packages/core/src/index.ts (1)
  • logger (38-38)
packages/core/src/services/types.ts (1)
  • Context (21-23)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build
  • GitHub Check: lint
🔇 Additional comments (3)
packages/core/src/middlewares/chat/read_chat_message.ts (3)

1-1: 导入语句正确。

新增的 SessionOneBotBot 类型导入是文件消息转换功能所必需的。

Also applies to: 6-6


246-251: 良好的改进:添加了缓冲区空值检查。

添加对 buffer?.buffer 的空值检查可以防止在文件读取失败时传递 nullcreateTempFile,有效避免了运行时错误。


295-321: readFile 函数实现良好。

该函数具有完善的错误处理机制,使用 try-catch 捕获异常,并在失败时返回一致的对象结构({ base64Source: null, buffer: null })。这与 readImage 函数的实现风格保持一致。


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.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @dingyi222666, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the system's capability to process file messages originating from the OneBot platform. It establishes a mechanism to intercept file elements within chat messages, retrieve their URLs from OneBot, download the files, store them using the chatluna_storage service, and then enrich the original message content with the file's name and its newly stored URL.

Highlights

  • OneBot File Handling: Introduced readPlatformFile to retrieve file URLs from OneBot private and group chats, enabling the system to access files directly from the platform.
  • File Interception and Storage: Added a file interceptor to the message transformer that automatically downloads files and stores them using the chatluna_storage service.
  • Message Content Enhancement: The system now automatically appends the filename and its newly stored URL to the chat message content, providing direct access and context.
  • Dependency Update: Added koishi-plugin-adapter-onebot to the development dependencies for improved type support related to OneBot interactions.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces file message transformation for the OneBot platform, which is a great feature. The implementation correctly adds a file interceptor to download and process files. However, I've identified a couple of critical issues that could lead to runtime errors. Specifically, there's a missing null check for the file buffer after a download attempt, and an uninitialized variable in readPlatformFile that would cause a crash for non-OneBot platforms. I've provided suggestions to fix these issues and improve code robustness.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
packages/core/src/middlewares/chat/read_chat_message.ts (1)

283-309: readFile 函数实现基本正确,但有一点建议。

当前 base64Source 被计算但在调用处并未使用(只用了 buffer)。考虑移除未使用的返回值以减少不必要的计算,或者确认后续是否会用到。

🔎 如果确认不需要 base64Source,可以简化为
 async function readFile(ctx: Context, url: string) {
     try {
         const response = await ctx.http(url, {
             responseType: 'arraybuffer',
             method: 'get',
             headers: {
                 'User-Agent':
                     'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
             }
         })

         const buffer = Buffer.from(response.data)

-        const base64 = buffer.toString('base64')
-
         return {
-            base64Source: base64,
             buffer
         }
     } catch (error) {
         logger.error(`Failed to read file from ${url}:`, error)
         return {
-            base64Source: null,
             buffer: null
         }
     }
 }
📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 28e666d and ff80261.

⛔ Files ignored due to path filters (1)
  • packages/core/package.json is excluded by !**/*.json
📒 Files selected for processing (1)
  • packages/core/src/middlewares/chat/read_chat_message.ts
🧰 Additional context used
🧬 Code graph analysis (1)
packages/core/src/middlewares/chat/read_chat_message.ts (1)
packages/core/src/index.ts (1)
  • logger (38-38)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build
  • GitHub Check: lint
🔇 Additional comments (1)
packages/core/src/middlewares/chat/read_chat_message.ts (1)

1-6: 导入更改看起来没问题。

新增的 SessionOneBotBot 类型导入是新功能所必需的。

- Add validation for file buffer and URL existence
- Add warning logs when file reading or URL retrieval fails
@dingyi222666 dingyi222666 merged commit 36eee77 into v1-dev Dec 29, 2025
5 checks passed
@dingyi222666 dingyi222666 deleted the feat/message-transformer branch December 29, 2025 18:20
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.

2 participants