From a14c1e833bd7f629d3111322a20bc199c9679c4f Mon Sep 17 00:00:00 2001 From: dsh-better-sidebar-ci Date: Wed, 9 Sep 2026 09:05:19 +0800 Subject: [PATCH] =?UTF-8?q?feat(editor):=20=E6=9C=AA=E4=BF=9D=E5=AD=98?= =?UTF-8?q?=E8=8D=89=E7=A8=BF=E4=BF=9D=E6=8A=A4=E3=80=81=E4=BF=9D=E5=AD=98?= =?UTF-8?q?=E5=86=B2=E7=AA=81=E6=A3=80=E6=B5=8B=E4=B8=8E=E5=86=85=E7=BD=AE?= =?UTF-8?q?=E6=9F=A5=E6=89=BE=E6=9B=BF=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 三项编辑器/磁盘边界上的改动,均不改变 ctx.betterSidebar 的服务方法签名: 1. 未保存草稿保护(新增 src/client/editor-dirty.ts) - EditorHost 把工具栏的 dirty 登记进模块级登记表,卸载即清除 - 关标签页(X / 中键 / 右键菜单)、删文件(closePathTabs)、 页面刷新/关闭(beforeunload)三条路径共用一次确认 2. 保存的乐观并发门 - fs.read 返回 mtimeMs;fs.write 接受 expectedMtimeMs,基线不符 返回 409 fs-conflict 而不是覆盖对方字节;成功回报新基线 - 编辑器显示冲突横幅 +「重新载入」,草稿不丢 - 顺带修复:临时文件改为随机命名兄弟文件,同一路径的并发保存 不再互删(原固定名 .dsh-sidebar-tmp-) 3. 内置查找/替换 - 接入 @codemirror/search(依赖此前白装)+ searchKeymap, 面板文案经 EditorState.phrases 接入本插件词典 测试:新增 21 例(guard 8 / fs.write 路由 5 / 冲突 4 / 查找 4); 19 个语言词典同步 12 个新 key。设计见 docs/plans/2026-09-09-editor-draft-protection-design.md。 --- README.md | 4 + README_EN.md | 4 + docs/external-plugin-guide.md | 6 +- ...26-09-09-editor-draft-protection-design.md | 82 +++++ src/client/EditorHost.tsx | 23 +- src/client/Sidebar.tsx | 24 ++ src/client/TextEditor.tsx | 92 +++++- src/client/api.ts | 19 +- src/client/editor-dirty.ts | 106 +++++++ src/client/locales-ar.ts | 12 + src/client/locales-de.ts | 12 + src/client/locales-fr.ts | 13 + src/client/locales-hi.ts | 12 + src/client/locales-id.ts | 12 + src/client/locales-it.ts | 13 + src/client/locales-ja.ts | 12 + src/client/locales-ko.ts | 12 + src/client/locales-nl.ts | 12 + src/client/locales-pl.ts | 12 + src/client/locales-pt.ts | 12 + src/client/locales-ru.ts | 12 + src/client/locales-sv.ts | 12 + src/client/locales-th.ts | 12 + src/client/locales-tr.ts | 12 + src/client/locales-vi.ts | 12 + src/client/locales-zh-HK.ts | 12 + src/client/locales-zh-MO.ts | 12 + src/client/locales-zh-TW.ts | 12 + src/client/locales.ts | 25 ++ src/client/service.ts | 6 + src/client/sidebar.module.css | 12 + src/client/tree-mutations.ts | 11 +- src/index.ts | 37 ++- src/wire.ts | 1 + tests/editor-unsaved-guard.spec.tsx | 290 ++++++++++++++++++ tests/fs-write-route.spec.ts | 199 ++++++++++++ tests/text-editor-conflict.spec.tsx | 124 ++++++++ tests/text-editor-search.spec.tsx | 143 +++++++++ 38 files changed, 1416 insertions(+), 22 deletions(-) create mode 100644 docs/plans/2026-09-09-editor-draft-protection-design.md create mode 100644 src/client/editor-dirty.ts create mode 100644 tests/editor-unsaved-guard.spec.tsx create mode 100644 tests/fs-write-route.spec.ts create mode 100644 tests/text-editor-conflict.spec.tsx create mode 100644 tests/text-editor-search.spec.tsx diff --git a/README.md b/README.md index 95f54e40..28e348e4 100644 --- a/README.md +++ b/README.md @@ -515,6 +515,9 @@ GitHub topic [`dsh-better-sidebar`](https://github.com/topics/dsh-better-sidebar | 操作 | 按键 | |---|---| | 保存编辑 | `Ctrl/Cmd + S` | +| 编辑器内查找 / 替换 | `Ctrl/Cmd + F` / `Ctrl/Cmd + H` | +| 查找下一个 / 上一个 | `Ctrl/Cmd + G` / `Shift + Ctrl/Cmd + G`(面板内:`Enter` / `Shift + Enter`) | +| 选中下一个相同片段 | `Ctrl/Cmd + D` | | Git 提交 | `Ctrl + Enter` | | 关闭 Tab | 鼠标中键 | | Tab 右键菜单 | 关闭 / 关闭其他页签 / 关闭左侧页签 / 关闭右侧页签(当前标签组) | @@ -566,6 +569,7 @@ make clean # 清理 lib/、*.tgz、playwright-report/、test-results/ ## ⚠️ 已知限制 - Git 无 push/pull/fetch;Markdown 预览提供手动刷新按钮,刷新未保存编辑前会确认是否丢弃草稿;无文件 watcher/自动轮询;工具行内文件打开按钮不可拦截 +- 未保存草稿:关闭标签页、删除文件、浏览器刷新/关闭页面都会先确认(`Ctrl/Cmd + F` 的查找面板只作用于编辑器,不做跨文件搜索);磁盘上被其他来源改动后再保存会被拒绝(提示「重新载入」),不会静默覆盖对方字节 - 终端 Tab 拖到另一分栏会重挂载(shell 重开) - Office 三件套预览(.docx/.xlsx/.pptx)已移至「推荐插件」(Office 预览插件,见设置页「添加插件」弹窗);未安装时此类文件走代码/下载查看兜底 - 浏览器沙箱无登录态/第三方 Cookie 受限,部分站点登录需走弹窗;被 `X-Frame-Options`/`frame-ancestors` 拒绝嵌入的站点(如 arxiv.org)显示原因面板(含「在浏览器中打开」);iframe 内部跳转不进后退栈 diff --git a/README_EN.md b/README_EN.md index f129fe3d..d5628382 100644 --- a/README_EN.md +++ b/README_EN.md @@ -516,6 +516,9 @@ All changes since v0.14.0: | Action | Keys | |---|---| | Save edits | `Ctrl/Cmd + S` | +| Find / replace in the editor | `Ctrl/Cmd + F` / `Ctrl/Cmd + H` | +| Find next / previous | `Ctrl/Cmd + G` / `Shift + Ctrl/Cmd + G` (in the panel: `Enter` / `Shift + Enter`) | +| Select next occurrence | `Ctrl/Cmd + D` | | Git commit | `Ctrl + Enter` | | Close tab | Middle mouse button | | Tab context menu (right-click) | Close / Close Other Tabs / Close Tabs to the Left / Close Tabs to the Right (current pane) | @@ -567,6 +570,7 @@ make clean # remove lib/, *.tgz, playwright-report/, test-results/ ## ⚠️ Known Limitations - Git has no push/pull/fetch; Markdown previews provide a manual refresh button with confirmation before discarding unsaved edits; no file watcher or automatic polling; tool inline file-open buttons cannot be intercepted +- Unsaved drafts: closing a tab, deleting the file, and refreshing/closing the page all confirm first (the `Ctrl/Cmd + F` panel searches the open editor only, not across files); a save is refused when the file changed on disk since it was loaded (a "Reload from disk" action is offered) instead of silently overwriting those bytes - Dragging a terminal tab to another pane remounts it (shell restarts) - Office-suite preview (.docx/.xlsx/.pptx) moved to the recommended office plugin (see the "Add plugins" modals in settings); without it these files fall through to the code/download fallbacks - Browser sandbox has no login state / third-party cookies are restricted; some sites need popup login; sites that refuse embedding via `X-Frame-Options`/`frame-ancestors` (e.g. arxiv.org) show a reason panel (with "Open in browser"); in-iframe navigation does not enter the back stack diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index 0dac147a..da02c0c9 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -416,12 +416,14 @@ interface FileViewerProps { viewerId: string // 命中 viewer 的 id(如 'code' / 'my-plugin:csv') content?: string // fetchStrategy='fsRead' 时 truncated?: boolean // fetchStrategy='fsRead' 时 + mtimeMs?: number // fetchStrategy='fsRead' 时:本次读取的磁盘 mtime(保存冲突基线) mediaUrl?: string // fetchStrategy='mediaUrl' 时 customData?: unknown // fetchStrategy='custom' 时(load() 的返回值) // 以下为内置文本编辑器与 EditorHost 内部协作字段,外部 viewer 忽略: toolbar?: 'self' | 'host' onToolbarState?: (state: EditorToolbarState) => void onToolbarControls?: (controls: EditorToolbarControls | null) => void + onReload?: () => void // 从磁盘重新加载(保存冲突横幅的按钮回调) } ``` @@ -522,8 +524,8 @@ const { value } = await res.json() // 错误时 { ok: false, error: { code, me |---|---| | `session.cwd` | 会话权威 cwd(`{ cwd, root, parent }`) | | `fs.tree` | 目录列表(`{ path, entries: FsEntry[], truncated }`;FsEntry 含 `isSymlink`/`broken`,目录软链接的 `isDir` 按目标类型) | -| `fs.read` | 读文件:文本返回 `{ kind: 'text', content, truncated }`;二进制返回 `{ kind: 'binary', size, truncated, head }`(head = base64 前 4KB) | -| `fs.write` | 原子写文件 | +| `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 }`(新基线)。临时文件为随机命名的同目录兄弟文件,同一路径的并发保存互不干扰 | | `git.status` / `git.diff` / `git.log` 等 | 全套 Git 只读 + 写操作 | | `pty.close` / `agent-pty.close` | 释放终端(外部 tab 一般用不到) | | `settings.get` / `settings.update` | 侧边栏偏好读写(revision 守卫) | diff --git a/docs/plans/2026-09-09-editor-draft-protection-design.md b/docs/plans/2026-09-09-editor-draft-protection-design.md new file mode 100644 index 00000000..b6ddafd4 --- /dev/null +++ b/docs/plans/2026-09-09-editor-draft-protection-design.md @@ -0,0 +1,82 @@ +# 编辑器未保存草稿保护 + 保存冲突检测 + 内置查找替换 + +> 状态:已实施(2026-09-09)。三项改动都在内置文本编辑器/侧边栏这一侧,不改 `ctx.betterSidebar` 的服务方法签名,不碰 DSH 源码。 + +## 1. 背景 + +三个独立但相邻的问题,都出在「编辑器与磁盘」的边界上: + +| 问题 | 现象 | 根因(实施前) | +|---|---|---| +| A 草稿静默丢失 | 关闭标签页 / 删文件 / 刷新页面,未保存的编辑直接消失 | 脏稿确认只挂在**手动刷新按钮**上(`EditorHost.refreshFile`);关 tab 走 `closeTab`,删文件走 `closePathTabs`,两者都不问;全仓库无 `beforeunload` | +| B 保存覆盖他人写入 | 模型(或另一个标签页 / 外部编辑器)改了同一个文件后,用户在旧草稿上 `Ctrl/Cmd + S`,对方的字节被静默覆盖 | `fs.write` 无并发基线;客户端也没有 mtime 概念 | +| C 并发写互删临时文件 | 同一文件两次保存同时进行时,其中一次报 `ENOENT` | 临时文件名固定为 `${path}.dsh-sidebar-tmp-${process.pid}`,先完成者的 `rm(tmp)` 会删掉后完成者的临时文件 | +| D 编辑器没有查找替换 | `Ctrl/Cmd + F` 无反应 | `@codemirror/search` 在 `dependencies` 里但 `src/` 零引用(依赖白装) | + +## 2. 设计 + +### 2.1 脏稿登记表(`src/client/editor-dirty.ts`,新增) + +模块级 `Map` + 监听器集合 + 单调 `revision`(供 `useSyncExternalStore` 取稳定快照)。写入方只有一处:`EditorHost` 的工具栏报告已经带 `dirty`,直接转发即可(不为外部 viewer 造新契约)。 + +```ts +setEditorDirty(tabId, dirty, sessionId, path) // 登记 / 清除(相同条目不抖动 revision) +clearEditorDirty(tabId) // 宿主卸载 +isEditorDirty(tabId) / dirtyCount() / dirtyCountForSession(sessionId) +confirmDiscardDraft(tabId, message) // 统一确认入口 +subscribeEditorDirty(fn) / editorDirtyRevision() +``` + +`EditorHost` 的登记 effect 依赖 `[tab.id, toolbar?.dirty, scope.sessionId, path, isDir]`,**卸载时 `clearEditorDirty`**——tab 关闭、会话切换、就地换文件都会经过卸载,因此条目不会比草稿活得更久。 + +### 2.2 三个关闭路径共用一次确认 + +| 路径 | 接线 | +|---|---| +| 标签页 X / 中键 / 右键菜单「关闭(其他/左/右)」 | `Sidebar.actions.closeTab` 开头 `if (!confirmDiscardDraft(tabId, t('closeUnsavedConfirm'))) return` | +| 文件树删除(含目录递归关闭) | `closePathTabs(ctx, store, target, message)` 内部逐个 `confirmDiscardDraft`;文案由调用方(`EditorHost.onPathDeleted`)传入,`tree-mutations.ts` 保持无 i18n 依赖 | +| 浏览器刷新 / 关页 / 导航 | `Sidebar` 的 `beforeunload` 监听:`dirtyCount() === 0` 时直接放行;`dirtyCount()` 而非当前会话,因为页面整个要走了 | + +`confirmDiscardDraft` 在确认后**立即清除条目**,因此同一次关闭动作里「右键菜单连续关闭多个脏 tab」不会对同一个 tab 重复弹窗。拒绝删除时标签页保留(其下一次保存会重建文件——这是用户的决定)。 + +### 2.3 保存的乐观并发门(`fs.write`) + +协议(向后兼容,两个字段都可省): + +``` +fs.read → { kind: 'text', content, truncated, mtimeMs } // 新增 mtimeMs + | { kind: 'binary', size, truncated, mtimeMs, head } +fs.write → { path, content, expectedMtimeMs? } + ← { ok: true, mtimeMs } // 新基线 + ← 409 { code: 'fs-conflict' } // 基线不符 +``` + +- host:`expectedMtimeMs` 存在且与 `stat(path).mtimeMs` 不等 → `SidebarError('fs-conflict', …, 409)`,**在写临时文件之前**判定,不留垃圾。文件不存在(`stat` 失败)视作无基线。 +- client:`EditorHost` 把 `fsRead` 的 `mtimeMs` 透传进 `FileViewerProps.mtimeMs`;`TextEditor` 用 `mtimeRef` 持有它(`null` = 文件原本不存在),保存成功后采纳响应里的新基线。 +- 冲突表现:`saveState` 回到 `idle` + 一条警告横幅(文案 `saveConflict`)+「重新载入」按钮 → `FileViewerProps.onReload` → `EditorHost.refreshFile`(那条已有的、会先确认脏稿的刷新路径)。**草稿不丢**。 + +### 2.4 并发写互删修复 + +临时文件改为 `.${basename(path)}.dsh-write-${randomUUID()}.tmp`(`fs-operations.ts` 上传路由的同款做法):每次保存有自己的临时兄弟文件,任何一次 `rm(tmp)` 都只可能删到自己的。 + +### 2.5 内置查找/替换 + +`TextEditor` 的 CodeMirror 扩展增加 `search({ top: true })` + `searchKeymap`(`Ctrl/Cmd+F`、`Ctrl/Cmd+H`、`Ctrl/Cmd+G`…),并用 `EditorState.phrases.of(...)` 把面板文案接进本插件词典(CodeMirror 默认只有英文)。工具栏新增放大镜按钮:预览态下先切到编辑态再开面板(面板挂在 CodeMirror 表面上)。文案在打开面板时求值,切换语言后下次 `Ctrl/Cmd+F` 即生效。 + +## 3. 测试 + +| 文件 | 覆盖 | +|---|---| +| `tests/editor-unsaved-guard.spec.tsx`(新,8 例) | 登记表语义(幂等 / 换文件重指向 / 订阅);`EditorHost` 登记与卸载清理;**真 Sidebar** 下取消保留 / 确认关闭 / 干净不弹窗;`confirmDiscardDraft` 分支;`closePathTabs` 的拒绝与确认 | +| `tests/fs-write-route.spec.ts`(新,5 例) | 并发同路径保存无交叉删除、无残留;重复保存;基线不符 409 + 对方字节存活;基线相符成功并回报新基线;省略基线仍可写(旧调用方) | +| `tests/text-editor-conflict.spec.tsx`(新,4 例) | 发送基线 mtime;`fs-conflict` 显示横幅且草稿保留、「重新载入」回调触发;普通失败不显示冲突横幅;成功后采纳新基线 | +| `tests/text-editor-search.spec.tsx`(新,4 例) | 工具栏按钮开面板并切到编辑态;en / zh 文案;`Mod-f` 打开面板 | +| `tests/locales.spec.ts`(既有) | 每个第三语言词典与 zh 键集相等(新增 12 个 key 已同步 19 个词典) | + +## 4. 已知偏差与取舍 + +- **`fs.write` 的基线不是内容哈希**:mtime 足够挡住「模型改了文件」这类秒级以上的改动,且零额外 IO;同一毫秒内的并发写仍可能双双通过(此时以最后一次 rename 为准)。要更强一致需内容哈希,代价是每次保存多读一遍文件,暂不引入。 +- **Windows 上并发 rename 可能报 EPERM**(文件被杀软/句柄短暂占用):这是平台行为,与本次修复的「互删临时文件」无关;`tests/fs-write-route.spec.ts` 的并发用例显式允许 EPERM 但拒绝 ENOENT,并断言无残留。 +- **外部 viewer 不参与脏稿保护**:只有内置文本编辑器会报告 `dirty`。第三方 viewer 若想接入,需要自己调用 `setEditorDirty`(当前未开放为服务 API,因为还没有第二个真实消费者)。 +- **跨会话切换不弹窗**:切换会话时未保存草稿会随组件卸载消失。页面级 `beforeunload` 覆盖了「关页/刷新」,会话内切换留待有真实需求时再加(会话切换本身是用户主动且可预期的操作)。 +- **未做跨文件搜索**:`Ctrl/Cmd+F` 只作用于当前编辑器;按仓库既定理念,跨文件代码搜索留给生态插件(`pluginCodeNav`)。 diff --git a/src/client/EditorHost.tsx b/src/client/EditorHost.tsx index d09b2817..95d60dc0 100644 --- a/src/client/EditorHost.tsx +++ b/src/client/EditorHost.tsx @@ -31,6 +31,7 @@ import { api, isOutsideWorkspaceMessage, mediaUrl, type SessionScope } from './a import { BinaryDownload } from './binary-download.tsx' import { FenceErrorNotice } from './FenceErrorNotice.tsx' import { planFirstMatch, planFsReadOutcome, type EditorLoadAction } from './editor-load.ts' +import { clearEditorDirty, setEditorDirty } from './editor-dirty.ts' import { baseName } from './FileTree.tsx' import { createFrameBatcher } from './frame-batcher.ts' import { openSidebarFile } from './intercept.tsx' @@ -48,7 +49,7 @@ import css from './sidebar.module.css' type EditorLoad = | { status: 'loading' } | { status: 'error'; message: string } - | { status: 'ready'; viewer: FileViewerDescriptor; content?: string; truncated?: boolean; mediaUrl?: string; customData?: unknown } + | { status: 'ready'; viewer: FileViewerDescriptor; content?: string; truncated?: boolean; mtimeMs?: number; mediaUrl?: string; customData?: unknown } | { status: 'binary' } /** The docked tree panel's width bounds (drag-resize clamps into them). */ @@ -233,7 +234,7 @@ export function EditorHost(props: { retargetPathTabs(ctx, store, oldPath, newPath) } const onPathDeleted = (path: string): void => { - closePathTabs(ctx, store, path) + closePathTabs(ctx, store, path, t('closeUnsavedConfirm')) } // The viewer's toolbar, hoisted into THIS header: the text editor reports @@ -248,6 +249,17 @@ export function EditorHost(props: { controlsRef.current = controls }, []) + // Publish this tab's unsaved-draft state to the close/unload guards: the + // toolbar report already carries `dirty`, so no extra plumbing is needed. + // A path-less window (the files home) and folder windows never register. + // The cleanup clears on unmount (tab closed, session switched, in-place + // path switch remounts the viewer) so a guard can never outlive its draft. + useEffect(() => { + if (path === '' || isDir) return + setEditorDirty(tab.id, toolbar?.dirty === true, scope.sessionId, path) + return () => { clearEditorDirty(tab.id) } + }, [tab.id, toolbar?.dirty, scope.sessionId, path, isDir]) + // The docked panel's drag-resize: pointer capture on the handle itself // (no window listeners — the captured pointer keeps tracking even off the // handle). Local width while dragging, persisted into meta.treeWidth on @@ -339,7 +351,10 @@ export function EditorHost(props: { truncated: result.truncated, head: result.kind === 'binary' ? result.head : undefined, }, (head) => ctx.get('betterSidebar')?.matchFileViewer(path, head), mediaUrlOf) - apply(outcome) + // Carry the read's mtime into the rendered viewer: the text + // editor uses it as the save baseline (fs-conflict on drift). + if (outcome.kind === 'render') setLoad({ ...outcome, status: 'ready', mtimeMs: result.mtimeMs }) + else apply(outcome) }).catch((error: unknown) => { if (cancelled) return setLoad({ status: 'error', message: error instanceof Error ? error.message : String(error) }) @@ -488,12 +503,14 @@ export function EditorHost(props: { viewerId: load.viewer.id, content: load.content, truncated: load.truncated, + mtimeMs: load.mtimeMs, mediaUrl: load.mediaUrl, customData: load.customData, // The viewer's toolbar always hoists into this host's header. toolbar: 'host', onToolbarState, onToolbarControls, + onReload: refreshFile, })} {treeOpen && ( diff --git a/src/client/Sidebar.tsx b/src/client/Sidebar.tsx index f20ce7ad..2372ef2b 100644 --- a/src/client/Sidebar.tsx +++ b/src/client/Sidebar.tsx @@ -51,6 +51,7 @@ import { getWcoSnapshot, subscribeWco } from './wco.ts' import { getShellPreset } from './shell-presets.ts' import { computeTitleBarStrip } from './titlebar-strip.ts' import { TabContent, buildNewTabOptions } from './sidebar/TabContent.tsx' +import { confirmDiscardDraft, dirtyCount, editorDirtyRevision, subscribeEditorDirty } from './editor-dirty.ts' import { useCenterColumn } from './sidebar/use-center-column.ts' import { useHostFeeds } from './sidebar/use-host-feeds.ts' import { usePinnedTabs } from './sidebar/use-pinned-tabs.ts' @@ -224,6 +225,24 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) { const state = snapshot.state const sessionId = snapshot.sessionId + + // Unload guard: a browser refresh / tab close / navigation would drop every + // open unsaved draft at once. The listener is armed only while at least one + // draft is dirty (subscribeEditorDirty fires on every register/clear), so a + // clean session navigates away without a prompt. Every session's drafts + // count — the page is going away, not just the visible conversation. The + // message itself is the browser's own generic warning (custom text ignored). + const dirtyRevision = useSyncExternalStore(subscribeEditorDirty, () => editorDirtyRevision()) + useEffect(() => { + const onBeforeUnload = (event: BeforeUnloadEvent): void => { + if (dirtyCount() === 0) return + event.preventDefault() + event.returnValue = '' + } + window.addEventListener('beforeunload', onBeforeUnload) + return () => { window.removeEventListener('beforeunload', onBeforeUnload) } + }, [dirtyRevision]) + const summaryCwd = sessionId === undefined ? undefined : sessionList.byId[sessionId]?.cwd const pushedBottomHeight = (bottomOpen: boolean, bottomHeight: number): number => layoutPushSize({ narrow, @@ -662,6 +681,11 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) { const actions: WorkbenchActions = useMemo(() => ({ closeTab: (paneId, tabId) => { + // An unsaved editor draft would be dropped by the unmount — ask first. + // The confirmation is the SAME guard the refresh button uses, so every + // close path (tab X, middle click, tab context menu, the tree's + // close-on-rename/delete) funnels through here and warns exactly once. + if (!confirmDiscardDraft(tabId, t('closeUnsavedConfirm'))) return // A closed terminal releases its pty immediately — including when its // socket is mid-reconnect, where the unmount close frame never reaches // the host and the process would hold the quota until the grace ends. diff --git a/src/client/TextEditor.tsx b/src/client/TextEditor.tsx index 8617274f..6432a177 100644 --- a/src/client/TextEditor.tsx +++ b/src/client/TextEditor.tsx @@ -19,9 +19,10 @@ import clsx from 'clsx' import { EditorState } from '@codemirror/state' import { EditorView as CodeMirrorView, keymap, lineNumbers } from '@codemirror/view' import { defaultKeymap, history, historyKeymap } from '@codemirror/commands' -import { IconCheckOutline16, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives' +import { openSearchPanel, search, searchKeymap } from '@codemirror/search' +import { IconCheckOutline16, IconSearchOutline16, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives' import { markdownTextProps } from './markdown-labels.tsx' -import { api, htmlUrl } from './api.ts' +import { api, htmlUrl, SidebarApiError } from './api.ts' import { markdownPreviewSource } from './markdown-frontmatter.ts' import { rewriteLocalImageUrls } from './markdown-images.ts' import { languageForPath } from './lang.ts' @@ -51,6 +52,28 @@ type ViewMode = 'preview' | 'edit' const previewScrollMemory = new Map() const previewScrollKey = (scope: { sessionId: string }, path: string): string => `${scope.sessionId}::${path}` +/** + * The CodeMirror search panel's labels, resolved from this plugin's own + * dictionary at call time (the panel reads them per open, so a live locale + * switch is picked up on the next Ctrl/Cmd+F). CodeMirror's built-in strings + * are English-only; the keys mirror its `phrase()` calls exactly. + */ +function searchPhrases(): Record { + return { + Find: t('find'), + Replace: t('replace'), + next: t('findNext'), + previous: t('findPrevious'), + all: t('findAll'), + 'match case': t('findMatchCase'), + regexp: t('findRegexp'), + 'by word': t('findByWord'), + replace: t('replaceOne'), + 'replace all': t('replaceAll'), + close: t('close'), + } +} + export function TextEditor(props: FileViewerProps) { const { ctx, scope, path, viewerId, content, truncated } = props const [mode, setMode] = useState('preview') @@ -58,9 +81,15 @@ export function TextEditor(props: FileViewerProps) { const [draft, setDraft] = useState(null) const [dirty, setDirty] = useState(false) const [saveState, setSaveState] = useState<'idle' | 'saving' | 'saved' | 'failed'>('idle') + /** The save was refused because the file changed on disk (fs-conflict). */ + const [conflict, setConflict] = useState(false) const hostRef = useRef(null) const viewRef = useRef(null) const savingRef = useRef(false) + /** The mtime the draft is based on (`null` = the file did not exist yet). + * Seeded from the load, refreshed by every successful save, and reset by + * the file-switch effect. */ + const mtimeRef = useRef(props.mtimeMs ?? null) /** The theme compartment of the current view (reconfigured on scheme flip). */ const themeCompRef = useRef(null) /** The app's resolved color scheme; the editor re-themes in place on flips. */ @@ -107,6 +136,9 @@ export function TextEditor(props: FileViewerProps) { setDraft(null) setDirty(false) setSaveState('idle') + setConflict(false) + // The freshly loaded bytes are the new save baseline. + mtimeRef.current = props.mtimeMs ?? null selectionPopup.hide() // hide() reads a live ref; the reset must fire only on a content (file) // swap, and the hook object's identity churns on every render. @@ -144,6 +176,12 @@ export function TextEditor(props: FileViewerProps) { CodeMirrorView.contentAttributes.of({ spellcheck: 'false' }), cmSurfaceTheme, themeComp.of(dark), + // Find / replace (Ctrl/Cmd+F, Ctrl/Cmd+H): the panel opens at the + // top (the editor header is directly above it), all matches are + // highlighted, and the labels follow the sidebar's own dictionary + // (CodeMirror's defaults are English-only) through the phrases facet. + EditorState.phrases.of(searchPhrases()), + search({ top: true }), ...(language !== null ? [language] : []), CodeMirrorView.updateListener.of((update) => { if (update.docChanged) { @@ -158,6 +196,7 @@ export function TextEditor(props: FileViewerProps) { }, ...defaultKeymap, ...historyKeymap, + ...searchKeymap, ]), // Selection popup (the code and markdown editors): a non-empty // selection anchors the floating "add to conversation" button above @@ -292,13 +331,26 @@ export function TextEditor(props: FileViewerProps) { if (view === null || savingRef.current) return savingRef.current = true setSaveState('saving') - api.fsWrite(scope, path, view.state.doc.toString()).then(() => { + // Optimistic concurrency: the draft was based on the bytes read at + // `mtimeMs`; a file that changed on disk since is REFUSED (fs-conflict) + // instead of clobbering whatever wrote it (the model, another tab, an + // external editor). `null` = the file did not exist when loaded. + api.fsWrite(scope, path, view.state.doc.toString(), mtimeRef.current ?? null).then((result) => { savingRef.current = false + // Adopt the fresh baseline the host reports (absent on a stat failure — + // keep the old one, the next save just re-checks). + if (typeof result.mtimeMs === 'number') mtimeRef.current = result.mtimeMs setDraft(null) setDirty(false) + setConflict(false) setSaveState('saved') - }).catch(() => { + }).catch((error: unknown) => { savingRef.current = false + if (error instanceof SidebarApiError && error.code === 'fs-conflict') { + setConflict(true) + setSaveState('idle') + return + } setSaveState('failed') }) } @@ -454,6 +506,26 @@ export function TextEditor(props: FileViewerProps) { )} {dirty && } + {editable && ( + + )} {editable && ( + + )}
('fs.search', scopePayload(scope, { query }), signal), fsRead: (scope: SessionScope, path: string, signal?: AbortSignal) => call('fs.read', scopePayload(scope, { path }), signal), - fsWrite: (scope: SessionScope, path: string, content: string) => - call<{ ok: true }>('fs.write', scopePayload(scope, { path, content })), + /** 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. */ + fsWrite: (scope: SessionScope, path: string, content: string, expectedMtimeMs?: number | null) => + call<{ ok: true; mtimeMs?: number }>('fs.write', scopePayload(scope, { + path, + content, + ...(expectedMtimeMs !== undefined ? { expectedMtimeMs } : {}), + })), /** Rename one tree row within its directory (single-segment name; the * server refuses existing destinations, the workspace root, and — while * the fence is armed — anything resolving outside the workspace). */ diff --git a/src/client/editor-dirty.ts b/src/client/editor-dirty.ts new file mode 100644 index 00000000..d8708144 --- /dev/null +++ b/src/client/editor-dirty.ts @@ -0,0 +1,106 @@ +/** + * Unsaved-edit registry: which editor tabs currently hold a draft that + * differs from disk. The editor host registers its tab's dirty state here + * (the toolbar report already carries it), so the flows that would silently + * drop the draft can ask first: + * + * - the sidebar's tab close (the X button, the middle click, the tab context + * menu, and the tree's close-on-rename/delete path all land there), + * - the browser unload (refresh / close tab / navigate away) through a + * `beforeunload` guard. + * + * Module-level and keyed by tab id — the same "one instance per client plugin + * activation" lifetime the store has, since the module only loads with the + * client bundle. An entry is written while a tab is dirty and deleted the + * moment it goes clean (save) or its host unmounts (tab closed, session + * switched), so a stale entry can never keep a guard armed. + */ + +/** One registered draft: the owning session (the guard's scope) and the file. */ +interface DirtyEntry { + sessionId: string + path: string +} + +const dirtyTabs = new Map() +const listeners = new Set<() => void>() +/** Monotonic change counter: a stable `useSyncExternalStore` snapshot. */ +let revision = 0 + +/** Notify every subscriber (the `beforeunload` guard). */ +function notify(): void { + revision += 1 + for (const listener of [...listeners]) listener() +} + +/** + * Publish one tab's dirty state: `true` registers the draft (session + path + * ride along for scoped queries), `false` / `undefined` clears it. + */ +export function setEditorDirty(tabId: string, dirty: boolean, sessionId: string, path: string): void { + const had = dirtyTabs.has(tabId) + if (!dirty) { + if (had) { + dirtyTabs.delete(tabId) + notify() + } + return + } + const previous = dirtyTabs.get(tabId) + if (previous !== undefined && previous.sessionId === sessionId && previous.path === path) return + dirtyTabs.set(tabId, { sessionId, path }) + notify() +} + +/** Drop a tab's entry (its editor host unmounted). Idempotent. */ +export function clearEditorDirty(tabId: string): void { + if (dirtyTabs.delete(tabId)) notify() +} + +/** Whether one tab holds an unsaved draft. */ +export function isEditorDirty(tabId: string): boolean { + return dirtyTabs.has(tabId) +} + +/** How many tabs of one session hold unsaved drafts. */ +export function dirtyCountForSession(sessionId: string): number { + let count = 0 + for (const entry of dirtyTabs.values()) { + if (entry.sessionId === sessionId) count += 1 + } + return count +} + +/** How many tabs hold unsaved drafts across every session (the unload guard). */ +export function dirtyCount(): number { + return dirtyTabs.size +} + +/** Subscribe to dirty-set changes; returns the disposer. */ +export function subscribeEditorDirty(listener: () => void): () => void { + listeners.add(listener) + return () => { listeners.delete(listener) } +} + +/** The change counter (a stable `useSyncExternalStore` snapshot). */ +export function editorDirtyRevision(): number { + return revision +} + +/** + * Ask before dropping `tabId`'s unsaved draft. Returns true when the caller + * may proceed (the tab is clean, the user confirmed, or no `confirm` is + * available — the same fallback the refresh guard uses). On confirm the + * entry is cleared immediately, so a follow-up close in the same tick does + * not double-prompt; the editor host's own cleanup would do it one commit + * later anyway. + * + * Shared by the sidebar's tab close and the file tree's close-on-delete so + * both paths warn exactly once, with the same copy. + */ +export function confirmDiscardDraft(tabId: string, message: string): boolean { + if (!dirtyTabs.has(tabId)) return true + const confirmed = typeof window.confirm === 'function' ? window.confirm(message) : true + if (confirmed) clearEditorDirty(tabId) + return confirmed +} diff --git a/src/client/locales-ar.ts b/src/client/locales-ar.ts index cc66eec0..89e9dca4 100644 --- a/src/client/locales-ar.ts +++ b/src/client/locales-ar.ts @@ -117,12 +117,24 @@ export const ar: Record = { mermaidZoomReset: 'إعادة تعيين', mermaidZoomHint: 'العجلة للتقريب · السحب للتحريك · Esc للإغلاق', refresh: 'تحديث', + find: 'بحث', + replace: 'استبدال', + findNext: 'التالي', + findPrevious: 'السابق', + findAll: 'تحديد الكل', + findMatchCase: 'مطابقة حالة الأحرف', + findRegexp: 'تعبير نمطي', + findByWord: 'كلمة كاملة', + replaceOne: 'استبدال', + replaceAll: 'استبدال الكل', showInFolder: 'إظهار في المجلد', refreshUnsavedConfirm: 'تغيّر الملف على القرص. سيؤدي التحديث إلى فقدان التعديلات غير المحفوظة. متابعة؟', + closeUnsavedConfirm: 'يحتوي هذا الملف على تعديلات غير محفوظة. سيؤدي إغلاق علامة التبويب إلى تجاهلها. المتابعة؟', save: 'حفظ', saved: 'تم الحفظ', unsaved: 'غير محفوظ', saveFailed: 'فشل الحفظ', + saveConflict: 'تم تغيير الملف على القرص من مصدر آخر. تم إيقاف الحفظ، وتعديلاتك ما زالت في المحرر.', saveConflictReload: 'إعادة التحميل من القرص', truncation: 'الملف كبير جداً — عرض أول 512KB', binary: 'ملف ثنائي، المعاينة غير متاحة', loading: 'جارٍ التحميل…', diff --git a/src/client/locales-de.ts b/src/client/locales-de.ts index d34b3820..be4f28e3 100644 --- a/src/client/locales-de.ts +++ b/src/client/locales-de.ts @@ -102,12 +102,24 @@ export const de: Record = { mermaidZoomReset: 'Zurücksetzen', mermaidZoomHint: 'Scrollen zum Zoomen · Ziehen zum Verschieben · Esc zum Schließen', refresh: 'Aktualisieren', + find: 'Suchen', + replace: 'Ersetzen', + findNext: 'Weiter', + findPrevious: 'Zurück', + findAll: 'Alle auswählen', + findMatchCase: 'Groß-/Kleinschreibung', + findRegexp: 'Regex', + findByWord: 'Ganzes Wort', + replaceOne: 'Ersetzen', + replaceAll: 'Alle ersetzen', showInFolder: 'Im Ordner anzeigen', refreshUnsavedConfirm: 'Die Datei wurde geändert. Beim Aktualisieren gehen ungespeicherte Änderungen verloren. Fortfahren?', + closeUnsavedConfirm: 'Diese Datei hat ungespeicherte Änderungen. Beim Schließen des Tabs gehen sie verloren. Fortfahren?', save: 'Speichern', saved: 'Gespeichert', unsaved: 'Nicht gespeichert', saveFailed: 'Speichern fehlgeschlagen', + saveConflict: 'Die Datei wurde auf der Platte von anderer Stelle geändert. Speichern abgebrochen; Ihre Änderungen bleiben im Editor.', saveConflictReload: 'Inhalt von der Platte neu laden', truncation: 'Datei zu groß – nur die ersten 512KB werden angezeigt', binary: 'Binärdatei, Vorschau nicht verfügbar', loading: 'Wird geladen…', diff --git a/src/client/locales-fr.ts b/src/client/locales-fr.ts index 567fffd3..3e28a892 100644 --- a/src/client/locales-fr.ts +++ b/src/client/locales-fr.ts @@ -109,12 +109,25 @@ export const fr: Record = { mermaidZoomReset: 'Réinitialiser', mermaidZoomHint: 'Molette pour zoomer · glisser pour déplacer · Échap pour fermer', refresh: 'Actualiser', + find: 'Rechercher', + replace: 'Remplacer', + findNext: 'Suivant', + findPrevious: 'Précédent', + findAll: 'Tout sélectionner', + findMatchCase: 'Respecter la casse', + findRegexp: 'Regex', + findByWord: 'Mot entier', + replaceOne: 'Remplacer', + replaceAll: 'Tout remplacer', showInFolder: 'Afficher dans le dossier', refreshUnsavedConfirm: 'Le fichier a changé sur le disque. Actualiser supprimera les modifications non enregistrées. Continuer ?', + closeUnsavedConfirm: 'Ce fichier contient des modifications non enregistrées. Fermer l\'onglet les perdra. Continuer ?', save: 'Enregistrer', saved: 'Enregistré', unsaved: 'Non enregistré', saveFailed: 'Échec de l’enregistrement', + saveConflict: 'Le fichier a été modifié sur le disque par une autre source. Enregistrement interrompu ; vos modifications restent dans l\'éditeur.', + saveConflictReload: 'Recharger depuis le disque', truncation: 'Fichier trop volumineux, seuls les 512 premiers Ko sont affichés', binary: 'Fichier binaire, aperçu impossible', loading: 'Chargement…', diff --git a/src/client/locales-hi.ts b/src/client/locales-hi.ts index 3c0ee0b5..70a60cef 100644 --- a/src/client/locales-hi.ts +++ b/src/client/locales-hi.ts @@ -116,12 +116,24 @@ export const hi: Record = { mermaidZoomReset: 'रीसेट', mermaidZoomHint: 'स्क्रॉल से ज़ूम · खींचें पैन करने · Esc से बंद', refresh: 'ताज़ा करें', + find: 'खोजें', + replace: 'बदलें', + findNext: 'अगला', + findPrevious: 'पिछला', + findAll: 'सभी चुनें', + findMatchCase: 'केस मिलाएँ', + findRegexp: 'रेगुलर एक्सप्रेशन', + findByWord: 'पूरा शब्द', + replaceOne: 'बदलें', + replaceAll: 'सभी बदलें', showInFolder: 'फ़ोल्डर में दिखाएँ', refreshUnsavedConfirm: 'डिस्क पर फ़ाइल बदल गई है। रीफ़्रेश करने पर असहेज किए गए संपादन खो जाएँगे। जारी रखें?', + closeUnsavedConfirm: 'इस फ़ाइल में सहेजे नहीं गए संपादन हैं। टैब बंद करने पर वे हट जाएँगे। जारी रखें?', save: 'सहेजें', saved: 'सहेजा गया', unsaved: 'असहेजित', saveFailed: 'सहेजना विफल', + saveConflict: 'फ़ाइल डिस्क पर किसी अन्य स्रोत से बदल दी गई है। सहेजना रोक दिया गया; आपके संपादन एडिटर में बने हुए हैं।', saveConflictReload: 'डिस्क से फिर लोड करें', truncation: 'फ़ाइल बहुत बड़ी — पहले 512KB दिखाए जा रहे', binary: 'बाइनरी फ़ाइल, पूर्वावलोकन अनुपलब्ध', loading: 'लोड हो रहा…', diff --git a/src/client/locales-id.ts b/src/client/locales-id.ts index 45a10024..3893a532 100644 --- a/src/client/locales-id.ts +++ b/src/client/locales-id.ts @@ -114,12 +114,24 @@ export const id: Record = { mermaidZoomReset: 'Reset', mermaidZoomHint: 'Gulir untuk zoom · seret untuk geser · Esc untuk tutup', refresh: 'Segarkan', + find: 'Cari', + replace: 'Ganti', + findNext: 'Berikutnya', + findPrevious: 'Sebelumnya', + findAll: 'Pilih semua', + findMatchCase: 'Cocokkan huruf besar/kecil', + findRegexp: 'Regex', + findByWord: 'Kata utuh', + replaceOne: 'Ganti', + replaceAll: 'Ganti semua', showInFolder: 'Tampilkan di folder', refreshUnsavedConfirm: 'File berubah di disk. Menyegarkan akan membuang edit yang belum disimpan. Lanjutkan?', + closeUnsavedConfirm: 'File ini memiliki edit yang belum disimpan. Menutup tab akan membuangnya. Lanjutkan?', save: 'Simpan', saved: 'Tersimpan', unsaved: 'Belum disimpan', saveFailed: 'Gagal menyimpan', + saveConflict: 'File diubah di disk oleh sumber lain. Penyimpanan dihentikan; edit Anda tetap ada di editor.', saveConflictReload: 'Muat ulang dari disk', truncation: 'Berkas terlalu besar — menampilkan 512KB pertama', binary: 'Berkas biner, pratinjau tidak tersedia', loading: 'Memuat…', diff --git a/src/client/locales-it.ts b/src/client/locales-it.ts index a7ab1433..d75b83fd 100644 --- a/src/client/locales-it.ts +++ b/src/client/locales-it.ts @@ -107,12 +107,25 @@ export const it: Record = { mermaidZoomReset: 'Ripristina', mermaidZoomHint: 'Scorra per zoom · trascini per panoramica · Esc per chiudere', refresh: 'Aggiorna', + find: 'Cerca', + replace: 'Sostituisci', + findNext: 'Successivo', + findPrevious: 'Precedente', + findAll: 'Seleziona tutto', + findMatchCase: 'Maiuscole/minuscole', + findRegexp: 'Regex', + findByWord: 'Parola intera', + replaceOne: 'Sostituisci', + replaceAll: 'Sostituisci tutto', showInFolder: 'Mostra nella cartella', refreshUnsavedConfirm: 'Il file è cambiato su disco. Aggiornare scarterà le modifiche non salvate. Continuare?', + closeUnsavedConfirm: 'Questo file ha modifiche non salvate. Chiudere la scheda le perderà. Continuare?', save: 'Salva', saved: 'Salvato', unsaved: 'Non salvato', saveFailed: 'Salvataggio non riuscito', + saveConflict: 'Il file è stato modificato su disco da un\'altra origine. Salvataggio annullato; le modifiche restano nell\'editor.', + saveConflictReload: 'Ricarica dal disco', truncation: 'File troppo grande — vengono mostrati i primi 512KB', binary: 'File binario, anteprima non disponibile', loading: 'Caricamento…', diff --git a/src/client/locales-ja.ts b/src/client/locales-ja.ts index a967059a..01d0f54d 100644 --- a/src/client/locales-ja.ts +++ b/src/client/locales-ja.ts @@ -116,12 +116,24 @@ export const ja: Record = { mermaidZoomReset: 'リセット', mermaidZoomHint: 'スクロールで拡大 ・ ドラッグで移動 ・ Esc で閉じる', refresh: '更新', + find: '検索', + replace: '置換', + findNext: '次へ', + findPrevious: '前へ', + findAll: 'すべて選択', + findMatchCase: '大文字と小文字を区別', + findRegexp: '正規表現', + findByWord: '単語単位', + replaceOne: '置換', + replaceAll: 'すべて置換', showInFolder: 'フォルダーで表示', refreshUnsavedConfirm: 'ディスク上のファイルが変更されました。更新すると未保存の編集が失われます。続行しますか?', + closeUnsavedConfirm: 'このファイルには未保存の編集があります。タブを閉じると破棄されます。続行しますか?', save: '保存', saved: '保存済み', unsaved: '未保存', saveFailed: '保存に失敗', + saveConflict: 'ファイルはディスク上で他によって変更されています。保存を中止しました。編集内容はそのまま残っています。', saveConflictReload: 'ディスクの内容を再読み込み', truncation: 'ファイルが大きすぎます — 最初の 512KB のみ表示', binary: 'バイナリファイル、プレビュー不可', loading: '読み込み中…', diff --git a/src/client/locales-ko.ts b/src/client/locales-ko.ts index 4e8b4f11..d03355a9 100644 --- a/src/client/locales-ko.ts +++ b/src/client/locales-ko.ts @@ -108,12 +108,24 @@ export const ko: Record = { mermaidZoomReset: '초기화', mermaidZoomHint: '휠로 확대/축소 · 드래그로 이동 · Esc로 닫기', refresh: '새로고침', + find: '찾기', + replace: '바꾸기', + findNext: '다음', + findPrevious: '이전', + findAll: '모두 선택', + findMatchCase: '대소문자 구분', + findRegexp: '정규식', + findByWord: '단어 단위', + replaceOne: '바꾸기', + replaceAll: '모두 바꾸기', showInFolder: '폴더에서 표시', refreshUnsavedConfirm: '디스크의 파일이 변경되었습니다. 새로고침하면 저장되지 않은 편집 내용이 손실됩니다. 계속하시겠습니까?', + closeUnsavedConfirm: '이 파일에 저장되지 않은 편집이 있습니다. 탭을 닫으면 삭제됩니다. 계속하시겠습니까?', save: '저장', saved: '저장됨', unsaved: '저장 안 됨', saveFailed: '저장 실패', + saveConflict: '파일이 디스크에서 다른 곳에 의해 변경되었습니다. 저장이 중단되었고 편집 내용은 그대로 남아 있습니다.', saveConflictReload: '디스크에서 다시 불러오기', truncation: '파일이 너무 커 앞의 512KB만 표시합니다', binary: '이진 파일이라 미리보기를 할 수 없습니다', loading: '불러오는 중…', diff --git a/src/client/locales-nl.ts b/src/client/locales-nl.ts index 8106e224..4ea1152b 100644 --- a/src/client/locales-nl.ts +++ b/src/client/locales-nl.ts @@ -114,12 +114,24 @@ export const nl: Record = { mermaidZoomReset: 'Resetten', mermaidZoomHint: 'Scrollen om te zoomen · slepen om te pannen · Esc om te sluiten', refresh: 'Vernieuwen', + find: 'Zoeken', + replace: 'Vervangen', + findNext: 'Volgende', + findPrevious: 'Vorige', + findAll: 'Alles selecteren', + findMatchCase: 'Hoofdlettergevoelig', + findRegexp: 'Regex', + findByWord: 'Heel woord', + replaceOne: 'Vervangen', + replaceAll: 'Alles vervangen', showInFolder: 'In map tonen', refreshUnsavedConfirm: 'Het bestand is op schijf gewijzigd. Vernieuwen gooit niet-opgeslagen wijzigingen weg. Doorgaan?', + closeUnsavedConfirm: 'Dit bestand heeft niet-opgeslagen wijzigingen. Het sluiten van het tabblad gooit ze weg. Doorgaan?', save: 'Opslaan', saved: 'Opgeslagen', unsaved: 'Niet opgeslagen', saveFailed: 'Opslaan mislukt', + saveConflict: 'Het bestand is op schijf door iets anders gewijzigd. Opslaan afgebroken; je wijzigingen blijven in de editor.', saveConflictReload: 'Opnieuw laden vanaf schijf', truncation: 'Bestand te groot — alleen de eerste 512KB worden getoond', binary: 'Binair bestand, geen voorbeeld beschikbaar', loading: 'Laden…', diff --git a/src/client/locales-pl.ts b/src/client/locales-pl.ts index dd62423e..f7bb5d38 100644 --- a/src/client/locales-pl.ts +++ b/src/client/locales-pl.ts @@ -118,12 +118,24 @@ export const pl: Record = { mermaidZoomReset: 'Resetuj', mermaidZoomHint: 'Kółko: powiększenie · przeciąganie: panowanie · Esc: zamknięcie', refresh: 'Odśwież', + find: 'Szukaj', + replace: 'Zamień', + findNext: 'Następne', + findPrevious: 'Poprzednie', + findAll: 'Zaznacz wszystko', + findMatchCase: 'Uwzględnij wielkość liter', + findRegexp: 'Regex', + findByWord: 'Całe słowo', + replaceOne: 'Zamień', + replaceAll: 'Zamień wszystko', showInFolder: 'Pokaż w folderze', refreshUnsavedConfirm: 'Plik zmienił się na dysku. Odświeżenie odrzuci niezapisane zmiany. Kontynuować?', + closeUnsavedConfirm: 'Ten plik ma niezapisane zmiany. Zamknięcie karty je odrzuci. Kontynuować?', save: 'Zapisz', saved: 'Zapisano', unsaved: 'Niezapisane', saveFailed: 'Zapis nie powiódł się', + saveConflict: 'Plik został zmieniony na dysku przez inne źródło. Zapis przerwany; zmiany pozostają w edytorze.', saveConflictReload: 'Wczytaj ponownie z dysku', truncation: 'Plik zbyt duży — pokazuję pierwsze 512 KB', binary: 'Plik binarny, podgląd niedostępny', loading: 'Ładowanie…', diff --git a/src/client/locales-pt.ts b/src/client/locales-pt.ts index 08c0d25c..a323a23c 100644 --- a/src/client/locales-pt.ts +++ b/src/client/locales-pt.ts @@ -99,12 +99,24 @@ export const pt: Record = { mermaidZoomReset: 'Redefinir', mermaidZoomHint: 'Rolar para ampliar · arrastar para mover · Esc para fechar', refresh: 'Atualizar', + find: 'Localizar', + replace: 'Substituir', + findNext: 'Próximo', + findPrevious: 'Anterior', + findAll: 'Selecionar tudo', + findMatchCase: 'Diferenciar maiúsculas', + findRegexp: 'Regex', + findByWord: 'Palavra inteira', + replaceOne: 'Substituir', + replaceAll: 'Substituir tudo', showInFolder: 'Mostrar na pasta', refreshUnsavedConfirm: 'O arquivo mudou no disco. Atualizar descartará edições não salvas. Continuar?', + closeUnsavedConfirm: 'Este arquivo tem edições não salvas. Fechar a aba irá descartá-las. Continuar?', save: 'Salvar', saved: 'Salvo', unsaved: 'Não salvo', saveFailed: 'Falha ao salvar', + saveConflict: 'O arquivo foi alterado no disco por outra origem. Salvamento cancelado; suas edições permanecem no editor.', saveConflictReload: 'Recarregar do disco', truncation: 'Arquivo grande demais — exibindo os primeiros 512KB', binary: 'Arquivo binário, pré-visualização indisponível', loading: 'Carregando…', diff --git a/src/client/locales-ru.ts b/src/client/locales-ru.ts index 10711b8e..758f6a25 100644 --- a/src/client/locales-ru.ts +++ b/src/client/locales-ru.ts @@ -112,12 +112,24 @@ export const ru: Record = { mermaidZoomReset: 'Сбросить', mermaidZoomHint: 'Колесо — масштаб · перетаскивание — панорама · Esc — закрыть', refresh: 'Обновить', + find: 'Найти', + replace: 'Заменить', + findNext: 'Далее', + findPrevious: 'Назад', + findAll: 'Выделить всё', + findMatchCase: 'Учитывать регистр', + findRegexp: 'Регулярное выражение', + findByWord: 'Слово целиком', + replaceOne: 'Заменить', + replaceAll: 'Заменить всё', showInFolder: 'Показать в папке', refreshUnsavedConfirm: 'Файл изменился на диске. Обновление отбросит несохранённые изменения. Продолжить?', + closeUnsavedConfirm: 'В файле есть несохранённые изменения. Закрытие вкладки их отменит. Продолжить?', save: 'Сохранить', saved: 'Сохранено', unsaved: 'Не сохранено', saveFailed: 'Не удалось сохранить', + saveConflict: 'Файл был изменён на диске другим источником. Сохранение прервано; ваши правки остались в редакторе.', saveConflictReload: 'Перезагрузить с диска', truncation: 'Файл слишком велик — показаны первые 512 КБ', binary: 'Бинарный файл — предпросмотр недоступен', loading: 'Загрузка…', diff --git a/src/client/locales-sv.ts b/src/client/locales-sv.ts index 8c1262f1..9f211b4c 100644 --- a/src/client/locales-sv.ts +++ b/src/client/locales-sv.ts @@ -99,12 +99,24 @@ export const sv: Record = { mermaidZoomReset: 'Återställ', mermaidZoomHint: 'Rulla för att zooma · dra för att panorera · Esc för att stänga', refresh: 'Uppdatera', + find: 'Sök', + replace: 'Ersätt', + findNext: 'Nästa', + findPrevious: 'Föregående', + findAll: 'Markera alla', + findMatchCase: 'Matcha skiftläge', + findRegexp: 'Regex', + findByWord: 'Helord', + replaceOne: 'Ersätt', + replaceAll: 'Ersätt alla', showInFolder: 'Visa i mapp', refreshUnsavedConfirm: 'Filen ändrades på disken. Uppdatering kastar osparade ändringar. Fortsätta?', + closeUnsavedConfirm: 'Filen har osparade ändringar. Att stänga fliken kastar dem. Fortsätta?', save: 'Spara', saved: 'Sparad', unsaved: 'Osparad', saveFailed: 'Kunde inte spara', + saveConflict: 'Filen ändrades på disken av någon annan. Sparandet avbröts; dina ändringar finns kvar i redigeraren.', saveConflictReload: 'Ladda om från disken', truncation: 'Filen är för stor — visar de första 512KB', binary: 'Binärfil, förhandsgranskning otillgänglig', loading: 'Laddar…', diff --git a/src/client/locales-th.ts b/src/client/locales-th.ts index fcdfa5d6..49c07e1b 100644 --- a/src/client/locales-th.ts +++ b/src/client/locales-th.ts @@ -116,12 +116,24 @@ export const th: Record = { mermaidZoomReset: 'รีเซ็ต', mermaidZoomHint: 'เลื่อนเพื่อซูม · ลากเพื่อแพน · Esc เพื่อปิด', refresh: 'รีเฟรช', + find: 'ค้นหา', + replace: 'แทนที่', + findNext: 'ถัดไป', + findPrevious: 'ก่อนหน้า', + findAll: 'เลือกทั้งหมด', + findMatchCase: 'ตรงตามตัวพิมพ์', + findRegexp: 'Regex', + findByWord: 'ทั้งคำ', + replaceOne: 'แทนที่', + replaceAll: 'แทนที่ทั้งหมด', showInFolder: 'แสดงในโฟลเดอร์', refreshUnsavedConfirm: 'ไฟล์เปลี่ยนบนดิสก์ การรีเฟรชจะทิ้งการแก้ไขที่ยังไม่ได้บันทึก ดำเนินการต่อหรือไม่', + closeUnsavedConfirm: 'ไฟล์นี้มีการแก้ไขที่ยังไม่ได้บันทึก การปิดแท็บจะทิ้งการแก้ไขนั้น ดำเนินการต่อหรือไม่', save: 'บันทึก', saved: 'บันทึกแล้ว', unsaved: 'ยังไม่ได้บันทึก', saveFailed: 'บันทึกล้มเหลว', + saveConflict: 'ไฟล์ถูกแก้ไขบนดิสก์จากแหล่งอื่น การบันทึกถูกยกเลิก การแก้ไขของคุณยังอยู่ในเอดิเตอร์', saveConflictReload: 'โหลดใหม่จากดิสก์', truncation: 'ไฟล์ใหญ่เกินไป — แสดงเพียง 512KB แรก', binary: 'ไฟล์ไบนารี ไม่สามารถพรีวิวได้', loading: 'กำลังโหลด…', diff --git a/src/client/locales-tr.ts b/src/client/locales-tr.ts index f7d015ed..51fc021c 100644 --- a/src/client/locales-tr.ts +++ b/src/client/locales-tr.ts @@ -116,12 +116,24 @@ export const tr: Record = { mermaidZoomReset: 'Sıfırla', mermaidZoomHint: 'Yakınlaştırmak için kaydır · taşımak için sürükle · kapatmak için Esc', refresh: 'Yenile', + find: 'Bul', + replace: 'Değiştir', + findNext: 'Sonraki', + findPrevious: 'Önceki', + findAll: 'Tümünü seç', + findMatchCase: 'Büyük/küçük harf', + findRegexp: 'Regex', + findByWord: 'Tam sözcük', + replaceOne: 'Değiştir', + replaceAll: 'Tümünü değiştir', showInFolder: 'Klasörde göster', refreshUnsavedConfirm: 'Dosya diskte değişti. Yenileme kaydedilmemiş düzenlemeleri atar. Devam edilsin mi?', + closeUnsavedConfirm: 'Bu dosyada kaydedilmemiş değişiklikler var. Sekmeyi kapatmak bunları atacak. Devam edilsin mi?', save: 'Kaydet', saved: 'Kaydedildi', unsaved: 'Kaydedilmedi', saveFailed: 'Kaydetme başarısız', + saveConflict: 'Dosya diskte başka bir kaynak tarafından değiştirildi. Kaydetme durduruldu; düzenlemeleriniz düzenleyicide kaldı.', saveConflictReload: 'Diskten yeniden yükle', truncation: 'Dosya çok büyük — ilk 512KB gösteriliyor', binary: 'İkili dosya, önizleme kullanılamıyor', loading: 'Yükleniyor…', diff --git a/src/client/locales-vi.ts b/src/client/locales-vi.ts index 11044a89..5b9a52b1 100644 --- a/src/client/locales-vi.ts +++ b/src/client/locales-vi.ts @@ -116,12 +116,24 @@ export const vi: Record = { mermaidZoomReset: 'Đặt lại', mermaidZoomHint: 'Cuộn để zoom · kéo để di chuyển · Esc để đóng', refresh: 'Làm mới', + find: 'Tìm', + replace: 'Thay thế', + findNext: 'Tiếp', + findPrevious: 'Trước', + findAll: 'Chọn tất cả', + findMatchCase: 'Phân biệt chữ hoa thường', + findRegexp: 'Regex', + findByWord: 'Toàn bộ từ', + replaceOne: 'Thay thế', + replaceAll: 'Thay thế tất cả', showInFolder: 'Hiển thị trong thư mục', refreshUnsavedConfirm: 'Tệp đã thay đổi trên đĩa. Làm mới sẽ loại bỏ các chỉnh sửa chưa lưu. Tiếp tục?', + closeUnsavedConfirm: 'Tệp này có chỉnh sửa chưa lưu. Đóng tab sẽ loại bỏ chúng. Tiếp tục?', save: 'Lưu', saved: 'Đã lưu', unsaved: 'Chưa lưu', saveFailed: 'Lưu thất bại', + saveConflict: 'Tệp đã bị nguồn khác sửa trên đĩa. Đã hủy lưu; chỉnh sửa của bạn vẫn còn trong trình soạn thảo.', saveConflictReload: 'Tải lại từ đĩa', truncation: 'Tệp quá lớn, chỉ hiển thị 512KB đầu', binary: 'Tệp nhị phân, không xem trước được', loading: 'Đang tải…', diff --git a/src/client/locales-zh-HK.ts b/src/client/locales-zh-HK.ts index b898c5a0..8a1f432a 100644 --- a/src/client/locales-zh-HK.ts +++ b/src/client/locales-zh-HK.ts @@ -131,12 +131,24 @@ export const zhHK: Record = { mermaidZoomReset: '重設', mermaidZoomHint: '滾輪縮放 · 拖曳平移 · Esc 關閉', refresh: '重新整理', + find: '尋找', + replace: '取代', + findNext: '下一個', + findPrevious: '上一個', + findAll: '全選相符', + findMatchCase: '區分大小寫', + findRegexp: '正規表示式', + findByWord: '全字', + replaceOne: '取代', + replaceAll: '全部取代', showInFolder: '在文件夾中顯示', refreshUnsavedConfirm: '檔案已在磁碟上變更。重新整理會丟失尚未儲存的編輯。繼續?', + closeUnsavedConfirm: '此檔案有未儲存的編輯,關閉後將被丟棄。繼續嗎?', save: '儲存', saved: '已儲存', unsaved: '未儲存', saveFailed: '儲存失敗', + saveConflict: '檔案已在磁碟上被其他來源修改。儲存已中止,你的編輯仍在編輯器中。', saveConflictReload: '重新載入磁碟內容', truncation: '檔案過大,僅顯示前 512KB', binary: '二進位檔案,無法預覽', loading: '載入中…', diff --git a/src/client/locales-zh-MO.ts b/src/client/locales-zh-MO.ts index 52d3e8db..4ecef9ef 100644 --- a/src/client/locales-zh-MO.ts +++ b/src/client/locales-zh-MO.ts @@ -131,12 +131,24 @@ export const zhMO: Record = { mermaidZoomReset: '重設', mermaidZoomHint: '滾輪縮放 · 拖曳平移 · Esc 關閉', refresh: '重新整理', + find: '尋找', + replace: '取代', + findNext: '下一個', + findPrevious: '上一個', + findAll: '全選相符', + findMatchCase: '區分大小寫', + findRegexp: '正規表示式', + findByWord: '全字', + replaceOne: '取代', + replaceAll: '全部取代', showInFolder: '在文件夾中顯示', refreshUnsavedConfirm: '檔案已在磁碟上變更。重新整理會丟失尚未儲存的編輯。繼續?', + closeUnsavedConfirm: '此檔案有未儲存的編輯,關閉後將被丟棄。繼續嗎?', save: '儲存', saved: '已儲存', unsaved: '未儲存', saveFailed: '儲存失敗', + saveConflict: '檔案已在磁碟上被其他來源修改。儲存已中止,你的編輯仍在編輯器中。', saveConflictReload: '重新載入磁碟內容', truncation: '檔案過大,僅顯示前 512KB', binary: '二進位檔案,無法預覽', loading: '載入中…', diff --git a/src/client/locales-zh-TW.ts b/src/client/locales-zh-TW.ts index 06015808..1bad538c 100644 --- a/src/client/locales-zh-TW.ts +++ b/src/client/locales-zh-TW.ts @@ -131,12 +131,24 @@ export const zhTW: Record = { mermaidZoomReset: '重設', mermaidZoomHint: '滾輪縮放 · 拖曳平移 · Esc 關閉', refresh: '重新整理', + find: '尋找', + replace: '取代', + findNext: '下一個', + findPrevious: '上一個', + findAll: '全選相符', + findMatchCase: '區分大小寫', + findRegexp: '正規表示式', + findByWord: '全字', + replaceOne: '取代', + replaceAll: '全部取代', showInFolder: '在資料夾中顯示', refreshUnsavedConfirm: '檔案已在磁碟上變更。重新整理會丟失尚未儲存的編輯。繼續?', + closeUnsavedConfirm: '此檔案有未儲存的編輯,關閉後將被丟棄。繼續嗎?', save: '儲存', saved: '已儲存', unsaved: '未儲存', saveFailed: '儲存失敗', + saveConflict: '檔案已在磁碟上被其他來源修改。儲存已中止,你的編輯仍在編輯器中。', saveConflictReload: '重新載入磁碟內容', truncation: '檔案過大,僅顯示前 512KB', binary: '二進位檔案,無法預覽', loading: '載入中…', diff --git a/src/client/locales.ts b/src/client/locales.ts index 2c0083e5..501c5b62 100644 --- a/src/client/locales.ts +++ b/src/client/locales.ts @@ -128,11 +128,23 @@ export const zh = { mermaidZoomReset: '重置', mermaidZoomHint: '滚轮缩放 · 拖拽平移 · Esc 关闭', refresh: '刷新', + find: '查找', + replace: '替换', + findNext: '下一个', + findPrevious: '上一个', + findAll: '全选匹配', + findMatchCase: '区分大小写', + findRegexp: '正则', + findByWord: '全词', + replaceOne: '替换', + replaceAll: '全部替换', refreshUnsavedConfirm: '文件已在磁盘更新,刷新将丢弃未保存编辑。继续吗?', + closeUnsavedConfirm: '该文件有未保存的编辑,关闭后将丢弃。继续吗?', save: '保存', saved: '已保存', unsaved: '未保存', saveFailed: '保存失败', + saveConflict: '文件已在磁盘上被其他来源修改。保存已中止,你的修改仍在编辑器中。', saveConflictReload: '重新载入磁盘内容', truncation: '文件过大,仅显示前 512KB', binary: '二进制文件,无法预览', loading: '加载中…', @@ -578,11 +590,24 @@ export const en: Record = { mermaidZoomReset: 'Reset', mermaidZoomHint: 'Scroll to zoom · drag to pan · Esc to close', refresh: 'Refresh', + find: 'Find', + replace: 'Replace', + findNext: 'Next', + findPrevious: 'Previous', + findAll: 'Select all', + findMatchCase: 'Match case', + findRegexp: 'Regexp', + findByWord: 'Whole word', + replaceOne: 'Replace', + replaceAll: 'Replace all', refreshUnsavedConfirm: 'The file changed on disk. Refreshing will discard unsaved edits. Continue?', + closeUnsavedConfirm: 'This file has unsaved edits. Closing the tab will discard them. Continue?', save: 'Save', saved: 'Saved', unsaved: 'Unsaved', saveFailed: 'Save failed', + saveConflict: 'The file changed on disk since it was loaded. The save was stopped; your edits are still in the editor.', + saveConflictReload: 'Reload from disk', truncation: 'File too large — showing the first 512KB', binary: 'Binary file, preview unavailable', loading: 'Loading…', diff --git a/src/client/service.ts b/src/client/service.ts index 8897e7dd..521b5e47 100644 --- a/src/client/service.ts +++ b/src/client/service.ts @@ -262,6 +262,10 @@ export interface FileViewerProps { /** fsRead text content (fetchStrategy='fsRead'). */ content?: string truncated?: boolean + /** Last-modified time (ms) of the loaded bytes — the built-in text editor's + * save baseline (a file that changed on disk since refuses the write). + * Absent for viewers/loads that carry no baseline. */ + mtimeMs?: number /** mediaUrl for the path (fetchStrategy='mediaUrl'). */ mediaUrl?: string /** custom load() return value (fetchStrategy='custom'). */ @@ -276,6 +280,8 @@ export interface FileViewerProps { /** Internal: the viewer registers its toolbar commands on mount (null on * unmount). */ onToolbarControls?: (controls: EditorToolbarControls | null) => void + /** Internal: reload the file from disk (the save-conflict banner's action). */ + onReload?: () => void } /** The toolbar state a text editor reports to the host's merged-mode header. */ diff --git a/src/client/sidebar.module.css b/src/client/sidebar.module.css index 3694a6b5..fbac9c41 100644 --- a/src/client/sidebar.module.css +++ b/src/client/sidebar.module.css @@ -1633,6 +1633,18 @@ body[data-dsh-sidebar-dragging] .bottomPanel { background: var(--dsw-alias-state-warn-tertiary); } +/* Inline action of a banner (the save-conflict "reload" link). */ +.editorBannerAction { + margin-left: 8px; + padding: 0; + border: 0; + background: none; + font: inherit; + color: inherit; + text-decoration: underline; + cursor: pointer; +} + /* Live sandbox status row (HTML preview / browser tab): GREEN while the sandbox is on (with the one-tap temporary unlock), RED while it is off (global setting or temporary unlock) — the red state is the persistent diff --git a/src/client/tree-mutations.ts b/src/client/tree-mutations.ts index 8b1719cb..b6f9dc7d 100644 --- a/src/client/tree-mutations.ts +++ b/src/client/tree-mutations.ts @@ -13,6 +13,7 @@ */ import type { Context } from '../context-types.ts' import { baseName } from './FileTree.tsx' +import { confirmDiscardDraft } from './editor-dirty.ts' import { allLeaves, type SidebarSnapshot, type SidebarStore, type SidebarTab } from './state.ts' import { isWithinWorkspace } from './paths.ts' @@ -39,12 +40,16 @@ export function retargetPathTabs(ctx: Context, store: SidebarStore, oldPath: str } /** Close tabs at or under the removed `target` (a directory takes its whole - * subtree of open files with it). */ -export function closePathTabs(ctx: Context, store: SidebarStore, target: string): void { + * subtree of open files with it). A tab holding an unsaved draft asks first + * (the same guard + copy as the sidebar's tab close); declining keeps the + * tab — its next save recreates the file, which is the user's call. */ +export function closePathTabs(ctx: Context, store: SidebarStore, target: string, unsavedMessage: string): void { const service = ctx.get('betterSidebar') if (service === undefined) return for (const tab of pathTabsOf(store.getSnapshot())) { const path = tab.path - if (path !== undefined && (path === target || isWithinWorkspace(target, path))) service.closeTab(tab.id) + if (path === undefined || (path !== target && !isWithinWorkspace(target, path))) continue + if (!confirmDiscardDraft(tab.id, unsavedMessage)) continue + service.closeTab(tab.id) } } diff --git a/src/index.ts b/src/index.ts index 4638174e..c88fbe47 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,6 +14,7 @@ * processes are keyed by session. */ import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises' +import { randomUUID } from 'node:crypto' import { basename, dirname, extname, isAbsolute, join } from 'node:path' import type { IncomingMessage } from 'node:http' import type { Duplex } from 'node:stream' @@ -179,6 +180,8 @@ async function readText(path: string, readLimit: number): Promise<{ truncated: boolean binary: boolean size: number + /** Last-modified time (ms) — the save route's conflict baseline. */ + mtimeMs: number head?: string }> { const info = await stat(path).catch((error: unknown) => { @@ -205,6 +208,7 @@ async function readText(path: string, readLimit: number): Promise<{ truncated, binary, size, + mtimeMs: info.mtimeMs, head, } } finally { @@ -350,15 +354,36 @@ function buildApi( // cwd; thread it so the path resolves inside the authorized workspace. const selected = selectedRepoOf(payload) const path = await ensureWorkspacePath(cwd, await resolveGitPath(cwd, requireString(payload, 'path'), selected), fenceEnabledOf(getSettings)) - const { content, truncated, binary, size, head } = await readText(path, resolved.readLimit) - if (binary) return { kind: 'binary', size, truncated, head } - return { kind: 'text', content, truncated } + const { content, truncated, binary, size, mtimeMs, head } = await readText(path, resolved.readLimit) + if (binary) return { kind: 'binary', size, truncated, mtimeMs, head } + return { kind: 'text', content, truncated, mtimeMs } }, 'fs.write': async (payload) => { const { cwd } = await cwdOf(payload) const path = await ensureWorkspaceWritePath(cwd, requireString(payload, 'path'), fenceEnabledOf(getSettings)) const content = requireString(payload, 'content') - const tmp = `${path}.dsh-sidebar-tmp-${process.pid}` + // 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 + // silently clobbering those bytes. Omitted (older callers) = no gate. + const record = payload as { expectedMtimeMs?: unknown } | null + const expected = typeof record?.expectedMtimeMs === 'number' && Number.isFinite(record.expectedMtimeMs) + ? record.expectedMtimeMs + : 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, + ) + } + } + // Unique temp sibling (randomUUID, the upload route's pattern): two + // concurrent saves to the same path write their own temp file, so one + // cannot rm() the other's before its rename (EEXIST cross-talk). + const tmp = join(dirname(path), `.${basename(path)}.dsh-write-${randomUUID()}.tmp`) try { await mkdir(dirname(path), { recursive: true }) await writeFile(tmp, content, 'utf8') @@ -367,7 +392,9 @@ function buildApi( await rm(tmp, { force: true }).catch(() => {}) throw new SidebarError('fs-error', `cannot write "${path}": ${error instanceof Error ? error.message : String(error)}`, 400) } - return { ok: true } + // The fresh baseline the client adopts after a successful save. + const mtimeMs = await stat(path).then(info => info.mtimeMs).catch(() => undefined) + return { ok: true, ...(mtimeMs !== undefined ? { mtimeMs } : {}) } }, // The tree row's rename: single-segment name, destination-existence and // workspace-root refusals, link-aware (renames the row, not its target). diff --git a/src/wire.ts b/src/wire.ts index 30025432..015c6b11 100644 --- a/src/wire.ts +++ b/src/wire.ts @@ -14,6 +14,7 @@ export type SidebarErrorCode = | 'method-error' | 'too-large' | 'fs-error' + | 'fs-conflict' | 'git-error' | 'pty-error' | 'pty-deps-missing' diff --git a/tests/editor-unsaved-guard.spec.tsx b/tests/editor-unsaved-guard.spec.tsx new file mode 100644 index 00000000..cc64aeec --- /dev/null +++ b/tests/editor-unsaved-guard.spec.tsx @@ -0,0 +1,290 @@ +/** + * Unsaved-draft protection: the dirty registry itself plus the close guard it + * arms. The registry is fed by the editor host's toolbar report; the guard is + * the sidebar's tab close (the X button, middle click, tab context menu, and + * the tree's close-on-rename/delete all funnel through the same action). + * + * The close path is driven through the REAL Sidebar shell (same minimal fake + * context as sidebar-crash.spec.tsx) so the test pins the behavior a user + * actually gets, not a helper: cancel keeps the tab, confirm closes it. + */ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createElement, useEffect } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { act } from 'react-dom/test-utils' +import { renderRoot, setupReactAct } from './test-utils.ts' +import type { Context } from '../src/context-types.ts' +import { EditorHost } from '../src/client/EditorHost.tsx' +import { Sidebar } from '../src/client/Sidebar.tsx' +import { createBetterSidebarService, type BetterSidebarService, type FileViewerProps } from '../src/client/service.ts' +import { allLeaves, createSidebarStore, type SidebarStore } from '../src/client/state.ts' +import { + clearEditorDirty, confirmDiscardDraft, dirtyCount, dirtyCountForSession, editorDirtyRevision, + isEditorDirty, setEditorDirty, subscribeEditorDirty, +} from '../src/client/editor-dirty.ts' +import { closePathTabs } from '../src/client/tree-mutations.ts' + +setupReactAct() + +const fsRead = vi.fn() +vi.mock('../src/client/api.ts', () => ({ + // fsTree: the sidebar shell renders the docked tree panel too; a missing + // method would trip the tab's render boundary and hide the failure. + api: { + fsRead: (...args: unknown[]) => fsRead(...args), + fsTree: () => Promise.resolve({ path: '', entries: [], truncated: false }), + }, + mediaUrl: () => '', +})) + +/** jsdom has no WebSocket; the sidebar's agent-terminals effect builds one. */ +class FakeWebSocket { + onmessage: ((event: { data: unknown }) => void) | null = null + onclose: (() => void) | null = null + onerror: (() => void) | null = null + close = (): void => {} + constructor(_url: string) {} +} + +/** A viewer that reports a dirty toolbar and renders nothing else. */ +function DirtyViewer({ onToolbarState }: FileViewerProps) { + useEffect(() => { + onToolbarState?.({ modes: false, mode: 'edit', dirty: true, editable: true, saveState: 'idle' }) + }, [onToolbarState]) + return createElement('div', null, 'dirty-viewer') +} + +let sessionSeq = 0 + +interface Mounted { + container: HTMLDivElement + store: SidebarStore + service: BetterSidebarService + sessionId: string + unmount: () => void +} + +/** Mount the real Sidebar shell with one open editor tab (dirty viewer). */ +function mountSidebarWithEditor(): Mounted { + vi.stubGlobal('WebSocket', FakeWebSocket) + const container = document.createElement('div') + document.body.append(container) + const store = createSidebarStore() + const service = createBetterSidebarService(store) + service.registerTab({ + id: 'editor', + title: () => 'Files', + dedupeKey: (tab) => tab.path, + component: ({ ctx, store: tabStore, scope, tab, expanded, revealed, onToggleDir, onReferenceFile }) => + createElement(EditorHost, { + ctx, store: tabStore, scope, tab, + expanded: expanded ?? [], revealed: revealed ?? [], + onToggleDir: onToggleDir ?? (() => {}), onReferenceFile: onReferenceFile ?? (() => {}), + }), + }) + service.registerFileViewer({ + id: 'mock-text', exts: ['ts'], priority: 0, fetchStrategy: 'fsRead', component: DirtyViewer, + }) + store.setPrefs({ ...store.getPrefs(), openByDefault: true }) + const sessionId = `dirty-${++sessionSeq}` + store.setSession(sessionId) + const localeSnapshot = { active: 'en' } + const sessionsSnapshot = { current: sessionId, byId: { [sessionId]: { cwd: '/tmp' } } } + const ctx = { + locale: { subscribe: () => () => {}, getSnapshot: () => localeSnapshot }, + sessions: { list: { subscribe: () => () => {}, getSnapshot: () => sessionsSnapshot } }, + betterSidebar: service, + get: (name: string) => name === 'betterSidebar' ? service : undefined, + } as unknown as Context + service.openTab({ type: 'editor', title: 'a.ts', path: '/tmp/a.ts', id: 'editor:/tmp/a.ts' }) + const root: Root = createRoot(container) + act(() => { root.render(createElement(Sidebar, { ctx, store })) }) + return { + container, store, service, sessionId, + unmount: () => { + act(() => { root.unmount() }) + container.remove() + }, + } +} + +/** The a.ts tab's close button (the seeded Files home tab also has one). */ +function closeButton(container: HTMLDivElement): HTMLButtonElement { + const tabNode = Array.from(container.querySelectorAll('[title="a.ts"]')) + .find(node => node.querySelector('button') !== null) + const button = tabNode?.querySelector('button[aria-label="Close"], button[aria-label="关闭"]') + if (button === undefined || button === null) throw new Error('close button not found') + return button as HTMLButtonElement +} + +function click(button: HTMLElement): void { + act(() => { button.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) +} + +function openTabIds(store: SidebarStore): string[] { + const state = store.getSnapshot().state + if (state === undefined) return [] + return allLeaves(state.splits).concat(allLeaves(state.bottomSplits)).flatMap(leaf => leaf.tabs).map(tab => tab.id) +} + +beforeEach(() => { + fsRead.mockReset() + fsRead.mockResolvedValue({ kind: 'text', content: 'hello', truncated: false }) + // The registry is module-level: a previous test's draft must not leak in. + for (const id of ['editor:/tmp/a.ts', 't1', 't2']) clearEditorDirty(id) +}) + +afterEach(() => { + document.body.innerHTML = '' + localStorage.clear() + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +describe('editor-dirty registry', () => { + it('registers a dirty tab and clears it again, bumping the revision each time', () => { + const before = editorDirtyRevision() + setEditorDirty('t1', true, 's1', '/tmp/a.ts') + expect(isEditorDirty('t1')).toBe(true) + expect(dirtyCount()).toBe(1) + expect(dirtyCountForSession('s1')).toBe(1) + expect(dirtyCountForSession('other')).toBe(0) + expect(editorDirtyRevision()).toBeGreaterThan(before) + + const afterRegister = editorDirtyRevision() + setEditorDirty('t1', true, 's1', '/tmp/a.ts') + // Same entry twice is a no-op: no revision churn (the unload effect would + // otherwise re-subscribe on every render). + expect(editorDirtyRevision()).toBe(afterRegister) + + clearEditorDirty('t1') + expect(isEditorDirty('t1')).toBe(false) + expect(dirtyCount()).toBe(0) + expect(editorDirtyRevision()).toBeGreaterThan(afterRegister) + }) + + it('re-points an entry when the tab switches file or session', () => { + setEditorDirty('t2', true, 's1', '/tmp/a.ts') + setEditorDirty('t2', true, 's2', '/tmp/b.ts') + expect(dirtyCountForSession('s1')).toBe(0) + expect(dirtyCountForSession('s2')).toBe(1) + }) + + it('notifies subscribers and stops after unsubscribe', () => { + const listener = vi.fn() + const unsubscribe = subscribeEditorDirty(listener) + setEditorDirty('t1', true, 's1', '/tmp/a.ts') + expect(listener).toHaveBeenCalledTimes(1) + clearEditorDirty('t1') + expect(listener).toHaveBeenCalledTimes(2) + unsubscribe() + setEditorDirty('t1', true, 's1', '/tmp/a.ts') + expect(listener).toHaveBeenCalledTimes(2) + }) + + it('confirmDiscardDraft passes clean tabs through and prompts for dirty ones', () => { + const confirmSpy = vi.fn().mockReturnValue(false) + vi.stubGlobal('confirm', confirmSpy) + expect(confirmDiscardDraft('t1', 'sure?')).toBe(true) + expect(confirmSpy).not.toHaveBeenCalled() + + setEditorDirty('t1', true, 's1', '/tmp/a.ts') + expect(confirmDiscardDraft('t1', 'sure?')).toBe(false) + expect(confirmSpy).toHaveBeenCalledWith('sure?') + // Declined: the draft survives. + expect(isEditorDirty('t1')).toBe(true) + + confirmSpy.mockReturnValue(true) + expect(confirmDiscardDraft('t1', 'sure?')).toBe(true) + // Confirmed: the entry is cleared so a follow-up close cannot re-prompt. + expect(isEditorDirty('t1')).toBe(false) + }) +}) + +describe('tree close-on-delete', () => { + it('keeps a dirty tab when the user declines, closes it on confirm', () => { + const confirmSpy = vi.fn().mockReturnValue(false) + vi.stubGlobal('confirm', confirmSpy) + const store = createSidebarStore() + const service = createBetterSidebarService(store) + service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null }) + store.setSession('tree-close') + const ctx = { betterSidebar: service, get: (name: string) => name === 'betterSidebar' ? service : undefined } as unknown as Context + service.openTab({ type: 'editor', title: 'a.ts', path: '/tmp/a.ts', id: 'editor:/tmp/a.ts' }) + setEditorDirty('editor:/tmp/a.ts', true, 'tree-close', '/tmp/a.ts') + + closePathTabs(ctx, store, '/tmp/a.ts', 'discard?') + expect(confirmSpy).toHaveBeenCalledWith('discard?') + expect(openTabIds(store)).toContain('editor:/tmp/a.ts') + + confirmSpy.mockReturnValue(true) + closePathTabs(ctx, store, '/tmp/a.ts', 'discard?') + expect(openTabIds(store)).not.toContain('editor:/tmp/a.ts') + }) +}) + +describe('EditorHost dirty registration', () => { + it('registers the open tab and clears it when the host unmounts', async () => { + const store = createSidebarStore() + const service = createBetterSidebarService(store) + service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null }) + service.registerFileViewer({ id: 'mock-text', exts: ['ts'], fetchStrategy: 'fsRead', component: DirtyViewer }) + store.setSession('editor-host-dirty') + const ctx = { betterSidebar: service, get: (name: string) => name === 'betterSidebar' ? service : undefined } as unknown as Context + service.openTab({ type: 'editor', title: 'a.ts', path: '/tmp/a.ts', id: 'editor:/tmp/a.ts' }) + const tab = allLeaves(store.getSnapshot().state!.splits).flatMap(leaf => leaf.tabs) + .find(candidate => candidate.path === '/tmp/a.ts')! + const mounted = renderRoot(createElement(EditorHost, { + ctx, store, scope: { sessionId: 'editor-host-dirty' }, tab, + expanded: [], revealed: [], onToggleDir: () => {}, onReferenceFile: () => {}, + })) + await act(async () => { await Promise.resolve() }) + expect(isEditorDirty(tab.id)).toBe(true) + mounted.unmount() + expect(isEditorDirty(tab.id)).toBe(false) + }) +}) + +describe('close guard', () => { + it('cancel keeps the tab open and confirm closes it', async () => { + const confirmSpy = vi.fn() + vi.stubGlobal('confirm', confirmSpy) + const mounted = mountSidebarWithEditor() + try { + await act(async () => { await Promise.resolve() }) + expect(openTabIds(mounted.store)).toContain('editor:/tmp/a.ts') + expect(isEditorDirty('editor:/tmp/a.ts')).toBe(true) + + // Cancel: the tab survives and stays dirty. + confirmSpy.mockReturnValue(false) + click(closeButton(mounted.container)) + expect(confirmSpy).toHaveBeenCalledTimes(1) + expect(openTabIds(mounted.store)).toContain('editor:/tmp/a.ts') + expect(isEditorDirty('editor:/tmp/a.ts')).toBe(true) + + // Confirm: the tab closes. + confirmSpy.mockReturnValue(true) + click(closeButton(mounted.container)) + expect(confirmSpy).toHaveBeenCalledTimes(2) + expect(openTabIds(mounted.store)).not.toContain('editor:/tmp/a.ts') + } finally { + mounted.unmount() + } + }) + + it('a clean tab closes without prompting', async () => { + const confirmSpy = vi.fn().mockReturnValue(false) + vi.stubGlobal('confirm', confirmSpy) + const mounted = mountSidebarWithEditor() + try { + await act(async () => { await Promise.resolve() }) + clearEditorDirty('editor:/tmp/a.ts') + click(closeButton(mounted.container)) + expect(confirmSpy).not.toHaveBeenCalled() + expect(openTabIds(mounted.store)).not.toContain('editor:/tmp/a.ts') + } finally { + mounted.unmount() + } + }) +}) diff --git a/tests/fs-write-route.spec.ts b/tests/fs-write-route.spec.ts new file mode 100644 index 00000000..6a399a56 --- /dev/null +++ b/tests/fs-write-route.spec.ts @@ -0,0 +1,199 @@ +/** + * 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-` name made the second rename fail with ENOENT). + * 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 + 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: () => () => {}, + 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 { + 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. */ +function tempLeftovers(dir: string): string[] { + return readdirSync(dir).filter(name => name.includes('.dsh-write-')) +} + +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 }) + } + }) +}) diff --git a/tests/text-editor-conflict.spec.tsx b/tests/text-editor-conflict.spec.tsx new file mode 100644 index 00000000..4f6e558a --- /dev/null +++ b/tests/text-editor-conflict.spec.tsx @@ -0,0 +1,124 @@ +/** + * The text editor's save-conflict surface: a save whose baseline mtime no + * longer matches the file on disk is refused by the host (`fs-conflict`) and + * the editor must (a) keep the draft, (b) explain why, (c) offer the host's + * reload. Rendered with the REAL CodeMirror viewer (the dirty draft only + * exists there), against a mocked api module. + */ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createElement } from 'react' +import { act } from 'react-dom/test-utils' +import { renderRoot, setupReactAct } from './test-utils.ts' +import { SidebarApiError } from '../src/client/api.ts' +import { TextEditor } from '../src/client/TextEditor.tsx' +import { createSidebarStore } from '../src/client/state.ts' +import type { FileViewerProps } from '../src/client/service.ts' + +setupReactAct() + +const fsWrite = vi.fn() +vi.mock('../src/client/api.ts', async (importOriginal) => { + // The real error class: TextEditor narrows the failure with instanceof. + const actual = await importOriginal() + return { + ...actual, + api: { fsWrite: (...args: unknown[]) => fsWrite(...args) }, + } +}) + +function viewerProps(overrides: Partial = {}): FileViewerProps { + return { + ctx: {} as FileViewerProps['ctx'], + store: createSidebarStore(), + scope: { sessionId: 's1', cwd: '/p' }, + path: '/p/a.ts', + title: 'a.ts', + viewerId: 'code', + content: 'const a = 1\n', + mtimeMs: 123, + ...overrides, + } +} + +/** The save button of the viewer's own toolbar (no host hoisting here). */ +function saveButton(container: HTMLDivElement): HTMLButtonElement { + const button = container.querySelector('button[aria-label="Save"], button[aria-label="保存"]') + if (button === null) throw new Error('save button not found') + return button as HTMLButtonElement +} + +function click(element: HTMLElement): void { + act(() => { element.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) +} + +beforeEach(() => { + fsWrite.mockReset() +}) + +afterEach(() => { + document.body.innerHTML = '' +}) + +describe('TextEditor save conflict', () => { + it('sends the loaded mtime as the baseline', async () => { + fsWrite.mockResolvedValue({ ok: true, mtimeMs: 456 }) + const mounted = renderRoot(createElement(TextEditor, viewerProps())) + try { + click(saveButton(mounted.container)) + await act(async () => { await Promise.resolve() }) + expect(fsWrite).toHaveBeenCalledTimes(1) + // scope, path, content, expectedMtimeMs + expect(fsWrite.mock.calls[0]![3]).toBe(123) + } finally { + mounted.unmount() + } + }) + + it('keeps the draft and offers a reload when the host refuses with fs-conflict', async () => { + fsWrite.mockRejectedValue(new SidebarApiError('fs-conflict', 'changed on disk')) + const onReload = vi.fn() + const mounted = renderRoot(createElement(TextEditor, viewerProps({ onReload }))) + try { + click(saveButton(mounted.container)) + await act(async () => { await Promise.resolve() }) + const text = mounted.container.textContent ?? '' + expect(text).toContain('changed on disk since it was loaded') + const reload = Array.from(mounted.container.querySelectorAll('button')) + .find(button => button.textContent === 'Reload from disk') + expect(reload).toBeDefined() + click(reload!) + expect(onReload).toHaveBeenCalledTimes(1) + } finally { + mounted.unmount() + } + }) + + it('does not show the conflict banner for an ordinary save failure', async () => { + fsWrite.mockRejectedValue(new SidebarApiError('fs-error', 'disk full')) + const mounted = renderRoot(createElement(TextEditor, viewerProps())) + try { + click(saveButton(mounted.container)) + await act(async () => { await Promise.resolve() }) + expect(mounted.container.textContent ?? '').not.toContain('changed on disk') + } finally { + mounted.unmount() + } + }) + + it('adopts the baseline the host reports after a successful save', async () => { + fsWrite.mockResolvedValue({ ok: true, mtimeMs: 456 }) + const mounted = renderRoot(createElement(TextEditor, viewerProps())) + try { + click(saveButton(mounted.container)) + await act(async () => { await Promise.resolve() }) + click(saveButton(mounted.container)) + await act(async () => { await Promise.resolve() }) + expect(fsWrite).toHaveBeenCalledTimes(2) + expect(fsWrite.mock.calls[0]![3]).toBe(123) + expect(fsWrite.mock.calls[1]![3]).toBe(456) + } finally { + mounted.unmount() + } + }) +}) diff --git a/tests/text-editor-search.spec.tsx b/tests/text-editor-search.spec.tsx new file mode 100644 index 00000000..a7484733 --- /dev/null +++ b/tests/text-editor-search.spec.tsx @@ -0,0 +1,143 @@ +/** + * The built-in text editor's find/replace surface (CodeMirror's search + * extension): the toolbar button opens the panel, the panel's labels follow + * the sidebar's own dictionary (CodeMirror ships English-only strings), and + * the panel is reachable in BOTH modes (the button flips a markdown/html + * preview to edit first, since the panel lives in the editor surface). + */ +// @vitest-environment jsdom +import { afterEach, describe, expect, it } from 'vitest' +import { createElement } from 'react' +import { act } from 'react-dom/test-utils' +import { renderRoot, setupReactAct } from './test-utils.ts' +import { TextEditor } from '../src/client/TextEditor.tsx' +import { attachLocale } from '../src/client/locales.ts' +import { createSidebarStore } from '../src/client/state.ts' +import type { FileViewerProps } from '../src/client/service.ts' + +setupReactAct() + +/** Minimal structural fake of the DSH LocaleService face the sidebar uses. */ +class FakeLocale { + active: string = 'en' + getSnapshot(): { active: string } { + return { active: this.active } + } + subscribe(_fn: () => void): () => void { + return () => {} + } + register(_ns: string, _locale: string, _dict: Record): void { + return () => {} + } +} + +function viewerProps(overrides: Partial = {}): FileViewerProps { + return { + ctx: {} as FileViewerProps['ctx'], + store: createSidebarStore(), + scope: { sessionId: 's1', cwd: '/p' }, + path: '/p/a.md', + title: 'a.md', + viewerId: 'markdown', + content: '# Title\n\nneedle here\n\nneedle again\n', + ...overrides, + } +} + +function click(element: HTMLElement): void { + act(() => { element.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) +} + +/** The toolbar's search button (locale-dependent aria-label). */ +function searchButton(container: HTMLDivElement): HTMLButtonElement { + const button = container.querySelector('button[aria-label="Find"], button[aria-label="查找"]') + if (button === null) throw new Error('search button not found') + return button as HTMLButtonElement +} + +/** The CodeMirror search panel, or null while closed. */ +function searchPanel(container: HTMLDivElement): HTMLElement | null { + return container.querySelector('.cm-search') +} + +afterEach(() => { + attachLocale(undefined) + document.body.innerHTML = '' +}) + +describe('TextEditor find/replace', () => { + it('opens the search panel from the toolbar button, in edit mode', () => { + const locale = new FakeLocale() + attachLocale(locale) + const mounted = renderRoot(createElement(TextEditor, viewerProps())) + try { + expect(searchPanel(mounted.container)).toBeNull() + click(searchButton(mounted.container)) + const panel = searchPanel(mounted.container) + expect(panel).not.toBeNull() + // The markdown editor flipped from preview to edit (the panel lives in + // the CodeMirror surface, which is display:none while previewing). + expect(panel!.closest('[hidden]')).toBeNull() + } finally { + mounted.unmount() + } + }) + + it('localizes the panel labels from the sidebar dictionary (en)', () => { + const locale = new FakeLocale() + locale.active = 'en' + attachLocale(locale) + const mounted = renderRoot(createElement(TextEditor, viewerProps({ viewerId: 'code', path: '/p/a.ts' }))) + try { + click(searchButton(mounted.container)) + const panel = searchPanel(mounted.container) + expect(panel).not.toBeNull() + const text = panel!.textContent ?? '' + expect(text).toContain('Replace') + expect(text).toContain('Match case') + expect(text).toContain('Whole word') + // The panel's Find input carries the placeholder/aria-label. + const findInput = panel!.querySelector('input[name="search"]') + expect(findInput?.getAttribute('aria-label')).toBe('Find') + } finally { + mounted.unmount() + } + }) + + it('localizes the panel labels from the sidebar dictionary (zh)', () => { + const locale = new FakeLocale() + locale.active = 'zh' + attachLocale(locale) + const mounted = renderRoot(createElement(TextEditor, viewerProps({ viewerId: 'code', path: '/p/a.ts' }))) + try { + click(searchButton(mounted.container)) + const panel = searchPanel(mounted.container) + expect(panel).not.toBeNull() + const text = panel!.textContent ?? '' + expect(text).toContain('替换') + expect(text).toContain('区分大小写') + expect(text).toContain('全词') + const findInput = panel!.querySelector('input[name="search"]') + expect(findInput?.getAttribute('aria-label')).toBe('查找') + } finally { + mounted.unmount() + } + }) + + it('opens the panel with Mod-f on the editor surface', () => { + attachLocale(new FakeLocale()) + const mounted = renderRoot(createElement(TextEditor, viewerProps({ viewerId: 'code', path: '/p/a.ts' }))) + try { + const content = mounted.container.querySelector('.cm-content') + expect(content).not.toBeNull() + act(() => { + content!.dispatchEvent(new KeyboardEvent('keydown', { + key: 'f', code: 'KeyF', ctrlKey: true, bubbles: true, cancelable: true, + })) + }) + expect(searchPanel(mounted.container)).not.toBeNull() + } finally { + mounted.unmount() + } + }) +})