diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index e521ea82..a8752ac2 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -648,7 +648,7 @@ const { value } = await res.json() // 错误时 { ok: false, error: { code, me | `fs.trees` | **批量**目录列表(v0.23.0+):入参 `{ sessionId, cwd?, paths: string[] }`(最多 64 条,绝对或会话相对),一次请求返回 `{ levels: [{ path, entries, truncated, error? }] }`。每层与 `fs.tree` 同解析、同缓存;**某一层失败只在该层带 `error`**(`entries: []`),整个批次仍是成功响应——树的一次挂载/刷新因此是 1 个请求而不是 N 个 | | `fs.read` | 读文件(v0.26.0 起三态):文本 `{ kind: 'text', content, size, mtimeMs }`;二进制 `{ kind: 'binary', size, mtimeMs, head }`;**超过编辑上限**(5 MiB)`{ kind: 'too-large', size, mtimeMs, head }`(head = base64 前 4KB,用于 `detect` 重匹配;`mtimeMs` = 本次读取的磁盘 mtime,保存冲突基线)。**不再有 `truncated` 文本读**——截断文档既不可信也不能保存(#732),超大文件改走 `fs.readPage` 分页预览 | | `fs.readPage` | 大文本文件的分页读取(v0.26.0+):`{ sessionId, cwd?, path, offset }` → `{ kind:'text', text, offset, nextOffset, eof, size, mtimeMs, encoding }`。窗口按行对齐(调用方可以直接当作整行/整条记录处理),单个超长行原样返回而不是空页;`nextOffset` 必然前进,`eof` 精确 | -| `fs.write`(**已移至 raw 路由**) | v0.26.0 起保存走 `POST /sidebar/write?sessionId=&cwd=&path=&expectedMtimeMs=`,**请求体就是 LF 文档**(不再走 JSON,因此不再受 `/sidebar/api` 的 1 MiB body 上限约束);响应仍是 `{ ok: true, value: { ok: true, mtimeMs? } }` 信封。语义不变:`expectedMtimeMs` 是乐观并发门,磁盘 mtime 与基线不符则拒绝(409,wire 错误码 `fs-conflict`),省略则不做门禁;宿主在写盘前按磁盘现状还原文件的行尾与字节编码(`restoreEol` + `encodeText`) | +| `fs.write`(**已移至 raw 路由**) | v0.26.0 起保存走 `POST /sidebar/write?sessionId=&cwd=&path=&expectedMtimeMs=`,**请求体就是 LF 文档**(不再走 JSON,因此不再受 `/sidebar/api` 的 1 MiB body 上限约束);响应仍是 `{ ok: true, value: { ok: true, mtimeMs? } }` 信封。语义不变:`expectedMtimeMs` 是乐观并发门,磁盘 mtime 与基线不符则拒绝(409,wire 错误码 `fs-conflict`),**目标已不存在(保存瞬间被删除或改名走)同样判 409**——数字基线只可能来自一次成功的读取,即该路径当时确实有文件,所以「读不到」是冲突而不是新建意图(新建走 `fs.createFile`、上传走上传路径,都不经过这条分支)。省略则不做门禁;宿主在写盘前按磁盘现状还原文件的行尾与字节编码(`restoreEol` + `encodeText`) | | `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 67e3092c..5cec9eea 100644 --- a/src/client/api.ts +++ b/src/client/api.ts @@ -448,9 +448,11 @@ export const api = { * request body — no JSON escaping, so nothing caps the saved size). * `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. */ + * 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) => fetchWrite(scope, path, content, expectedMtimeMs ?? undefined), /** Rename one tree row within its directory (single-segment name; the diff --git a/src/fs-operations.ts b/src/fs-operations.ts index a6bebfc4..fb9da19f 100644 --- a/src/fs-operations.ts +++ b/src/fs-operations.ts @@ -119,7 +119,11 @@ export interface WorkspaceWriteInput { /** * The mtime the draft was based on. A file that changed on disk since is * REFUSED with `fs-conflict` instead of silently clobbering whatever wrote - * it; `undefined` = no gate (a brand-new file has no baseline). + * it — and so is a file that is GONE: a numeric baseline proves it was read + * from a file that existed, so "no stat" is a change the user made rather + * than permission to re-create the path. `undefined` = no gate (a brand-new + * file has no baseline — creating one is a different intent with its own + * entry points, `fs.createFile` and the upload writer). */ expectedMtimeMs?: number } @@ -141,7 +145,8 @@ export interface WorkspaceWriteInput { * is removed on every failure path. * * @throws {SidebarError} fs-conflict (409) when `expectedMtimeMs` no longer - * matches the file, fs-error when the write itself fails. + * matches the file OR the file is no longer there at all, fs-error when the + * write itself fails. */ export async function writeWorkspaceText(input: WorkspaceWriteInput): Promise<{ mtimeMs?: number }> { const { cwd, path, content, expectedMtimeMs } = input @@ -151,12 +156,18 @@ export async function writeWorkspaceText(input: WorkspaceWriteInput): Promise<{ const { encoding, eol } = await fileFormatOf(absolute) if (expectedMtimeMs !== undefined) { const current = await stat(absolute).then(info => info.mtimeMs).catch(() => undefined) - if (current !== undefined && current !== expectedMtimeMs) { - throw new SidebarError( - 'fs-conflict', - `"${absolute}" changed on disk since it was loaded (expected mtime ${expectedMtimeMs}, 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 !== expectedMtimeMs) { + const why = current === undefined + ? `no longer exists on disk (expected mtime ${expectedMtimeMs})` + : `changed on disk since it was loaded (expected mtime ${expectedMtimeMs}, found ${current})` + throw new SidebarError('fs-conflict', `"${absolute}" ${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 c15fe457..7fa3614b 100644 --- a/tests/fs-write-route.spec.ts +++ b/tests/fs-write-route.spec.ts @@ -17,10 +17,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' @@ -264,6 +267,42 @@ describe('/sidebar/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.api, '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 invokeWrite(route, { + 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 a save path that is missing, and writes nothing', async () => { const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-write-nopath-')) try { @@ -290,6 +329,32 @@ describe('/sidebar/write route', () => { } }) + 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.api, '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 invokeWrite(route, { + 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 {