diff --git a/AGENTS.md b/AGENTS.md index 0e1bd940..9a6ca05f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -121,6 +121,7 @@ - **构建纯度门**:client bundle 禁止 value-import `@dsh-external/*` 或非白名单 `@deepseek-ai/*`(`tsdown.config.ts` 拦截);`import type {}` 被擦除不触发——类型可共享,运行时符号不行;跨插件交互走 `ctx.betterSidebar` 方法调用。 - **懒加载 chunk**:重依赖(CodeMirror / mermaid / 19 份第三语言词典)在独立 bundle(`lib/client-.js`,0.20.0 起剩 `editor` / `mermaid` / `locale`,v0.24.x 起加 `terminal`),经 `/sidebar/bundle` 按需下发、`globalThis.__dshChunks__` 物化(`src/client/chunk-loader.ts`),**核心 bundle 禁止静态 import `src/client/chunks/*`**。chunk 名在 8 处镜像(`tsdown.config.ts` / `src/bundle-route.ts` / `src/client/chunk-loader.ts` / `package.json.files` / `scripts/package-registry.mjs` / `tests/{bundle-route,chunk-loader,chunk-artifact,manifest-consistency}.spec.ts`)——删一个 chunk 必须同步全部。 - **i18n**:词典在 `betterSidebar` 命名空间,跟随 DSH `ctx.locale`;**新增 zh key 必须同步 `src/client/locales-ja.ts` 的 ja 翻译**(否则 ja 下回退 en)。渲染 `MarkdownText` 必须经 `markdownTextProps()`(§3 第 3 条)。 +- **保存语义(编辑器的两个「不偷偷改写」保证)**:`fs.write` 在写盘**前**按磁盘现状还原文件格式——`text-encoding.ts` 的 `fileFormatOf(path)` 用一趟 64 KiB sniff 同时给出 `{ encoding, eol }`,落盘是 `encodeText(restoreEol(content, eol), encoding)`;**客户端只发送 LF 文档**(CodeMirror 没有别的行模型),行尾由服务端还原(#523 编码 / #871 行尾)。行尾口径与宿主 `edit` 工具一致(前 4096 字符多数票、孤立 `\r` 不计票也不改写、还原前先归一化以免 `\r\r\n`);新文件是 UTF-8 + LF,**不**推断项目级约定。改这条路径时 `tests/{text-encoding,fs-write-route}.spec.ts` 必须跟着红(拿掉 `restoreEol` 调用即有用例失败)。 - **皮肤契约**:视觉值只消费 `--dsw-alias-*` / `--dsw-font-*` / `--ds-*` 令牌,无硬编码颜色,**插件没有任何豁免面**——文件/文件夹图标是 DSH 官方 `FileTypeIcon` 的图形(宿主自己的调色板),插件画的每个 glyph(含内置 tab 彩色图标)颜色都来自令牌;`tests/theme.spec.ts` 同时守护「图标模块零颜色字面量」「样式表每条 `color` 解析到令牌」「没有图标数据被做成 chunk」。契约全文见[指南 §12](docs/external-plugin-guide.md),改动必须同步该节与 `tests/theme.spec.ts`(titleBar「位置兼容模式」四方案模型与 `--dsh-title-bar-strip` 让位链已整体移除,见指南 §12.1 与 [docs/plans/2026-10-05-remove-titlebar-compat-strip.md](docs/plans/2026-10-05-remove-titlebar-compat-strip.md))。 - **契约反向引用**:皮肤契约被 `src/client/index.tsx` / `file-icons.tsx` / `builtins/tab-icons.tsx` 与 `tests/{changes-tab,theme}.spec.ts(x)` 的注释以「指南 §12」引用——调整指南章节结构时同步检查这些位置(`src/client/shell-presets.ts` 曾引用它,随 titleBar 让位机制一并删除)。 - **接入 API 即文档**:`src/client/service.ts` 与 `src/client/builtins/` 的任何行为变更,必须同步 [docs/external-plugin-guide.md](docs/external-plugin-guide.md)(唯一权威接入文档,不再双份维护)。 diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ae61b96..a5ce27a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ ### Unreleased +- 🪟 **保存不再把 CRLF 文件写成 LF([#871](https://github.com/omdsh-dev/DSH-better-sidebar/issues/871))**:上一批只修了读取侧,写入侧仍有洞——编辑器传送的永远是 LF 文档(CodeMirror 没有别的行模型),而 `fs.write` 把它原样落盘,于是在 Windows 检出上**改一行 = 整文件 diff**。现在保存前用**同一趟** 64 KiB sniff 读取同时取出编码与行尾(`text-encoding.ts` 的 `encodingOfFile` 扩成 `fileFormatOf`,新增 `detectEol` / `restoreEol`),落盘改为 `encodeText(restoreEol(content, eol), encoding)`:CRLF 文件保持 CRLF、LF 文件不被引入 `\r`、已含 `\r\n` 的内容不会被写成 `\r\r\n`。口径与宿主自己的 `edit` 工具逐字一致(前 4096 字符多数票;孤立 `\r` 既不计票也不改写),所以插件保存与模型 `edit` 对同一个文件得到同一个结论——顺带核实:宿主的 `write` 工具**不做**这件事(`writeText` 原样写模型文本),模型整份覆盖时文件仍会变成 LF,那是宿主写入、插件无权干预,已在 issue 里留结论。**客户端零改动**,保存入口(含快捷键与草稿边沿)自动全覆盖。新文件仍是 UTF-8 + LF:「项目级行尾约定」不在本批范围。 +- 🧪 测试:`tests/text-encoding.spec.ts` 补 3 条新用例(CRLF/LF 检测、多数票与孤立 `\r`、`restoreEol` 不双写)并把既有的编码三例扩成 `fileFormatOf` 断言;`tests/fs-write-route.spec.ts` 补 3 条端到端(CRLF 文件写 LF 文档后除被编辑行外全 CRLF 且无裸 `\n`、LF 文件不引入 `\r`、GBK + CRLF 组合下两个 restore 同时开火)。判别性:把 `restoreEol(...)` 换回 `content` → 2 条端到端红,其余仍绿。 - 🔎 **搜索框支持直接粘贴路径:指名路径 stat 直开、相对片段按路径匹配**([#879](https://github.com/omdsh-dev/DSH-better-sidebar/issues/879)):`fs.search` 之前把整个输入当作文件名子串在整个 cwd 树里递归匹配——文件名永不包含分隔符,所以粘贴任何带 `/` 的路径都是**结构性零命中**,却仍烧满 10 万条访问预算(实测含 worktree 森林的 Rust 仓库上 1.9s 返回 `{matches:[],truncated:true}`,工作区外文件如 `/tmp` 下的实验产物图因此在右侧无从预览)。现在 `searchFiles` 按查询形态分流:**指名单一目标的 query(绝对路径、`~/…`、`./x`、`../x`)经 `resolveTarget`——与 fs.read 同一解析原语(`~` 展开 #713、会话 cwd 拼接、win32 WSL/dsh-remote 命名空间改写、词法 resolve)——stat 直取**,命中返回**解析后的绝对路径**(resolve 剥掉 shell 补全带的尾分隔符;客户端对匹配行与树行做精确字符串比对,客户端 `resolveSidebarPath` 对绝对路径透传,TreePanel 现有点击链路零改动即可打开),目录目标按 #801 契约同列 `dirs`(行内树导航而非按文件打开;**工作区外的目录命中行只清空查询**——树以 cwd 为根,没有可导航的行,客户端守卫同时避免了 `ancestorDirs` 为外部路径合成垃圾 `expanded` 条目),目标缺失立即返回空结果(不再烧预算换一个注定为空的遍历);**含分隔符的相对片段按根相对路径匹配**(大小写不敏感,Windows 两种分隔符都收;同名文件消歧正是 #306 的诉求)。引擎不参与路径分支——fd 的 `--fixed-strings` 不带 `--full-path`、rg 的三个 glob 以单路径段为匹配单元,路径语义由遍历独占,引擎 argv 构造零改动(新 skip 名仍由 `SKIP_DIR_NAMES` 派生进 fd `--exclude` / rg glob,`check:engines` 门禁不受影响)。用户 exclude 列表不作用于直开分支:粘贴路径是显式意图,与点击后的 `fs.read` 行为一致(fs.read 同样不应用 exclude)。POSIX 上 `\` 仍是文件名合法字符而非分隔符(`~\foo` 形态仅在 win32 计入路径手势);单独的 `~` 按客户端 `isAbsolutePath` 的口径视为指名 home 目录,其余不带分隔符的 `~`/点前缀拼写(`util.ts~`、`~$doc.docx`、`.env`)仍是名字查询,引擎资格不受影响。 - 🧹 **噪声目录名单补 worktree 森林与语言环境**:`SKIP_DIR_NAMES` 增加 `.worktrees` / `.worktree`(两种 git worktree 布局拼写,`.worktrees/` 正是 DeepSeek Harness 自己的约定)、`target`(Rust / Maven 构建产物)、`venv` / `.venv` / `__pycache__`(Python 环境与字节码缓存)——此前两片 worktree 森林实测可烧掉 100k 预算的 97k,真实目录从未被遍历、`truncated` 恒真。walk 与两条引擎 argv 共用同一名单(fd `--exclude` 与 rg glob 对自动派生),引擎与遍历的跳过行为保持一致。 - 🧪 测试:`tests/fs-search.spec.ts` 新增 9 条——路径片段匹配(深度无关 / 大小写 / 目录行的 dirs 拆分 / 噪声围栏照常生效)、直开分支(文件与目录目标、目标缺失即空且 `maxVisited:1` 下仍 `truncated:false` 钉住「未走遍历」、尾分隔符 / `./` / `../` / `~` 经 `resolveTarget` 解析后返回解析路径)、`probed===false` 证明路径分支不触引擎、不带分隔符的 `~`/点前缀拼写仍是名字查询(引擎资格保持)、分隔符 query 不进引擎(假引擎返回污染行判别)、POSIX 反斜杠名字(探针式 skipIf 只在名字可存在的平台运行)、worktree/语言环境森林不进入;`tests/smoke.spec.ts` 新增 1 条路由级用例(绝对命中 / 立即空结果 / 相对片段 / `./` 锚定解析四态穿真实 mount);`tests/file-tree-search-persist.spec.tsx` 新增 1 条(工作区外目录命中行只清空查询、不触发任何 toggle)。判别性:还原 `fs-search.ts` 的分支即红(引擎污染行会浮出来);还原 skip 名单即红(森林内的 guide.md 命中);拿掉客户端守卫即红(外部路径的垃圾 toggle 浮出)。 diff --git a/docs/plans/2026-10-06-preserve-eol-on-save.md b/docs/plans/2026-10-06-preserve-eol-on-save.md new file mode 100644 index 00000000..23e6fe30 --- /dev/null +++ b/docs/plans/2026-10-06-preserve-eol-on-save.md @@ -0,0 +1,79 @@ +# 保存保持文件原有行尾(#871) + +> 状态:已实现(`fix/871-preserve-eol`)。来源:[issue #871](https://github.com/omdsh-dev/DSH-better-sidebar/issues/871) +> ——它是 `fix/crlf-markdown-surface`(`dev` 合并 `0ee870a`)的**直接后续**:那一批修的是读取侧的三层 +> `\r` 误判,刻意没动写入侧。 + +## 1. 问题 + +在侧栏编辑器里打开一个 **CRLF 行尾**的文件,按一次保存,整个文件变成 **LF**:`git diff` 全红、review +读不了、可能触发无谓的冲突与 CI 差异。不丢数据,但把「改一行」变成「重写整个文件」。 + +证据链(issue 已给):CodeMirror 的文档模型只有 LF,`save()` 写的是 `view.state.doc.toString()`; +同一条归一化在预览侧也能观察到——CRLF 内容的 draft 快照到达时已经是 LF 分段。 + +## 2. 已核实的事实(读装好的宿主包,逐字核对 rc.1 与 rc.2) + +**结论:宿主的 `edit` 工具不会改行尾,`write` 工具会;插件的保存路径从来没管过行尾。** + +| 写入面 | 行尾行为 | 证据 | +| --- | --- | --- | +| 宿主 `edit` 工具 | **保住**原文件风格 | `dsh-tool-fs` 的 `edit` → `ctx.fs.editText` → `dsh-fs-local` `editText`:`readForEdit` 返回 LF 归一化的 content + `detectLineEndings(raw)`,匹配与替换都在 LF 上做,落盘前 `restoreLineEndings(edited.content, original.lineEndings)` | +| 宿主 `write` 工具 | **不保**(原样写) | `dsh-tool-fs` 的 `write` → `ctx.fs.writeText` → `writeFileAtomic(targetKey, content)`,只有**回给 UI 的 diff 基线**做了 `normalizeLineEndings`,落盘字节就是模型给的文本 | +| 插件 `fs.write` 路由 | **原来完全不管** | `src/index.ts` 先 `encodingOfFile` 检测编码、过 mtime 冲突门,然后 `encodeText(content, encoding)` 直接写;行尾没有任何一步经手 | + +检测口径(宿主 `dsh-fs-local`):取**前 4096 字符**做多数票,`\r\n` 数**多于**裸 `\n` 数才算 CRLF; +归一化只认 `\r\n`(孤立 `\r` 即经典 Mac 行尾既不计票也不改写);还原时**先归一化再 `split('\n').join('\r\n')`**, +注释里写明这是为了不写出 `\r\r\n`。 + +版本面:本机全局装 0.2.0-rc.2,从 registry 取 `@deepseek-ai/dsh-fs-local@0.2.0-rc.1` 的 tarball 对照, +上述函数**行号与实现逐字相同**,所以对仓库 CI 钉的基线同样成立。 + +## 3. 设计:在服务端、与编码检测同一个缝里还原 + +改动面只有两处,**客户端一行不动**: + +- `src/text-encoding.ts` + - 新增 `TextEol = 'lf' | 'crlf'` 与 `FileFormat = { encoding, eol }`; + - 新增 `detectEol(text)`(前 `EOL_SNIFF_LIMIT = 4096` 字符多数票,与宿主同款口径)与 + `restoreEol(text, eol)`(LF 原样返回;CRLF 先归一化再 join); + - `encodingOfFile(path)` 扩成 **`fileFormatOf(path)`**:**同一趟** 64 KiB sniff 读取同时给出编码与行尾, + `decodeTextBytes` 返回的 `content` 本身不做行尾归一化,直接拿来投票。二进制读(`decoded === null`) + 与 `ENOENT` 都返回 `{ encoding: 'utf8', eol: 'lf' }`。 +- `src/index.ts` 的 `fs.write`:`const { encoding, eol } = await fileFormatOf(path)`, + 落盘改为 `encodeText(restoreEol(content, eol), encoding)`。顺序仍是「mtime 门 → sniff → 写」, + 所以还原依据是**磁盘当前**状态(外部改过就用外部的新风格),与编码检测同一取舍。 + +**为什么不把 `eol` 记进客户端 / per-tab store。** 那样等于再造一份状态,要跟未保存草稿、多 tab 共享 +同一文件、宿主重挂三处对齐;而且保存入口只有一个(`TextEditor.tsx` 的 `api.fsWrite`),服务端覆盖它就是 +全覆盖。客户端继续只发送 LF 文档,协议零变更。 + +**为什么不加设置开关。** 「编辑器不该偷偷改我的文件」本身就是正确默认;给两种保存语义各配一套测试与 +文档只会稀释这条保证。 + +## 4. 边界与「不做」 + +| 情形 | 行为 | 理由 | +| --- | --- | --- | +| 混合行尾 | 按**多数风格整份回写** | 与宿主 `editText` 同款取舍;「只改被编辑行」做不到——CodeMirror 只给整份文档,没有逐行归属 | +| CR-only(经典 Mac) | 不识别、字节原样保留 | 归一化只认 `\r\n`;新插入的行会是 LF(结果是混合),与宿主一致,不自行发明 | +| 新文件(`ENOENT`) | UTF-8 + **LF** | **项目级行尾一致性是另一个问题**:本批只保证「不改一个文件既有的格式」,不推断项目约定(兄弟目录多数票 / `.gitattributes` / 偏好都不是本批的事) | +| 内容里已含 `\r\n`(粘贴、老调用方) | 不产生 `\r\r\n` | 先归一化再 join | +| 大文件截断只读、二进制、上传 | 不进这条路径 | 只读态没有保存入口;二进制走下载面板 | +| 模型 `write` 整份覆盖同一文件 | **仍会变 LF** | 那是宿主的 `writeText`,插件拦不住;见 §6 | + +## 5. 测试与判别性 + +- `tests/text-encoding.spec.ts`:`fileFormatOf` 的 CRLF/LF/新文件、`detectEol` 的多数票与孤立 `\r`、 + `restoreEol` 不双写;既有 3 条编码断言改为 `toMatchObject` / `toEqual`(签名换了,覆盖面没减)。 +- `tests/fs-write-route.spec.ts`:三条端到端——CRLF 文件写 LF 文档后**除被编辑行外全 CRLF**且没有裸 `\n`、 + LF 文件不引入 `\r`、GBK + CRLF 组合(LF 文档 → GBK + CRLF 字节,两个 restore 都要开火)。 +- 判别性(实测):把 `restoreEol(content, eol)` 换回 `content` → 后两条端到端用例**红**,其余仍绿。 + +## 6. 后续(不在本批) + +1. **上游 `write` 工具不做行尾还原**:模型用 `write` 整份覆盖一个 CRLF 文件时,文件仍会变 LF。插件侧 + 无写入权(那是 `ctx.fs.writeText`),只能向上游提「`writeText` 也按磁盘风格回写」,或让模型改用 `edit`。 + 本批只在 issue 里留结论,不阻塞落地。 +2. **新文件的 EOL 与项目级一致性**:默认 LF 是现状的诚实描述;若要做「跟随项目约定」,需要先定义口径 + (读 `.gitattributes`?同目录多数票?设置项?),另立 issue。 diff --git a/src/index.ts b/src/index.ts index 074dae37..78258d09 100644 --- a/src/index.ts +++ b/src/index.ts @@ -70,7 +70,7 @@ import { // row bound, so it lives in a dependency-free module both can import. import { FS_TREES_MAX_PATHS } from './fs-batch.ts' import { activeWorktreeRootOf } from './active-worktree.ts' -import { decodeTextBytes, encodeText, encodingOfFile } from './text-encoding.ts' +import { decodeTextBytes, encodeText, fileFormatOf, restoreEol } from './text-encoding.ts' export { Config } export type { SidebarConfig, ResolvedSidebarConfig } @@ -601,9 +601,13 @@ function buildApi( const { cwd } = await cwdOf(payload) const path = await ensureWorkspaceWritePath(cwd, requireString(payload, 'path')) const content = requireString(payload, 'content') - // Detect the encoding BEFORE the temp write so the save round-trips the - // bytes the file already used (GBK / UTF-16 / BOM'd UTF-8 stay put). - const encoding = await encodingOfFile(path) + // Detect the byte encoding AND the line ending BEFORE the temp write, so + // the save round-trips what the file already used: GBK / UTF-16 / BOM'd + // UTF-8 stay put, and a CRLF file stays CRLF. The second half matters + // because the editor transports an LF document (CodeMirror has no other + // line model), so writing it verbatim turns one edited line into a + // whole-file diff for every Windows checkout (#871). + const { encoding, eol } = await fileFormatOf(path) // Optimistic concurrency: the client sends the mtime its draft was based // on; a file that changed on disk since (the model wrote it, another tab // saved, an external editor touched it) refuses the write instead of @@ -629,7 +633,7 @@ function buildApi( const tmp = join(dirname(path), `.${basename(path)}.dsh-sidebar-tmp-${randomUUID()}.tmp`) try { await mkdir(dirname(path), { recursive: true }) - await writeFile(tmp, encodeText(content, encoding), { flag: 'wx' }) + await writeFile(tmp, encodeText(restoreEol(content, eol), encoding), { flag: 'wx' }) await rename(tmp, path) } catch (error) { await rm(tmp, { force: true }).catch(() => {}) diff --git a/src/text-encoding.ts b/src/text-encoding.ts index 89cc4a10..eeb14d05 100644 --- a/src/text-encoding.ts +++ b/src/text-encoding.ts @@ -25,6 +25,25 @@ export interface DecodedText { encoding: TextEncoding } +/** + * Line-ending style a save must round-trip. Only CRLF is recognized: a lone + * `\r` (classic Mac) is neither counted by {@link detectEol} nor rewritten by + * {@link restoreEol}, which mirrors the host filesystem backend + * (`@deepseek-ai/dsh-fs-local`). Its `edit` tool is the reference behaviour + * here — it restores the style detected at read time instead of normalizing the + * file, so a model edit does not rewrite every line. The host's `write` tool + * does NOT do this (it writes the model's LF text verbatim), which is why the + * editor's own save has to carry the guarantee itself. + */ +export type TextEol = 'lf' | 'crlf' + +/** The on-disk format of a file: how its bytes are encoded and how its lines + * end. Both are re-detected from disk before every save. */ +export interface FileFormat { + encoding: TextEncoding + eol: TextEol +} + const UTF8_BOM = Buffer.from([0xef, 0xbb, 0xbf]) const UTF16LE_BOM = Buffer.from([0xff, 0xfe]) const UTF16BE_BOM = Buffer.from([0xfe, 0xff]) @@ -32,6 +51,11 @@ const UTF32LE_BOM = Buffer.from([0xff, 0xfe, 0x00, 0x00]) const UTF32BE_BOM = Buffer.from([0x00, 0x00, 0xfe, 0xff]) const ENCODING_SNIFF_LIMIT = 64 * 1024 +/** Sample the line-ending vote reads (characters, not bytes). Same window as + * the host backend's `detectLineEndings`, so the plugin and the host reach the + * same verdict about the same file. */ +const EOL_SNIFF_LIMIT = 4096 + const UTF8_DECODER = new TextDecoder('utf-8', { fatal: true }) const GBK_DECODER = new TextDecoder('gbk', { fatal: true }) const GB18030_DECODER = new TextDecoder('gb18030', { fatal: true }) @@ -315,12 +339,50 @@ export function encodeText(text: string, encoding: TextEncoding): Buffer { } } -export async function encodingOfFile(path: string): Promise { +/** + * Majority vote over the leading {@link EOL_SNIFF_LIMIT} characters: CRLF wins + * only when the CRLF pairs outnumber the bare LFs. A file with a single trailing + * CRLF among many LF lines therefore reads as LF, and a `\r`-only (classic Mac) + * file reads as LF without its bytes being touched — both the same verdict the + * host backend reaches, so a plugin save and a model `edit` agree. + */ +export function detectEol(text: string): TextEol { + const sample = text.slice(0, EOL_SNIFF_LIMIT) + const crlf = sample.split('\r\n').length - 1 + const lines = sample.split('\n').length - 1 + return crlf > lines - crlf ? 'crlf' : 'lf' +} + +/** + * Convert the editor's LF document back to the file's own style before + * encoding. CRLF content is normalized first (unlike a naive `split('\n').join` + * this can never turn an existing pair into `\r\r\n`) — the same guard the host + * backend's `restoreLineEndings` documents. Everything else, including a lone + * `\r`, is passed through untouched. + */ +export function restoreEol(text: string, eol: TextEol): string { + if (eol === 'lf') return text + return text.replaceAll('\r\n', '\n').split('\n').join('\r\n') +} + +/** + * Detect the on-disk format a save has to round-trip: byte encoding AND line + * endings, from one sniff read. Called before the temp write on every save, so + * the editor never silently converts GBK / UTF-16 / BOM'd UTF-8 bytes — nor a + * CRLF file to LF, which for a one-line edit would land as a whole-file diff + * (#871). A missing file yields UTF-8 + LF (see the comment below). + */ +export async function fileFormatOf(path: string): Promise { let handle try { handle = await open(path, 'r') } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 'utf8' + // A file that does not exist yet has no format to preserve. New files are + // written as UTF-8 + LF; deriving a project-wide convention (a sibling + // majority, a `.gitattributes` read, a preference) is a separate decision, + // deliberately not taken here — this batch only stops CHANGING a format a + // file already has. + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { encoding: 'utf8', eol: 'lf' } throw error } try { @@ -329,7 +391,13 @@ export async function encodingOfFile(path: string): Promise { const truncated = info.size > ENCODING_SNIFF_LIMIT const bytes = Buffer.alloc(Math.min(info.size, ENCODING_SNIFF_LIMIT)) const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0) - return decodeTextBytes(bytes.subarray(0, bytesRead), truncated)?.encoding ?? 'utf8' + const decoded = decodeTextBytes(bytes.subarray(0, bytesRead), truncated) + return { + encoding: decoded?.encoding ?? 'utf8', + // A binary read has no line structure to preserve; the editor cannot be + // showing one anyway (it falls back to the download pane). + eol: decoded === null ? 'lf' : detectEol(decoded.content), + } } finally { await handle.close() } diff --git a/tests/fs-write-route.spec.ts b/tests/fs-write-route.spec.ts index f442e35c..0917977b 100644 --- a/tests/fs-write-route.spec.ts +++ b/tests/fs-write-route.spec.ts @@ -17,6 +17,7 @@ import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, utimesSync, import { tmpdir } from 'node:os' import { join } from 'node:path' import { apply } from '../src/index.ts' +import { encodeText } from '../src/text-encoding.ts' import type { SidebarWebRoute } from '../src/context-types.ts' interface FakeContext { @@ -202,4 +203,79 @@ describe('fs.write route', () => { rmSync(root, { recursive: true, force: true }) } }) + + // #871: the editor transports an LF document (CodeMirror has no other line + // model), so writing it verbatim turned ONE edited line into a whole-file diff + // on every CRLF checkout. The route now restores the style the file already + // had — the SAME guarantee the host's own `edit` tool gives (dsh-fs-local's + // restoreLineEndings), which the host's `write` tool does not. + it('keeps a CRLF file CRLF when the editor saves its LF document (#871)', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-write-crlf-')) + try { + const workspace = join(root, 'ws') + mkdirSync(workspace) + const target = join(workspace, 'win.txt') + writeFileSync(target, 'one\r\ntwo\r\nthree\r\n') + const route = mountApi(workspace) + const result = await invoke(route, 'fs.write', { + sessionId: 's', + path: target, + content: 'one\ntwo edited\nthree\n', + }) + expect(result, JSON.stringify(result)).toMatchObject({ ok: true, status: 200 }) + const written = readFileSync(target, 'utf8') + expect(written).toBe('one\r\ntwo edited\r\nthree\r\n') + // No bare LF may survive — that is precisely the whole-file diff. + expect(written.replaceAll('\r\n', '')).not.toContain('\n') + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + it('leaves an LF file LF — a save never introduces CR', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-write-lf-')) + try { + const workspace = join(root, 'ws') + mkdirSync(workspace) + const target = join(workspace, 'posix.sh') + writeFileSync(target, 'one\ntwo\n') + const route = mountApi(workspace) + const result = await invoke(route, 'fs.write', { + sessionId: 's', + path: target, + content: 'one\ntwo edited\n', + }) + expect(result, JSON.stringify(result)).toMatchObject({ ok: true, status: 200 }) + const written = readFileSync(target, 'utf8') + expect(written).toBe('one\ntwo edited\n') + expect(written).not.toContain('\r') + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + it('composes the EOL restore with the encoding restore (GBK + CRLF, no \\r\\r\\n)', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-write-gbk-crlf-')) + try { + const workspace = join(root, 'ws') + mkdirSync(workspace) + const target = join(workspace, 'legacy.cmd') + writeFileSync(target, encodeText('@echo off\r\necho 中文\r\n', 'gbk')) + const route = mountApi(workspace) + // An LF document (what the editor always sends) into a GBK + CRLF file: + // both restores have to fire for the bytes to match. + const result = await invoke(route, 'fs.write', { + sessionId: 's', + path: target, + content: '@echo off\necho 中文 saved\n', + }) + expect(result, JSON.stringify(result)).toMatchObject({ ok: true, status: 200 }) + expect(readFileSync(target).equals(encodeText('@echo off\r\necho 中文 saved\r\n', 'gbk'))).toBe(true) + // Redundant with the byte comparison, but keeps the intent readable when + // that assertion ever gets relaxed. + expect(readFileSync(target).toString('utf8')).not.toContain('\r\r') + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) }) diff --git a/tests/text-encoding.spec.ts b/tests/text-encoding.spec.ts index e099da41..5be0328c 100644 --- a/tests/text-encoding.spec.ts +++ b/tests/text-encoding.spec.ts @@ -4,8 +4,10 @@ import { join } from 'node:path' import { tmpdir } from 'node:os' import { decodeTextBytes, + detectEol, encodeText, - encodingOfFile, + fileFormatOf, + restoreEol, type TextEncoding, } from '../src/text-encoding.ts' @@ -75,17 +77,50 @@ describe('text encoding', () => { // The 64 KiB sniff window ends inside a three-byte character; the save // side must still recognize the file as UTF-8. writeFileSync(path, Buffer.from(`${'a'.repeat(64 * 1024 - 2)}中文`, 'utf8')) - await expect(encodingOfFile(path)).resolves.toBe('utf8') + await expect(fileFormatOf(path)).resolves.toMatchObject({ encoding: 'utf8' }) }) it('detects the on-disk encoding used for the next save', async () => { const path = join(root, 'legacy.cmd') writeFileSync(path, encodeText('@echo off\r\necho 中文\r\n', 'gbk')) - await expect(encodingOfFile(path)).resolves.toBe('gbk') + await expect(fileFormatOf(path)).resolves.toEqual({ encoding: 'gbk', eol: 'crlf' }) }) - it('defaults new files to UTF-8', async () => { - await expect(encodingOfFile(join(root, 'missing.txt'))).resolves.toBe('utf8') + it('defaults new files to UTF-8 + LF', async () => { + // A file that does not exist yet has no format to preserve. Deriving a + // project-wide convention is deliberately out of scope (#871): this only + // pins the default the route writes for a create. + await expect(fileFormatOf(join(root, 'missing.txt'))).resolves.toEqual({ encoding: 'utf8', eol: 'lf' }) + }) + + it('reads a CRLF file as CRLF and an LF file as LF', async () => { + const crlf = join(root, 'crlf.txt') + writeFileSync(crlf, 'one\r\ntwo\r\nthree\r\n') + await expect(fileFormatOf(crlf)).resolves.toEqual({ encoding: 'utf8', eol: 'crlf' }) + + const lf = join(root, 'lf.txt') + writeFileSync(lf, 'one\ntwo\nthree\n') + await expect(fileFormatOf(lf)).resolves.toEqual({ encoding: 'utf8', eol: 'lf' }) + }) + + it('votes on the majority and ignores a lone CR', () => { + // Same rule (and same 4096-char window) as the host backend's + // detectLineEndings, so a plugin save and a model `edit` agree. + expect(detectEol('a\r\nb\r\nc\n')).toBe('crlf') + expect(detectEol('a\nb\nc\r\n')).toBe('lf') + // A classic-Mac file is not CRLF and its `\r` bytes are never rewritten. + expect(detectEol('a\rb\r')).toBe('lf') + expect(restoreEol('a\rb\r', 'lf')).toBe('a\rb\r') + // Past the window only the prefix votes. + expect(detectEol(`${'a\r\n'.repeat(3000)}b\n`)).toBe('crlf') + }) + + it('restores CRLF without doubling an existing pair', () => { + expect(restoreEol('a\nb\n', 'crlf')).toBe('a\r\nb\r\n') + // The editor hands us LF, but a caller may pass CRLF through (a paste, a + // future caller): the naive split/join would emit `\r\r\n` here. + expect(restoreEol('a\r\nb\r\n', 'crlf')).toBe('a\r\nb\r\n') + expect(restoreEol('a\r\nb', 'crlf')).toBe('a\r\nb') }) it('refuses silently lossy GBK writes', () => {