diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index 1d367b54..f904d3f9 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -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 | diff --git a/src/client/api.ts b/src/client/api.ts index e8da82ef..16828b0e 100644 --- a/src/client/api.ts +++ b/src/client/api.ts @@ -372,9 +372,11 @@ export const api = { call('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, diff --git a/src/index.ts b/src/index.ts index 78258d09..32a8a5df 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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 diff --git a/tests/fs-write-route.spec.ts b/tests/fs-write-route.spec.ts index 0917977b..f01516d7 100644 --- a/tests/fs-write-route.spec.ts +++ b/tests/fs-write-route.spec.ts @@ -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 {