fix(fs): 带基线保存时目标已不存在判冲突,不再无提示重建被删的文件

`fs.write` 的乐观并发门只在「读得到磁盘 mtime 且与基线不符」时报冲突。目标
已被删除或改名走时,`stat` 失败被 `.catch(() => undefined)` 吃掉,代码把
「读不到」当成「没有基线可比」,于是整段门禁跳过、直接写盘:文件被重建,被
一并删掉的父目录也被 `mkdir -p` 重建,客户端清掉 dirty 并显示「已保存」——
用户刚做的删除被无提示地推翻。

数字基线只可能来自一次成功的读取,也就是那个路径当时确实有文件;所以「读不
到」是磁盘上的删除/改名,不是「新建」意图——新建走 `fs.createFile`,上传走
上传写入,都不经过这条分支。据此把 `current === undefined` 单独判成 409
`fs-conflict`(消息写明 no longer exists on disk)。

改动:
- `src/index.ts`:冲突门拆出「目标不存在」这一支
- `docs/external-plugin-guide.md` 的 `fs.write` 行、`src/client/api.ts` 的
  `fsWrite` 注释:同步这条语义
- `tests/fs-write-route.spec.ts` 两条新用例:目标文件被删(409,不重建、无
  临时文件残留)、父目录被删(409,目录不被重建)

客户端沿用既有的 `fs-conflict` 横幅(「文件已在磁盘上被其它来源改动。保存已
中止,你的修改仍留在编辑器里。」):删除属于「磁盘上被改动」,草稿保留与
重载按钮都仍然成立,因此不新增 20 份词典的词条。
This commit is contained in:
unsc9 committed 2026-10-10 21:40:49 +08:00
1 parent 1184d063c9
commit d6d927bf6a
4 files changed
+85 -12

No files matched your search

+1 -1
View File
@@ -641,7 +641,7 @@ const { value } = await res.json() // 错误时 { ok: false, error: { code, me
| `fs.tree` / `fs.trees` | 目录列表(`{ path, entries: FsEntry[], truncated }`;FsEntry 含 `isSymlink`/`broken`,目录软链接的 `isDir` 按目标类型;请求可带 `exclude` 模式串,行上可带 `compact` 标记——单目录链由 client 折叠为面包屑行,匹配条目从列表与折叠探测中彻底移除)。`fs.trees` 是批量版(文件树的真实入口,同样吃 `exclude`) |
| `fs.trees` | **批量**目录列表(v0.23.0+):入参 `{ sessionId, cwd?, paths: string[] }`(最多 64 条,绝对或会话相对),一次请求返回 `{ levels: [{ path, entries, truncated, error? }] }`。每层与 `fs.tree` 同解析、同缓存;**某一层失败只在该层带 `error`**(`entries: []`),整个批次仍是成功响应——树的一次挂载/刷新因此是 1 个请求而不是 N 个 |
| `fs.read` | 读文件:文本返回 `{ kind: 'text', content, truncated, mtimeMs }`;二进制返回 `{ kind: 'binary', size, truncated, mtimeMs, head }`(head = base64 前 4KB;`mtimeMs` = 本次读取的磁盘 mtime,保存冲突基线) |
| `fs.write` | 原子写文件:`{ path, content, expectedMtimeMs? }`。带 `expectedMtimeMs` 时是乐观并发门——磁盘 mtime 与基线不符则拒绝(409,wire 错误码 `fs-conflict`),不覆盖对方字节;省略则不做门禁。成功返回 `{ ok: true, mtimeMs }`(新基线) |
| `fs.write` | 原子写文件:`{ path, content, expectedMtimeMs? }`。带 `expectedMtimeMs` 时是乐观并发门——磁盘 mtime 与基线不符则拒绝(409,wire 错误码 `fs-conflict`),不覆盖对方字节;**目标已不存在(保存瞬间被删除或改名走)同样判 409**——数字基线只可能来自一次成功的读取,即该路径当时确实有文件,所以「读不到」是冲突而不是新建意图(新建走 `fs.createFile`、上传走上传路径,都不经过这条分支)。省略 `expectedMtimeMs` 则不做门禁。成功返回 `{ ok: true, mtimeMs }`(新基线) |
| `git.status` / `git.diff` / `git.log` 等 | 全套 Git 只读 + 写操作 |
| `pty.close` / `agent-pty.close` | **已删除**(插件自带的 PTY 栈随终端一起移除;宿主 `ui-sidebar-terminal` 不通过本插件的路由暴露控制面) |
| `settings.get` / `settings.update` | 侧边栏偏好读写(revision 守卫,冲突回 wire 错误码 `settings-conflict`);后端在 0.1.7 上就是宿主的 `SettingsForms`,见 §8.2 |
+5 -3
View File
@@ -372,9 +372,11 @@ export const api = {
call<FsTextResult | FsBinaryResult>('fs.read', scopePayload(scope, { path }), signal),
/** Save a file. `expectedMtimeMs` is the mtime the draft was based on: a
* file that changed on disk since refuses with code `fs-conflict` (the
* editor then offers a reload) instead of clobbering those bytes. `null`
* (the file did not exist yet) and omitted (older callers) both mean no
* gate. The response carries the fresh baseline. */
* editor then offers a reload) instead of clobbering those bytes — and so
* does a file that is no longer there at all, because a numeric baseline
* proves it was read from an existing file. `null` (the file did not exist
* yet) and omitted (older callers) both mean no gate. The response carries
* the fresh baseline. */
fsWrite: (scope: SessionScope, path: string, content: string, expectedMtimeMs?: number | null) =>
call<{ ok: true; mtimeMs?: number }>('fs.write', scopePayload(scope, {
path,
+12 -6
View File
@@ -618,12 +618,18 @@ function buildApi(
: undefined
if (expected !== undefined) {
const current = await stat(path).then(info => info.mtimeMs).catch(() => undefined)
if (current !== undefined && current !== expected) {
throw new SidebarError(
'fs-conflict',
`"${path}" changed on disk since it was loaded (expected mtime ${expected}, found ${current})`,
409,
)
// A NUMERIC baseline can only come from a successful read of a file
// that existed, so "no stat" is not "nothing to compare" — it means the
// path was removed (or renamed away) while the draft was open. Reading
// that as "no gate" wrote the draft back over the user's own deletion
// and re-created the file (and its parent directory) with no prompt.
// Creating a file is a different intent with its own entry points
// (`fs.createFile`, the upload writer), so refusing here costs nothing.
if (current !== expected) {
const why = current === undefined
? `no longer exists on disk (expected mtime ${expected})`
: `changed on disk since it was loaded (expected mtime ${expected}, found ${current})`
throw new SidebarError('fs-conflict', `"${path}" ${why}`, 409)
}
}
// Per-request temp name (same pattern as writeWorkspaceUpload): a
+67 -2
View File
@@ -10,10 +10,13 @@
* 2. `expectedMtimeMs` is an optimistic-concurrency gate: a file that changed
* on disk since the draft was loaded refuses with `fs-conflict` (409)
* instead of clobbering the new bytes, and a successful save reports the
* fresh baseline the client adopts.
* fresh baseline the client adopts. A file that is GONE at save time is the
* same refusal — a numeric baseline proves it was read from an existing
* file, so its absence is a change the user made, not permission to
* re-create it.
*/
import { describe, expect, it } from 'vitest'
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { apply } from '../src/index.ts'
@@ -188,6 +191,68 @@ describe('fs.write route', () => {
}
})
// A baseline the client still holds means the draft was loaded from a file
// that existed. If the path is GONE at save time (the user removed it, the
// model ran `rm`, a branch switch took it away), the old code read the failed
// stat as "no baseline to compare" and wrote the draft back — re-creating the
// file, and its parent directory, with no prompt while reporting a clean
// save. Only "the file changed" was treated as a conflict; "the file is not
// there any more" is the same class of surprise.
it('refuses to re-create a file that was deleted since it was loaded', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-write-gone-'))
try {
const workspace = join(root, 'ws')
mkdirSync(workspace)
const target = join(workspace, 'draft.txt')
writeFileSync(target, 'disk-v1')
const route = mountApi(workspace)
const read = await invoke(route, 'fs.read', { sessionId: 's', path: target })
const baseline = read.value?.mtimeMs
expect(typeof baseline).toBe('number')
// The user (or something else) removed it while the draft was open.
rmSync(target, { force: true })
const stale = await invoke(route, 'fs.write', {
sessionId: 's', path: target, content: 'my-draft', expectedMtimeMs: baseline,
})
expect(stale).toMatchObject({ ok: false, status: 409, error: { code: 'fs-conflict' } })
// The deletion stands: nothing was written back, and no temp sibling
// survived the refusal.
expect(existsSync(target)).toBe(false)
expect(tempLeftovers(workspace)).toEqual([])
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('refuses the same way when the whole parent directory is gone', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-write-gonedir-'))
try {
const workspace = join(root, 'ws')
const nested = join(workspace, 'src')
mkdirSync(nested, { recursive: true })
const target = join(nested, 'draft.txt')
writeFileSync(target, 'disk-v1')
const route = mountApi(workspace)
const read = await invoke(route, 'fs.read', { sessionId: 's', path: target })
const baseline = read.value?.mtimeMs
// A rename/removal of the parent directory: the writer's `mkdir -p` used
// to rebuild the tree for a single file.
rmSync(nested, { recursive: true, force: true })
const stale = await invoke(route, 'fs.write', {
sessionId: 's', path: target, content: 'my-draft', expectedMtimeMs: baseline,
})
expect(stale).toMatchObject({ ok: false, status: 409, error: { code: 'fs-conflict' } })
expect(existsSync(nested)).toBe(false)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('treats an omitted baseline as no gate (older callers keep working)', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-write-legacy-'))
try {