Files
apes-sidebar/tests/fs-write-route.spec.ts
T
Menghuan1918 783ac9feb6 merge #600 into dev(草稿保护/冲突门/替换;删掉与 #587 重复的查找接线与词典键,换掉已删图标名)
贡献者 PR #600(feat/editor-draft-protection,head a14c1e8)以 --no-ff 落到 dev
基线(9b97e6f)。贡献者的提交原样保留,冲突解决体现为本次合并结果。

保留(PR 独有):
- 草稿保护:src/client/editor-dirty.ts(脏稿登记表 + confirmDiscardDraft)、EditorHost
  的登记/卸载清理、Sidebar 的 closeTab 门与 beforeunload、closePathTabs 的确认参数。
- 保存冲突门:fs.read 回报 mtimeMs、fs.write 的 expectedMtimeMs(409 fs-conflict,在写
  临时文件之前判定)、TextEditor 的 mtimeRef + 冲突横幅 + onReload、wire 的
  fs-conflict 码,以及 fs-write-route / text-editor-conflict 两个新 spec。
- 查找/替换入口:TextEditor 工具栏放大镜按钮(打开 #587 的面板;可编辑视图的面板自带
  替换行),文案用 #587 的 searchFind。

删除(与 #587 / 2e22b90 重复的部分):
- TextEditor 里重复的那份查找接线:本地 searchPhrases()、EditorState.phrases.of(...)、
  search({ top: true })、编辑器 keymap 里的 ...searchKeymap,以及 search / searchKeymap
  两个 import——#587 的 src/client/cm-search.ts 已提供同一套(面板、keymap、phrases 隔间、
  令牌主题)。
- 20 份词典里被 #587 取代的 10 个键:find / replace / findNext / findPrevious / findAll /
  findMatchCase / findRegexp / findByWord / replaceOne / replaceAll(命名以先落的 #587 为准:
  searchFind / searchReplace / searchNext / searchPrevious / searchAll / searchMatchCase /
  searchWholeWord / searchRegexp / searchReplaceAll)。
- src/index.ts 里已被 2e22b90 覆盖的临时文件改名(.dsh-write-<uuid>):保留 dev 的
  .dsh-sidebar-tmp-<uuid>,tests/fs-write-route.spec.ts 的残留断言改指 dev 命名。
- tests/text-editor-search.spec.tsx 中与 editor-find.spec.tsx 重复的三个用例(en/zh 文案、
  Mod-f),只留「工具栏按钮开面板并切到编辑态」这一个独有用例。
- README / README_EN / 指南里未实现的 Ctrl/Cmd + H 声明(PR 从未绑定 Mod-h,且浏览器保留
  该组合键),改为如实描述「Ctrl/Cmd + F 的面板含替换行」,并补上 #587 已支持的
  Ctrl/Cmd + G / Shift + Ctrl/Cmd + G / Ctrl/Cmd + D。

其它解冲突取舍(dev 上下文已漂移,不复活 PR 基线代码):
- 图标:IconSearchOutline16 在宿主图标整族改名后已不存在,换为 IconSearchOutlineRegular
  size={16}(显式尺寸;旧 16 后缀已删,不传会按新默认尺寸)。
- 采纳 dev 侧:fs.read 的 ensureWorkspacePath 两参调用、truncation 横幅不带 mode 条件、
  fs.write 的编码探测与 invalidateDirectoryCache、Sidebar 的 closeTab 里 PR 基线的终端
  pty 释放块(dev 已移走)与 summaryCwd/pushedBottomHeight/collapsed 块(dev 已删)。
- 测试 harness 跟随 dev:ctx.sidebarRight.mounted、bottomSplits、先打开底部工作台、
  apply() 需要的 ctx.on、api 模块改为部分 mock(保留 sessionPhase / sessionCwd)。
- 取舍记录写入 docs/plans/2026-09-09-editor-draft-protection-design.md。

Refs #600
2026-10-05 01:58:18 +08:00

206 lines
8.8 KiB
TypeScript

/**
* Host `fs.write` route: the two guarantees the editor's save depends on.
*
* 1. Concurrent saves to the SAME path are independent — each writes its own
* uniquely named temp sibling, so one save's cleanup can never delete the
* other's temp file before its rename (the old shared
* `.dsh-sidebar-tmp-<pid>` name made the second rename fail with ENOENT).
* This guarantee ALREADY landed on dev (2e22b90, `.dsh-sidebar-tmp-<uuid>`);
* the case below pins dev's naming, it does not carry a fix of its own.
* 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.
*/
import { describe, expect, it } from 'vitest'
import { 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'
import type { SidebarWebRoute } from '../src/context-types.ts'
interface FakeContext {
webRuntime: { trustedHosts: readonly string[] }
webServer: {
register: (route: SidebarWebRoute) => () => void
registerUpgrade: () => () => void
}
sessions: { get: (id: string) => { header: { cwd?: string } } | undefined }
tools: { register: () => () => void }
effect: (fn: () => void | (() => void)) => void
inject: (deps: readonly string[], callback: (sctx: never) => void) => () => void
/** The assistant-live buffer subscribes on mount (dev's apply). */
on: () => () => void
get: (key: string) => undefined
}
/** Mount the plugin against a fake context whose session cwd is `workspace`. */
function mountApi(workspace: string): SidebarWebRoute {
const routes: SidebarWebRoute[] = []
const ctx: FakeContext = {
webRuntime: { trustedHosts: [] },
webServer: { register: (route) => { routes.push(route); return () => {} }, registerUpgrade: () => () => {} },
sessions: { get: () => ({ header: { cwd: workspace } }) },
tools: { register: () => () => {} },
effect: (fn) => { fn() },
inject: () => () => {},
on: () => () => {},
get: () => undefined,
}
apply(ctx as never, {})
return routes.find(route => route.path === '/sidebar/api')!
}
interface Invoked {
ok: boolean
status: number
value?: { ok?: boolean; mtimeMs?: number; kind?: string; content?: string }
error?: { code?: string; message?: string }
}
async function invoke(route: SidebarWebRoute, method: string, payload: unknown): Promise<Invoked> {
const body = Buffer.from(JSON.stringify(payload))
const req = {
method: 'POST',
url: `/sidebar/api/${method}`,
headers: { host: '127.0.0.1:3080' },
[Symbol.asyncIterator]: async function* () { yield body },
} as never
const out = { status: 200, body: '' }
const res = {
writeHead: (status: number) => { out.status = status },
end: (chunk: unknown) => { out.body += String(chunk ?? '') },
} as never
await route.handler(req, res)
return { ...JSON.parse(out.body) as Invoked, status: out.status }
}
/** Temp siblings the route may leave behind on failure (dev's per-save name,
* landed by 2e22b90 — this PR keeps it as-is). */
function tempLeftovers(dir: string): string[] {
return readdirSync(dir).filter(name => name.includes('.dsh-sidebar-tmp-'))
}
describe('fs.write route', () => {
it('keeps concurrent saves to the same path independent and leaves no temp files', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-write-race-'))
try {
const workspace = join(root, 'ws')
mkdirSync(workspace)
const target = join(workspace, 'race.txt')
const route = mountApi(workspace)
const results = await Promise.all([
invoke(route, 'fs.write', { sessionId: 's', path: target, content: 'first' }),
invoke(route, 'fs.write', { sessionId: 's', path: target, content: 'second' }),
invoke(route, 'fs.write', { sessionId: 's', path: target, content: 'third' }),
])
for (const result of results) {
// The bug this pins: with ONE shared temp name, a loser's cleanup
// rm()s the winner's temp file and its rename fails ENOENT. Windows
// may still refuse a concurrent rename over an open file with EPERM
// (antivirus / handle timing) — a platform quirk, not cross-talk.
expect(result.ok || (result.error?.message ?? '').includes('EPERM'), JSON.stringify(result)).toBe(true)
}
// At least one rename landed (the last successful writer wins), and no
// temp sibling survived either path.
expect(['first', 'second', 'third']).toContain(readFileSync(target, 'utf8'))
expect(tempLeftovers(workspace)).toEqual([])
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('runs repeated saves to the same path cleanly and leaves no temp files', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-write-repeat-'))
try {
const workspace = join(root, 'ws')
mkdirSync(workspace)
const target = join(workspace, 'seq.txt')
writeFileSync(target, 'v0')
const route = mountApi(workspace)
for (const content of ['v1', 'v2', 'v3']) {
const result = await invoke(route, 'fs.write', { sessionId: 's', path: target, content })
expect(result, JSON.stringify(result)).toMatchObject({ ok: true, status: 200 })
}
expect(readFileSync(target, 'utf8')).toBe('v3')
expect(tempLeftovers(workspace)).toEqual([])
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('refuses a save whose baseline mtime no longer matches the file on disk', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-write-conflict-'))
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 })
expect(read).toMatchObject({ ok: true, value: { kind: 'text', content: 'disk-v1' } })
const baseline = read.value?.mtimeMs
expect(typeof baseline).toBe('number')
// Something else (the model, another tab, an external editor) wrote it.
writeFileSync(target, 'disk-v2')
utimesSync(target, new Date(), new Date(Date.now() + 2_000))
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 foreign bytes survive: the write was refused, not merged.
expect(readFileSync(target, 'utf8')).toBe('disk-v2')
expect(tempLeftovers(workspace)).toEqual([])
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('accepts a save whose baseline still matches and reports the fresh baseline', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-write-ok-'))
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 saved = await invoke(route, 'fs.write', {
sessionId: 's', path: target, content: 'disk-v2', expectedMtimeMs: read.value?.mtimeMs,
})
expect(saved).toMatchObject({ ok: true, status: 200, value: { ok: true } })
expect(typeof saved.value?.mtimeMs).toBe('number')
expect(readFileSync(target, 'utf8')).toBe('disk-v2')
// The reported baseline is the one a follow-up save must present.
const second = await invoke(route, 'fs.write', {
sessionId: 's', path: target, content: 'disk-v3', expectedMtimeMs: saved.value?.mtimeMs,
})
expect(second).toMatchObject({ ok: true, status: 200 })
expect(readFileSync(target, 'utf8')).toBe('disk-v3')
} 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 {
const workspace = join(root, 'ws')
mkdirSync(workspace)
const target = join(workspace, 'legacy.txt')
writeFileSync(target, 'disk-v1')
const route = mountApi(workspace)
const result = await invoke(route, 'fs.write', { sessionId: 's', path: target, content: 'overwritten' })
expect(result).toMatchObject({ ok: true, status: 200 })
expect(readFileSync(target, 'utf8')).toBe('overwritten')
} finally {
rmSync(root, { recursive: true, force: true })
}
})
})