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
This commit is contained in:
Menghuan1918 committed 2026-10-05 01:58:18 +08:00
commit 783ac9feb6
38 files changed
+1171 -23

No files matched your search

+4 -1
View File
@@ -241,7 +241,9 @@ dsh registry enable dsh-external/dsh-better-sidebar
| 操作 | 按键 |
|---|---|
| 保存编辑 | `Ctrl/Cmd + S` |
| 文件内查找 | `Ctrl/Cmd + F`(`Enter` / `Shift + Enter` 下一个 / 上一个,`Esc` 关闭) |
| 文件内查找 / 替换 | `Ctrl/Cmd + F`(面板含替换行;`Enter` / `Shift + Enter` 下一个 / 上一个,`Esc` 关闭) |
| 查找下一个 / 上一个 | `Ctrl/Cmd + G` / `Shift + Ctrl/Cmd + G` |
| 选中下一个相同片段 | `Ctrl/Cmd + D` |
| Git 提交 | `Ctrl + Enter` |
| 关闭 Tab | 鼠标中键 |
| Tab 右键菜单 | 关闭 / 关闭其他页签 / 关闭左侧页签 / 关闭右侧页签(当前标签组) |
@@ -294,6 +296,7 @@ make clean # 清理 lib/、*.tgz、playwright-report/、test-results/
## ⚠️ 已知限制
- Git 无 push/pull/fetch;Markdown 预览提供手动刷新按钮,刷新未保存编辑前会确认是否丢弃草稿;文件树只对**已展开**的目录做 watch(折叠的目录不订阅,也不做全工作区递归扫描);工具行内文件打开按钮不可拦截
- 未保存草稿:关闭编辑器标签页、删除文件、浏览器刷新/关闭页面都会先确认(查找/替换面板只作用于当前编辑器,不做跨文件搜索);磁盘上被其他来源改动后再保存会被拒绝(提示「重新载入」),不会静默覆盖对方字节
- **只读预览的格式由宿主决定**:表格 / PDF / 图片 / Office 走 DSH 自己的 `ui-sidebar-documentpreview`,插件只渲染 Markdown / HTML 与可编辑的文本代码;宿主的实现(渲染细节、缩放、刷新时机)随 DSH 版本走
- **浏览器视图只在 desktop profile 存在**:Web profile 没有宿主 `browser` kind,插件也不再自带浏览器 tab,因此网页 tab 只在 desktop profile 可用;登录态 / 第三方 Cookie / `X-Frame-Options` 等限制随宿主实现
- HTML 预览渲染的是已保存文件(不反映未保存草稿)
+4 -1
View File
@@ -250,7 +250,9 @@ WeChat / QQ group QR codes will live here. After uploading the QR images (drag t
| Action | Keys |
|---|---|
| Save edits | `Ctrl/Cmd + S` |
| Find in file | `Ctrl/Cmd + F` (`Enter` / `Shift + Enter` next / previous, `Esc` closes) |
| Find / replace in file | `Ctrl/Cmd + F` (the panel carries the replace row; `Enter` / `Shift + Enter` next / previous, `Esc` closes) |
| Find next / previous | `Ctrl/Cmd + G` / `Shift + Ctrl/Cmd + G` |
| 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) |
@@ -303,6 +305,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; the file tree only watches **expanded** directories (collapsed folders are unsubscribed, and there is no recursive whole-workspace scan); tool inline file-open buttons cannot be intercepted
- Unsaved drafts: closing an editor tab, deleting the file, and refreshing/closing the page all confirm first (the find/replace panel covers 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
- **Which read-only previews exist is the host's call**: spreadsheets / PDF / images / Office go to DSH's own `ui-sidebar-documentpreview`, while the plugin renders only Markdown / HTML and the editable text buffer; the host implementation (rendering details, zoom, refresh timing) follows the DSH version
- **The browser view exists only in the desktop profile**: the Web profile has no host `browser` kind and the plugin no longer ships a browser tab, so web tabs are desktop-only; login state / third-party cookies / `X-Frame-Options` limits follow the host implementation
- HTML preview renders the saved file (not unsaved drafts)
+4 -2
View File
@@ -486,12 +486,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 // 从磁盘重新加载(保存冲突横幅的按钮回调)
}
```
@@ -603,8 +605,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.trees` | **批量**目录列表(v0.23.0+):入参 `{ sessionId, cwd?, paths: string[] }`(最多 64 条,绝对或会话相对),一次请求返回 `{ levels: [{ path, entries, truncated, error? }] }`。每层与 `fs.tree` 同解析、同缓存;**某一层失败只在该层带 `error`**(`entries: []`),整个批次仍是成功响应——树的一次挂载/刷新因此是 1 个请求而不是 N 个 |
| `fs.read` | 读文件:文本返回 `{ kind: 'text', content, truncated }`;二进制返回 `{ 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` | **已删除**(插件自带的 PTY 栈随终端一起移除;宿主 `ui-sidebar-terminal` 不通过本插件的路由暴露控制面) |
| `settings.get` / `settings.update` | 侧边栏偏好读写(revision 守卫,冲突回 wire 错误码 `settings-conflict`);后端在 0.1.7 上就是宿主的 `SettingsForms`,见 §8.2 |
@@ -0,0 +1,84 @@
# 编辑器未保存草稿保护 + 保存冲突检测 + 内置查找替换
> 状态:已实施(2026-09-09)。三项改动都在内置文本编辑器/侧边栏这一侧,不改 `ctx.betterSidebar` 的服务方法签名,不碰 DSH 源码。
>
> **合入 `dev` 时的取舍(#600 解冲突,2026-10-05)**:本 PR 的基线(`d88dcfc`)落后 `dev` 约 300 个提交,落地时与三处已合并的工作重叠——① **编辑器内查找**已由 **#587**(`4ac02b3`)落地(`src/client/cm-search.ts`:`search({top:true})` + `searchKeymap` + phrases 隔间 + 面板主题,词典键一律 `search*` 前缀),因此本 PR 的那份查找接线(本地 `searchPhrases()`、`EditorState.phrases.of`、`search({top:true})`、编辑器 keymap 里的 `searchKeymap`)与 10 个 `find*`/`replace*` 词典键**整份删除**,只留工具栏放大镜按钮(它独有的入口,改用 #587 的 `searchFind` 文案);② **并发写临时文件**已由 **2e22b90** 落地(`.dsh-sidebar-tmp-<uuid>`,`flag: 'wx'`),本 PR 的 `.dsh-write-<uuid>` 改名**丢弃**,只保留冲突门与 `tests/fs-write-route.spec.ts` 的回归;③ `IconSearchOutline16` 在宿主 0.1.7 图标整族改名后已不存在,改为 `IconSearchOutlineRegular size={16}`。README/指南里的 `Ctrl/Cmd + H` 声明**删除**:本 PR 从未绑定 `Mod-h`,且浏览器保留该组合键(历史/隐藏窗口),页面无法可靠接管。
## 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)` 会删掉后完成者的临时文件(**已由 `2e22b90` 在 `dev` 上修掉,本 PR 不再重复**) |
| D 编辑器没有查找替换 | `Ctrl/Cmd + F` 无反应 | `@codemirror/search` 在 `dependencies` 里但 `src/` 零引用(依赖白装)(**查找部分已由 #587 落地,本 PR 只补工具栏入口**) |
## 2. 设计
### 2.1 脏稿登记表(`src/client/editor-dirty.ts`,新增)
模块级 `Map<tabId, {sessionId, path}>` + 监听器集合 + 单调 `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 并发写互删修复
**不在本 PR 的范围内**:`dev` 的 `2e22b90` 已把临时文件命名为 `.${basename(path)}.dsh-sidebar-tmp-${randomUUID()}.tmp`(`flag: 'wx'`),每次保存有自己的临时兄弟文件,任何一次 `rm(tmp)` 都只可能删到自己的。本 PR 解冲突时保留该命名,只把自带的 `tests/fs-write-route.spec.ts` 的残留断言改指它。
### 2.5 内置查找/替换
**面板与键位由 #587 提供**(`src/client/cm-search.ts`:`search({ top: true })`、上游 `searchKeymap`、`CmSearchPhrases` 语言隔间、`cmSearchTheme` 令牌主题),本 PR 不重复接线。本 PR 独有的只有**工具栏放大镜按钮**:预览态下先切到编辑态再 `openSearchPanel(view)`(面板挂在 CodeMirror 表面上,预览态该表面是隐藏的),文案用 #587 的 `searchFind`(`Find` / `查找`)。可编辑视图的面板自带**替换行**(`input[name=replace]`),所以按钮同时触达查找与替换;`Ctrl/Cmd + H` 未被绑定也不再声明(浏览器保留该组合键)。
## 3. 测试
| 文件 | 覆盖 |
|---|---|
| `tests/editor-unsaved-guard.spec.tsx`(新,8 例) | 登记表语义(幂等 / 换文件重指向 / 订阅);`EditorHost` 登记与卸载清理;**真 Sidebar** 下取消保留 / 确认关闭 / 干净不弹窗;`confirmDiscardDraft` 分支;`closePathTabs` 的拒绝与确认 |
| `tests/fs-write-route.spec.ts`(新,5 例) | 并发同路径保存无交叉删除、无残留(按 dev 的 `.dsh-sidebar-tmp-` 命名断言);重复保存;基线不符 409 + 对方字节存活;基线相符成功并回报新基线;省略基线仍可写(旧调用方) |
| `tests/text-editor-conflict.spec.tsx`(新,4 例) | 发送基线 mtime;`fs-conflict` 显示横幅且草稿保留、「重新载入」回调触发;普通失败不显示冲突横幅;成功后采纳新基线 |
| `tests/text-editor-search.spec.tsx`(新,1 例) | 工具栏按钮开面板(含替换行)并把 markdown 预览切到编辑态;**面板键位与文案的覆盖在 `tests/editor-find.spec.tsx`(#587)** |
| `tests/locales.spec.ts`(既有) | 每个第三语言词典与 zh 键集相等(本 PR 新增 3 个 key:`closeUnsavedConfirm` / `saveConflict` / `saveConflictReload`,已同步 19 个词典) |
## 4. 已知偏差与取舍
- **`fs.write` 的基线不是内容哈希**:mtime 足够挡住「模型改了文件」这类秒级以上的改动,且零额外 IO;同一毫秒内的并发写仍可能双双通过(此时以最后一次 rename 为准)。要更强一致需内容哈希,代价是每次保存多读一遍文件,暂不引入。
- **Windows 上并发 rename 可能报 EPERM**(文件被杀软/句柄短暂占用):这是平台行为,与「互删临时文件」(`2e22b90` 已修)无关;`tests/fs-write-route.spec.ts` 的并发用例显式允许 EPERM 但拒绝 ENOENT,并断言无残留。
- **外部 viewer 不参与脏稿保护**:只有内置文本编辑器会报告 `dirty`。第三方 viewer 若想接入,需要自己调用 `setEditorDirty`(当前未开放为服务 API,因为还没有第二个真实消费者)。
- **跨会话切换不弹窗**:切换会话时未保存草稿会随组件卸载消失。页面级 `beforeunload` 覆盖了「关页/刷新」,会话内切换留待有真实需求时再加(会话切换本身是用户主动且可预期的操作)。
- **未做跨文件搜索**:`Ctrl/Cmd+F` 只作用于当前编辑器;按仓库既定理念,跨文件代码搜索留给生态插件(`pluginCodeNav`)。
+20 -3
View File
@@ -30,6 +30,7 @@ import type { Context } from '../context-types.ts'
import { api, mediaUrl, type SessionScope } from './api.ts'
import { BinaryDownload } from './binary-download.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 { openClaimedNativeFile, openSidebarFile } from './sidebar-file.ts'
@@ -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). */
@@ -281,7 +282,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
@@ -296,6 +297,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
@@ -387,7 +399,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) })
@@ -537,12 +552,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,
})}
</div>
{treeOpen && (
+23
View File
@@ -46,6 +46,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 { mountedSessions } from './native/surface.ts'
@@ -221,6 +222,23 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) {
// 空白会话(无 user/assistant message)里宿主不渲染会话头,本插件的会话头入口不可达:
// 由 DockFallback 自行按会话相位决定是否渲染(sidebar/dock-fallback.tsx),二者互斥。
// 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])
// Title-bar / shell compatibility (the "位置兼容模式" scheme):
// auto — CONSERVATIVE: only the standard Window Controls Overlay
// geometry contributes (the real caption-overlay height,
@@ -500,6 +518,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
// Route through the service: the tab-bar close is the canonical close
// path (finds the pane itself, fires descriptor.onClose); the session
// scope (with its cwd) rides to the callback.
+59 -4
View File
@@ -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 { IconCheckOutlineRegular, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
import { openSearchPanel } from '@codemirror/search'
import { IconCheckOutlineRegular, IconSearchOutlineRegular, 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'
@@ -59,9 +60,15 @@ export function TextEditor(props: FileViewerProps) {
const [draft, setDraft] = useState<string | null>(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<HTMLDivElement>(null)
const viewRef = useRef<CodeMirrorView | null>(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<number | null>(props.mtimeMs ?? null)
/** The theme compartment of the current view (reconfigured on scheme flip). */
const themeCompRef = useRef<CmThemeCompartment | null>(null)
/** The search-phrases compartment of the current view (reconfigured on a
@@ -137,6 +144,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.
@@ -372,13 +382,26 @@ export function TextEditor(props: FileViewerProps) {
if (truncated === true) 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')
})
}
@@ -540,6 +563,26 @@ export function TextEditor(props: FileViewerProps) {
</div>
)}
{dirty && <span className={css.dirtyDot} title={t('unsaved')} />}
{editable && (
<button
type="button"
className={css.iconButton}
aria-label={t('searchFind')}
title={`${t('searchFind')} (Ctrl/Cmd+F)`}
onClick={() => {
// The panel lives in the CodeMirror surface: in preview mode the
// editor is hidden, so switch to edit first (the search panel is
// not part of the preview).
if (mode === 'preview' && (markdown || html)) setMode('edit')
const view = viewRef.current
if (view === null) return
view.focus()
openSearchPanel(view)
}}
>
<IconSearchOutlineRegular size={16} />
</button>
)}
{editable && truncated !== true && (
<button
type="button"
@@ -557,6 +600,18 @@ export function TextEditor(props: FileViewerProps) {
{editable && (
<>
{truncated === true && <div className={css.editorBanner}>{t('truncation')}</div>}
{conflict && (
<div className={css.editorBanner}>
{t('saveConflict')}
<button
type="button"
className={css.editorBannerAction}
onClick={() => { props.onReload?.() }}
>
{t('saveConflictReload')}
</button>
</div>
)}
<div
className={clsx(css.editorCm, (markdown || html) && mode === 'preview' && css.editorCmHidden)}
ref={hostRef}
+14 -5
View File
@@ -89,11 +89,11 @@ export interface GitLogEntry {
refs: string
}
/** Text read result. */
export interface FsTextResult { kind: 'text'; content: string; truncated: boolean }
/** Text read result. `mtimeMs` is the save route's conflict baseline. */
export interface FsTextResult { kind: 'text'; content: string; truncated: boolean; mtimeMs?: number }
/** Binary read result (no content; images load through the media route).
* `head` carries the first bytes (base64) for viewer detect sniffing. */
export interface FsBinaryResult { kind: 'binary'; size: number; truncated: boolean; head: string }
export interface FsBinaryResult { kind: 'binary'; size: number; truncated: boolean; mtimeMs?: number; head: string }
/** The `subagents.live` response: one row per tree child (and the root). */
export type SubagentLiveResult = { live: Record<string, SidebarChildLiveView> }
@@ -299,8 +299,17 @@ export const api = {
call<{ matches: string[]; dirs: string[]; truncated: boolean }>('fs.search', scopePayload(scope, { query }), signal),
fsRead: (scope: SessionScope, path: string, signal?: AbortSignal) =>
call<FsTextResult | FsBinaryResult>('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). */
+106
View File
@@ -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<string, DirtyEntry>()
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
}
+3
View File
@@ -141,10 +141,13 @@ export const ar: Record<string, string> = {
refresh: 'تحديث',
showInFolder: 'إظهار في المجلد',
refreshUnsavedConfirm: 'تغيّر الملف على القرص. سيؤدي التحديث إلى فقدان التعديلات غير المحفوظة. متابعة؟',
closeUnsavedConfirm: 'يحتوي هذا الملف على تعديلات غير محفوظة. سيؤدي إغلاق علامة التبويب إلى تجاهلها. المتابعة؟',
save: 'حفظ',
saved: 'تم الحفظ',
unsaved: 'غير محفوظ',
saveFailed: 'فشل الحفظ',
saveConflict: 'تم تغيير الملف على القرص من مصدر آخر. تم إيقاف الحفظ، وتعديلاتك ما زالت في المحرر.',
saveConflictReload: 'إعادة التحميل من القرص',
truncation: 'الملف كبير جداً — عرض أول 512KB',
searchFind: 'بحث',
searchReplace: 'استبدال',
+3
View File
@@ -126,10 +126,13 @@ export const de: Record<string, string> = {
refresh: 'Aktualisieren',
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',
searchFind: 'Suchen',
searchReplace: 'Ersetzen',
+3
View File
@@ -133,10 +133,13 @@ export const fr: Record<string, string> = {
refresh: 'Actualiser',
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',
searchFind: 'Rechercher',
searchReplace: 'Remplacer',
+3
View File
@@ -140,10 +140,13 @@ export const hi: Record<string, string> = {
refresh: 'ताज़ा करें',
showInFolder: 'फ़ोल्डर में दिखाएँ',
refreshUnsavedConfirm: 'डिस्क पर फ़ाइल बदल गई है। रीफ़्रेश करने पर असहेज किए गए संपादन खो जाएँगे। जारी रखें?',
closeUnsavedConfirm: 'इस फ़ाइल में सहेजे नहीं गए संपादन हैं। टैब बंद करने पर वे हट जाएँगे। जारी रखें?',
save: 'सहेजें',
saved: 'सहेजा गया',
unsaved: 'असहेजित',
saveFailed: 'सहेजना विफल',
saveConflict: 'फ़ाइल डिस्क पर किसी अन्य स्रोत से बदल दी गई है। सहेजना रोक दिया गया; आपके संपादन एडिटर में बने हुए हैं।',
saveConflictReload: 'डिस्क से फिर लोड करें',
truncation: 'फ़ाइल बहुत बड़ी — पहले 512KB दिखाए जा रहे',
searchFind: 'खोजें',
searchReplace: 'बदलें',
+3
View File
@@ -138,10 +138,13 @@ export const id: Record<string, string> = {
refresh: 'Segarkan',
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',
searchFind: 'Cari',
searchReplace: 'Ganti',
+3
View File
@@ -131,10 +131,13 @@ export const it: Record<string, string> = {
refresh: 'Aggiorna',
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',
searchFind: 'Trova',
searchReplace: 'Sostituisci',
+3
View File
@@ -140,10 +140,13 @@ export const ja: Record<string, string> = {
refresh: '更新',
showInFolder: 'フォルダーで表示',
refreshUnsavedConfirm: 'ディスク上のファイルが変更されました。更新すると未保存の編集が失われます。続行しますか?',
closeUnsavedConfirm: 'このファイルには未保存の編集があります。タブを閉じると破棄されます。続行しますか?',
save: '保存',
saved: '保存済み',
unsaved: '未保存',
saveFailed: '保存に失敗',
saveConflict: 'ファイルはディスク上で他によって変更されています。保存を中止しました。編集内容はそのまま残っています。',
saveConflictReload: 'ディスクの内容を再読み込み',
truncation: 'ファイルが大きすぎます — 最初の 512KB のみ表示',
searchFind: '検索',
searchReplace: '置換',
+3
View File
@@ -132,10 +132,13 @@ export const ko: Record<string, string> = {
refresh: '새로고침',
showInFolder: '폴더에서 표시',
refreshUnsavedConfirm: '디스크의 파일이 변경되었습니다. 새로고침하면 저장되지 않은 편집 내용이 손실됩니다. 계속하시겠습니까?',
closeUnsavedConfirm: '이 파일에 저장되지 않은 편집이 있습니다. 탭을 닫으면 삭제됩니다. 계속하시겠습니까?',
save: '저장',
saved: '저장됨',
unsaved: '저장 안 됨',
saveFailed: '저장 실패',
saveConflict: '파일이 디스크에서 다른 곳에 의해 변경되었습니다. 저장이 중단되었고 편집 내용은 그대로 남아 있습니다.',
saveConflictReload: '디스크에서 다시 불러오기',
truncation: '파일이 너무 커 앞의 512KB만 표시합니다',
searchFind: '찾기',
searchReplace: '바꾸기',
+3
View File
@@ -138,10 +138,13 @@ export const nl: Record<string, string> = {
refresh: 'Vernieuwen',
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',
searchFind: 'Zoeken',
searchReplace: 'Vervangen',
+3
View File
@@ -142,10 +142,13 @@ export const pl: Record<string, string> = {
refresh: 'Odśwież',
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',
searchFind: 'Szukaj',
searchReplace: 'Zamień',
+3
View File
@@ -123,10 +123,13 @@ export const pt: Record<string, string> = {
refresh: 'Atualizar',
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',
searchFind: 'Localizar',
searchReplace: 'Substituir',
+3
View File
@@ -136,10 +136,13 @@ export const ru: Record<string, string> = {
refresh: 'Обновить',
showInFolder: 'Показать в папке',
refreshUnsavedConfirm: 'Файл изменился на диске. Обновление отбросит несохранённые изменения. Продолжить?',
closeUnsavedConfirm: 'В файле есть несохранённые изменения. Закрытие вкладки их отменит. Продолжить?',
save: 'Сохранить',
saved: 'Сохранено',
unsaved: 'Не сохранено',
saveFailed: 'Не удалось сохранить',
saveConflict: 'Файл был изменён на диске другим источником. Сохранение прервано; ваши правки остались в редакторе.',
saveConflictReload: 'Перезагрузить с диска',
truncation: 'Файл слишком велик — показаны первые 512 КБ',
searchFind: 'Найти',
searchReplace: 'Заменить',
+3
View File
@@ -123,10 +123,13 @@ export const sv: Record<string, string> = {
refresh: 'Uppdatera',
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',
searchFind: 'Sök',
searchReplace: 'Ersätt',
+3
View File
@@ -140,10 +140,13 @@ export const th: Record<string, string> = {
refresh: 'รีเฟรช',
showInFolder: 'แสดงในโฟลเดอร์',
refreshUnsavedConfirm: 'ไฟล์เปลี่ยนบนดิสก์ การรีเฟรชจะทิ้งการแก้ไขที่ยังไม่ได้บันทึก ดำเนินการต่อหรือไม่',
closeUnsavedConfirm: 'ไฟล์นี้มีการแก้ไขที่ยังไม่ได้บันทึก การปิดแท็บจะทิ้งการแก้ไขนั้น ดำเนินการต่อหรือไม่',
save: 'บันทึก',
saved: 'บันทึกแล้ว',
unsaved: 'ยังไม่ได้บันทึก',
saveFailed: 'บันทึกล้มเหลว',
saveConflict: 'ไฟล์ถูกแก้ไขบนดิสก์จากแหล่งอื่น การบันทึกถูกยกเลิก การแก้ไขของคุณยังอยู่ในเอดิเตอร์',
saveConflictReload: 'โหลดใหม่จากดิสก์',
truncation: 'ไฟล์ใหญ่เกินไป — แสดงเพียง 512KB แรก',
searchFind: 'ค้นหา',
searchReplace: 'แทนที่',
+3
View File
@@ -140,10 +140,13 @@ export const tr: Record<string, string> = {
refresh: 'Yenile',
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',
searchFind: 'Bul',
searchReplace: 'Değiştir',
+3
View File
@@ -140,10 +140,13 @@ export const vi: Record<string, string> = {
refresh: 'Làm mới',
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',
searchFind: 'Tìm',
searchReplace: 'Thay thế',
+3
View File
@@ -155,10 +155,13 @@ export const zhHK: Record<string, string> = {
refresh: '重新整理',
showInFolder: '在文件夾中顯示',
refreshUnsavedConfirm: '檔案已在磁碟上變更。重新整理會丟失尚未儲存的編輯。繼續?',
closeUnsavedConfirm: '此檔案有未儲存的編輯,關閉後將被丟棄。繼續嗎?',
save: '儲存',
saved: '已儲存',
unsaved: '未儲存',
saveFailed: '儲存失敗',
saveConflict: '檔案已在磁碟上被其他來源修改。儲存已中止,你的編輯仍在編輯器中。',
saveConflictReload: '重新載入磁碟內容',
truncation: '檔案過大,僅顯示前 512KB',
searchFind: '尋找',
searchReplace: '取代',
+3
View File
@@ -155,10 +155,13 @@ export const zhMO: Record<string, string> = {
refresh: '重新整理',
showInFolder: '在文件夾中顯示',
refreshUnsavedConfirm: '檔案已在磁碟上變更。重新整理會丟失尚未儲存的編輯。繼續?',
closeUnsavedConfirm: '此檔案有未儲存的編輯,關閉後將被丟棄。繼續嗎?',
save: '儲存',
saved: '已儲存',
unsaved: '未儲存',
saveFailed: '儲存失敗',
saveConflict: '檔案已在磁碟上被其他來源修改。儲存已中止,你的編輯仍在編輯器中。',
saveConflictReload: '重新載入磁碟內容',
truncation: '檔案過大,僅顯示前 512KB',
searchFind: '尋找',
searchReplace: '取代',
+3
View File
@@ -155,10 +155,13 @@ export const zhTW: Record<string, string> = {
refresh: '重新整理',
showInFolder: '在資料夾中顯示',
refreshUnsavedConfirm: '檔案已在磁碟上變更。重新整理會丟失尚未儲存的編輯。繼續?',
closeUnsavedConfirm: '此檔案有未儲存的編輯,關閉後將被丟棄。繼續嗎?',
save: '儲存',
saved: '已儲存',
unsaved: '未儲存',
saveFailed: '儲存失敗',
saveConflict: '檔案已在磁碟上被其他來源修改。儲存已中止,你的編輯仍在編輯器中。',
saveConflictReload: '重新載入磁碟內容',
truncation: '檔案過大,僅顯示前 512KB',
searchFind: '尋找',
searchReplace: '取代',
+6
View File
@@ -151,10 +151,13 @@ export const zh = {
mermaidZoomHint: '滚轮缩放 · 拖拽平移 · Esc 关闭',
refresh: '刷新',
refreshUnsavedConfirm: '文件已在磁盘更新,刷新将丢弃未保存编辑。继续吗?',
closeUnsavedConfirm: '该文件有未保存的编辑,关闭后将丢弃。继续吗?',
save: '保存',
saved: '已保存',
unsaved: '未保存',
saveFailed: '保存失败',
saveConflict: '文件已在磁盘上被其他来源修改。保存已中止,你的修改仍在编辑器中。',
saveConflictReload: '重新载入磁盘内容',
truncation: '文件过大,仅显示前 512KB',
searchFind: '查找',
searchReplace: '替换',
@@ -689,10 +692,13 @@ export const en: Record<keyof typeof zh, string> = {
mermaidZoomHint: 'Scroll to zoom · drag to pan · Esc to close',
refresh: 'Refresh',
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',
searchFind: 'Find',
searchReplace: 'Replace',
+6
View File
@@ -289,6 +289,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'). */
@@ -303,6 +307,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. */
+12
View File
@@ -1496,6 +1496,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
+8 -3
View File
@@ -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'
@@ -38,12 +39,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)
}
}
+27 -4
View File
@@ -216,6 +216,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) => {
@@ -243,6 +245,7 @@ async function readText(path: string, readLimit: number): Promise<{
truncated,
binary,
size,
mtimeMs: info.mtimeMs,
head,
}
} finally {
@@ -388,9 +391,9 @@ 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))
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)
@@ -399,6 +402,24 @@ function buildApi(
// Detect the encoding BEFORE the temp write so the save round-trips the
// bytes the file already used (GBK / UTF-16 / BOM'd UTF-8 stay put).
const encoding = await encodingOfFile(path)
// 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,
)
}
}
// Per-request temp name (same pattern as writeWorkspaceUpload): a
// pid-suffixed name is shared by every concurrent save to the same
// path, letting two writers interleave into one temp file — and the
@@ -413,7 +434,9 @@ function buildApi(
throw new SidebarError('fs-error', `cannot write "${path}": ${error instanceof Error ? error.message : String(error)}`, 400)
}
invalidateDirectoryCache(dirname(path))
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).
+1
View File
@@ -18,6 +18,7 @@ export type SidebarErrorCode =
| 'method-error'
| 'too-large'
| 'fs-error'
| 'fs-conflict'
| 'git-error'
| 'job-error'
| 'team-error'
+304
View File
@@ -0,0 +1,304 @@
/**
* 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, toggleBottomPanel, 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()
// Partial mock: only the reads this spec drives are stubbed. The sidebar shell
// also touches `sessionPhase` / `api.sessionCwd` / the tree panel on mount, and
// a wholesale replacement breaks them (`No "sessionPhase" export …`).
vi.mock('../src/client/api.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/client/api.ts')>()
return {
...actual,
api: {
...actual.api,
fsRead: (...args: unknown[]) => fsRead(...args),
fsTree: () => Promise.resolve({ path: '', entries: [], truncated: false }),
},
}
})
/** 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,
})
const sessionId = `dirty-${++sessionSeq}`
store.setSession(sessionId)
// The plugin's own workbench hosts its tabs; without the panel open the tab
// strip (and its close button) is not rendered at all.
store.reduce(toggleBottomPanel)
const localeSnapshot = { active: 'en' }
// The session-list snapshot never carried a current-session field: the shell
// binds its per-session state to the native surface's mounted seat.
const sessionsSnapshot = { byId: { [sessionId]: { cwd: '/tmp' } } }
const mounted = { getSnapshot: () => sessionId, subscribe: () => () => {} }
const ctx = {
locale: { subscribe: () => () => {}, getSnapshot: () => localeSnapshot },
sessions: { list: { subscribe: () => () => {}, getSnapshot: () => sessionsSnapshot } },
betterSidebar: service,
get: (name: string) => name === 'betterSidebar'
? service
: name === 'sidebarRight' ? { mounted } : 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 []
// The plugin's tabs live in its own bottom workbench (the main column
// belongs to DSH's native right sidebar).
return 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!.bottomSplits).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()
}
})
})
+205
View File
@@ -0,0 +1,205 @@
/**
* 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 })
}
})
})
+124
View File
@@ -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<typeof import('../src/client/api.ts')>()
return {
...actual,
api: { fsWrite: (...args: unknown[]) => fsWrite(...args) },
}
})
function viewerProps(overrides: Partial<FileViewerProps> = {}): 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()
}
})
})
+103
View File
@@ -0,0 +1,103 @@
/**
* The built-in text editor's find/replace TOOLBAR affordance: the header's
* magnifier button opens CodeMirror's search panel — the same panel the
* Ctrl/Cmd+F keymap opens (find-in-file wiring itself is pinned by
* editor-find.spec.tsx, which owns the extensions, the keymap and the panel
* copy) — and the panel carries the REPLACE row, so the button reaches both
* halves of the find/replace surface. The button also flips a markdown
* preview to edit first, since the panel lives in the hidden CodeMirror
* 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 () => {}
}
}
function viewerProps(overrides: Partial<FileViewerProps> = {}): 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')
}
/** The header's preview/edit toggle buttons, keyed by their label. */
function modeButton(container: HTMLDivElement, label: string): HTMLButtonElement {
const button = Array.from(container.querySelectorAll('button'))
.find(candidate => candidate.textContent === label)
if (button === undefined) throw new Error(`mode button "${label}" not found`)
return button
}
/** The active mode toggle carries one extra class (the "active" marker). */
function activeMode(container: HTMLDivElement): string {
const preview = modeButton(container, 'Preview')
const edit = modeButton(container, 'Edit')
return edit.classList.length > preview.classList.length ? 'edit' : 'preview'
}
afterEach(() => {
attachLocale(undefined)
document.body.innerHTML = ''
})
describe('TextEditor find/replace toolbar button', () => {
it('opens the search panel, replace row included, from the toolbar button', () => {
attachLocale(new FakeLocale())
const mounted = renderRoot(createElement(TextEditor, viewerProps()))
try {
expect(searchPanel(mounted.container)).toBeNull()
// The markdown viewer starts in preview, where the CodeMirror surface
// (and therefore the panel) is hidden — the button must flip first.
expect(activeMode(mounted.container)).toBe('preview')
click(searchButton(mounted.container))
const panel = searchPanel(mounted.container)
expect(panel).not.toBeNull()
// The button reaches the REPLACE half too (an editable view's panel
// renders the second field; a read-only one would not).
expect(panel!.querySelector('input[name="replace"]')).not.toBeNull()
expect(activeMode(mounted.container)).toBe('edit')
} finally {
mounted.unmount()
}
})
})