Skip to content

Conversation

@SodaACE
Copy link

@SodaACE SodaACE commented Aug 22, 2025

Types

  • 🎉 New Features
  • 🐛 Bug Fixes
  • 📚 Documentation Changes
  • 💄 Code Style Changes
  • 💄 Style Changes
  • 🪚 Refactors
  • 🚀 Performance Improvements
  • 🏗️ Build System
  • ⏱ Tests
  • 🧹 Chores
  • Other Changes

Background or solution

fix #3615
f04a64cec0c1c8e0a6ac2216e36b19bd
在 $ensureFileExis方法里的targetPath原来类似于图片上这种,在创建文件写入流会报错,报错原因是路径生成错误。

Changelog

修复在windows上,拖拽文件到IDE中,文件损坏的问题

Summary by CodeRabbit

  • Bug Fixes
    • 修复文件拖放时的目标路径解析问题,解决在 Windows 等平台因路径格式不兼容导致无法创建/写入文件的情况,提升稳定性与跨平台兼容性。

@CLAassistant
Copy link

CLAassistant commented Aug 22, 2025

CLA assistant check
All committers have signed the CLA.

@CLAassistant
Copy link

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.


lintao4 seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@opensumi opensumi bot added the 🐞 bug Something isn't working label Aug 22, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 22, 2025

Walkthrough

在 FileDropService 中,将两个内部目标路径的计算从 Uri.file(...).path 切换为 Uri.file(...).fsPath,其余写入流创建、写入与关闭逻辑未改动;无公开 API 变更。

Changes

Cohort / File(s) Summary
文件拖拽服务路径计算更新
packages/addons/src/node/file-drop.service.ts
在 $ensureFileExist 与 $writeStream 中,将目标路径从 .path 改为 .fsPath,用于生成本地文件系统路径;其余逻辑(创建/缓存 WriteStream、按 'binary' 写入、完成时关闭与移除)保持不变。

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Assessment against linked issues

Objective Addressed Explanation
修复从操作系统文件管理器拖拽到文件树后文件内容丢失的问题(#3615 仅更换为 fsPath 涉及路径规范化,疑似面向 Windows,但缺少验证与测试覆盖,无法确认是否完全解决所有场景。

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 0

🧹 Nitpick comments (3)
packages/addons/src/node/file-drop.service.ts (3)

12-16: 建议:在创建写入流前加固路径安全与错误处理

当前直接 path.join(targetDir, fileName) 没有防目录穿越(如 ..)、也未确保父目录存在、且对 createWriteStreamerror 事件未做清理,可能导致:

  • 文件被写到 targetDir 之外(安全/多工作区隔离风险)。
  • 目录不存在时创建流失败、Map 中遗留无效句柄。
  • 异常未被及时清理,造成资源泄漏。

可在不改变对外行为的前提下,局部增强健壮性(保持 .fsPath 以兼容 Windows):

-  async $ensureFileExist(fileName: string, targetDir: string): Promise<boolean> {
-    const targetPath = Uri.file(path.join(targetDir, fileName)).fsPath;
-    this.writeableStreams.set(targetPath, fs.createWriteStream(targetPath));
-    return true;
-  }
+  async $ensureFileExist(fileName: string, targetDir: string): Promise<boolean> {
+    const base = path.resolve(targetDir);
+    const abs = path.resolve(base, fileName);
+    if (!abs.startsWith(base + path.sep)) {
+      throw new Error('Invalid fileName: outside targetDir');
+    }
+    await fs.promises.mkdir(path.dirname(abs), { recursive: true });
+    const targetPath = Uri.file(abs).fsPath;
+    const stream = fs.createWriteStream(targetPath);
+    // 出错时及时清理,避免 Map 残留
+    stream.once('error', () => this.writeableStreams.delete(targetPath));
+    this.writeableStreams.set(targetPath, stream);
+    return true;
+  }

18-33: 建议:修正写入流程以避免数据损坏或丢失(ArrayBuffer 处理、编码、end vs close、未初始化流)

  • chunk 类型包含 ArrayBuffer 时,直接传给 stream.write 可能抛错;应先转 Buffer
  • 对字符串使用 'binary' 编码容易引入内容歧义;建议尽量以 Buffer 写入,避免编码参与。
  • close() 可能在缓冲区未完全刷新时关闭文件,推荐在最后一次写入后调用 end() 并在回调中清理。
  • 若未先调用 $ensureFileExiststream 为空时当前实现不会 reject,调用方无法感知失败。

可在本段内做最小入侵式调整:

-  $writeStream(chunk: string | ArrayBuffer, fileName: string, targetDir: string, done: boolean): Promise<void> {
-    const targetPath = Uri.file(path.join(targetDir, fileName)).fsPath;
-    const stream = this.writeableStreams.get(targetPath);
-    return new Promise((resolve, reject) => {
-      stream?.write(chunk, 'binary', (err) => {
-        if (err) {
-          reject(err);
-        }
-        resolve();
-        if (done) {
-          stream.close();
-          this.writeableStreams.delete(targetPath);
-        }
-      });
-    });
-  }
+  $writeStream(chunk: string | ArrayBuffer, fileName: string, targetDir: string, done: boolean): Promise<void> {
+    const base = path.resolve(targetDir);
+    const abs = path.resolve(base, fileName);
+    if (!abs.startsWith(base + path.sep)) {
+      return Promise.reject(new Error('Invalid fileName: outside targetDir'));
+    }
+    const targetPath = Uri.file(abs).fsPath;
+    const stream = this.writeableStreams.get(targetPath);
+    if (!stream) {
+      return Promise.reject(new Error('WriteStream not initialized'));
+    }
+    return new Promise((resolve, reject) => {
+      const data = typeof chunk === 'string' ? Buffer.from(chunk, 'binary') : Buffer.from(chunk);
+      stream.write(data, (err) => {
+        if (err) return reject(err);
+        if (done) {
+          stream.end(() => {
+            this.writeableStreams.delete(targetPath);
+            resolve();
+          });
+        } else {
+          resolve();
+        }
+      });
+    });
+  }

18-33: 回归验证建议:覆盖 Windows 与非 Windows 路径与内容一致性

为确保此次修复不引入回归,建议最小用例集:

  • Windows 10/11(含不同盘符):分别将文本文件与二进制文件(如 PNG)拖入文件树,打开后与源文件做哈希比对应一致。示例(PowerShell):Get-FileHash .\source.png; Get-FileHash .\workspace\target.png
  • 包含空格与非 ASCII 文件名(如中文)。
  • 目标目录包含/不包含预创建子目录(验证递归创建逻辑,如采纳上述建议)。
  • 未调用 $ensureFileExist 直接 $writeStream 的错误反馈是否符合预期(应明确失败)。

如需,我可以补充一个最小的集成测试(利用临时目录 + 伪造 chunk 数据)以自动化覆盖上述场景。

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7dfa870 and 8a11e83.

📒 Files selected for processing (1)
  • packages/addons/src/node/file-drop.service.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: weiwen111
PR: opensumi/core#4139
File: packages/core-browser/src/window/window.service.ts:0-0
Timestamp: 2024-10-30T12:51:05.546Z
Learning: 在 Web 环境中,使用 `workspaceUri.path.toString()` 获取路径可能仍然包含 `file://` 前缀,应该使用 `workspaceUri.fsPath` 来获取不含 `file://` 前缀的路径。
🧬 Code graph analysis (1)
packages/addons/src/node/file-drop.service.ts (1)
scripts/download.js (1)
  • targetDir (14-14)
🔇 Additional comments (1)
packages/addons/src/node/file-drop.service.ts (1)

12-16: Windows 路径修复方向正确:改用 fsPath 规避盘符前置斜杠与 file:// 前缀问题

在 Windows 上由 Uri.file(...).path 切换为 .fsPath 能避免诸如 /C:/... 这类路径导致的写入失败,和我们既有经验一致(此前在 Web 环境也有类似结论:应使用 fsPath 获取无 file:// 前缀的路径)。本次修改对定位到的问题是有效的。

Copy link
Member

@erha19 erha19 left a comment

Choose a reason for hiding this comment

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

LGTM

@codecov
Copy link

codecov bot commented Aug 22, 2025

Codecov Report

❌ Patch coverage is 0% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 52.61%. Comparing base (7dfa870) to head (8a11e83).

Files with missing lines Patch % Lines
packages/addons/src/node/file-drop.service.ts 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4624      +/-   ##
==========================================
+ Coverage   52.59%   52.61%   +0.01%     
==========================================
  Files        1686     1686              
  Lines      104362   104362              
  Branches    22682    22682              
==========================================
+ Hits        54894    54905      +11     
+ Misses      41097    41087      -10     
+ Partials     8371     8370       -1     
Flag Coverage Δ
jsdom 48.14% <0.00%> (+<0.01%) ⬆️
node 12.03% <0.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] 操作系统文件资源管理器中选中文件拖入到opensumi ide文件树中内容消失

3 participants