fix(editor): 原生页签关闭与桌面退出保留未保存草稿(#1072 / #1071)

宿主原生页签条的关闭路径只有一个同步清理钩子(唯一的阻止方式是 throw,
会把异常抛给 replaceTab / 公共 close() 调用方),桌面 Cmd+Q 则完全在壳内
完成(before-quit → app.exitRequested),页面没有可取消事件;壳内也没有
will-prevent-unload 处理器。插件因此不伪造拦截,改为降低损失:

- 草稿变脏时按 1 s 节流把实时文档写入 localStorage(sessionId::path,
  单条 200k 字符 / 总计 600k / 最多 8 条 FIFO)
- 原生 registerCloseHandler('editor') 与 beforeunload 时立即 flush
- 重开同一文件提示恢复;保存、确认丢弃、确认刷新/换文件即删除备份

新增 src/client/editor-draft-backup.ts;docs/host-contracts.md §C 记录宿主
限制与将来的接法。测试:新增 editor-draft-backup.spec.tsx(8 例)+ guard
spec 2 例;去掉任一修复点后对应用例均转红。
This commit is contained in:
Menghuan1918 committed 2026-11-04 21:04:16 +08:00
1 parent 4f6b763d1e
commit 4224c78a98
32 files changed
+647 -11

No files matched your search

+4
View File
@@ -4,6 +4,10 @@
### 未发布
- 🛟 **原生页签关闭与桌面 Cmd+Q 不再无声丢掉编辑器草稿**([#1072](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1072) / [#1071](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1071)):宿主原生右侧栏的页签条(× / 中键 / 上下文菜单 / `page.close`)与桌面壳的退出都没有「可确认」的关闭钩子(`registerCloseHandler` 是同步清理,唯一的阻止方式是 `throw`;桌面 Cmd+Q 走壳自己的 `before-quit` → `app.exitRequested`,页面收不到可取消事件,详见[宿主契约 §C](docs/host-contracts.md))。插件无法在这两条路径上弹确认,因此改为降低损失:草稿变脏时按 1 s 节流把**实时文档**写入 `localStorage`(key = `sessionId::path`;单条 200k 字符、总计 600k、最多 8 条、FIFO 淘汰),在原生关闭回调与 `beforeunload` 时立即落盘,重开同一文件时提示「检测到未保存的草稿,恢复吗?」。保存成功、确认丢弃、确认刷新 / 就地换文件都会删掉对应备份。
- 🧪 测试:新增 `tests/editor-draft-backup.spec.tsx`(8 例:节流后读到实时文本、FIFO 上限、超大草稿跳过、与磁盘相同即丢弃、恢复后保存的是草稿、拒绝恢复时打开磁盘内容、无草稿不提示、原生关闭钩子立即落盘);`tests/editor-unsaved-guard.spec.tsx` 追加 2 例(确认丢弃同时删备份、`beforeunload` 先落盘再拦截)。
- ⚠️ 宿主侧仍缺:Electron 桌面壳没有 `will-prevent-unload` 对话框,也没有退出前可取消钩子;真正的「保存 / 丢弃 / 取消」需要宿主补能力,届时再接 `confirmDiscardDraft` 并删除这条降级路径。
- 📐 **页面 CSS zoom 不再被误判成页面级 transform**([#1102](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1102);贡献者 PR [#1110](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1110) @HootRock):`body { zoom: 1.15 }` 下 panel host 的 `100vh` 按 zoom 放大(811px 视口 → 约 932.6px),几何自检因此判定「页面被 transform」→ 降级成 absolute、把文档撑高,聚焦 / 滚动会把整个外壳一起推走。现在预期高度按祖先链累积的 `zoom` 归一,宽度与位移仍按原阈值判定,真实 transform 不会被掩盖。
- 🧪 测试:`tests/e2e/panel-host-zoom.e2e.ts`(Chromium 实测 `body { zoom: 1.15 }` 下不再降级)。
- 🎛 **Changes 的「Git / 本轮文件」切换改用公开组件**([#1098](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1098);贡献者 PR [#1101](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1101) @wang-kaopu):此前自己画一套按钮、还依赖宿主私有 CSS Modules 的哈希类名,宿主一改样式就退化成浏览器原生按钮(方框 + 1px 黑边)。现在改用 `dsh-client-ui-primitives` 公开导出的 `SegmentedControl`,私有类名依赖一并删除。
+4
View File
@@ -6,6 +6,10 @@
### Unreleased
- 🛟 **The native tab close and Desktop Cmd+Q no longer discard editor drafts silently** ([#1072](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1072), [#1071](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1071)): the host's right-column tab strip (× / middle click / context menu / `page.close`) and the Desktop shell's quit expose no confirmable close hook — `registerCloseHandler` is a synchronous cleanup whose only veto is a throw, and Desktop Cmd+Q runs through the shell's own `before-quit` → `app.exitRequested` where the page sees no cancellable event (see [host contracts §C](docs/host-contracts.md)). The editor now throttles the **live document** into `localStorage` (key = `sessionId::path`; 200k characters per draft, 600k total, 8 drafts, FIFO), flushes it in the native close handler and in `beforeunload`, and offers "An unsaved draft was found. Restore it?" when the same file is reopened. Saving, confirming a discard, and confirming a reload / in-place switch drop the backup.
- 🧪 Tests: new `tests/editor-draft-backup.spec.tsx` (8 cases) and two new cases in `tests/editor-unsaved-guard.spec.tsx`.
- ⚠️ Host gap: the Electron desktop shell has no `will-prevent-unload` dialog and no cancellable quit hook, so a real save / discard / cancel flow needs a host capability; the guard would then call `confirmDiscardDraft` and this fallback path could go away.
- 📐 **Page CSS zoom is no longer mistaken for a page-level transform** ([#1102](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1102), PR [#1110](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1110)): with `body { zoom: 1.15 }` the panel host's `100vh` resolved to ~932.6px in an 811px viewport, so the geometry self-check switched the host to absolute positioning and grew the document. The expected height now folds the ancestor `zoom` chain while width and offsets keep their thresholds, so a real page transform is still caught.
- 🎛 **The Changes lens switcher uses the public `SegmentedControl`** ([#1098](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1098), PR [#1101](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1101)): it previously painted its own buttons on top of host-private CSS-module hash names and degraded to native browser buttons whenever the host restyled. The private-class dependency is gone.
- 🗂 **A container workspace now shows and switches every child repository**: `git.status` has always reported every discovered root in `repositories`, but the Git panel only listed them in the "More actions → Repository" submenu — no name and no count at the top of the panel, and the body rendered `repositories[0]`, so a workspace holding three projects looked like it had one. When more than one root is discovered, a chip row (`data-scm-repos`, one `[data-scm-repo]` per root) now renders above the Changes section with the current checkout marked `[data-active="true"]`; clicking a chip goes through the existing `chooseRepo`, so reads, mutations and the commit graph stay pinned to the chosen root. A single-repository workspace renders no row, and the existing menu entry stays.
+8
View File
@@ -46,3 +46,11 @@
**插件展示元数据**(Plugins 页与 `plugin_manager` 列表,v0.21.1 起已采纳)三条硬规则:`package.json#icon` 必须是**包内相对路径**且写进 `files`(36×36、纯填充无描边、**双色渐变**——与 DSH 自带 `PluginArtwork*` 同风格,单色版在 30px 行内尺寸下会读成一块纯色板);`locale/en.json` 是发现基线(缺它整个目录都不读,`meta.title` / `description` 在这里);`exports` 必须暴露 `./locale/*.json` 与 `./package.json`。**所有失败都是静默的**——元数据有问题只会退化成一行纯文字,没有任何报错;`tests/plugin-meta.spec.ts` 守护「声明了就必须发布出去」。plugin-manager 侧另有**多 registry 回退**(配置源 → `fallbackRegistries`,默认含 `registry.npmmirror.com`;`network`/`timeout`/`not-found`/`no-matching-version` 会自动问下一个源;`registry` 入参只存在于 Web 对话框与 `plugin_manager` 工具,**CLI 没有 registry flag**)。
12. **宿主版本兼容性是启动期硬约束**:当前宿主先读插件 `package.json#engines.dsh`;字段存在时只按该范围判定,DSH peer 不再拓宽或收窄结果。字段缺席时回退检查名字为 `@deepseek-ai/dsh` 或以 `@deepseek-ai/dsh-` 开头的 peer,按 `semver.satisfies(宿主版本, range, { includePrerelease: true })` 判定。本插件刻意不新增该字段,仍由 14 条 DSH peer 的 `^0.2.1-rc.1` 支持线约束,optional peer 没有豁免。`engines` 非对象或 `engines.dsh` 非字符串会导致兼容性清单不可读并拒绝加载;`workspace:` 仅在 peer 中有效。安装与 profile 启动拒绝可能禁用整行,需读 `disabling profile plugin` 日志;拒绝记录字段已由 `peers` 改为 `requirements`,其中 key 为 `engines.dsh` 或回退检查的 peer 包名。`pnpm peers check` 校验的是 dev 依赖树,不能证明宿主启动预检通过。[官方升级指南](https://github.com/deepseek-ai/deepseek-harness/blob/dsh-v0.2.1-alpha.5/docs/upgrade-guide/v0.2.1-alpha.3/plugin-engines-dsh/guide.md)。
13. **会话地址的基准是会话 header cwd,相对路径不得中途换基准(#947 / #950;同族 #952)**:`dsh-resource://file/session/<sid>/<path>` 的相对路径,宿主构造端(`ui-chat` 的 `fileAddressFor(sessionId, sessions.list.byId[sid].cwd, path)`)与解析端(`api-workspace-files` → `sessions.get(sid).header.cwd`)都取会话存储的 header cwd;插件自 #802 起让 fs 路由跟随**活动 worktree 根**,两者在「会话 header cwd 是主检出、agent 在 linked worktree 里干活」时不同 → 地址路径被活动根**再拼一次**:翻倍 ENOENT(#947),或静默读到另一检出的同名文件(#950,可保存写回、更危险)。规则:**构造端**(`native/surface.ts` 的 `fileAddress`、`sidebar-file.ts` 的 `openClaimedNativeFile`)与**消费端**(`fileParamsOf(info, base)`)都经 `src/client/address-base.ts` 的 `addressBaseOf(ctx, sessionId)` 取基准,并在消费边界把地址路径解析成**绝对路径**(绝对路径在任何基准下都一样);只有用户/插件**意图**的相对路径(文件树、路径输入框、文档内链接、`openSidebarFile` 的 `options.cwd`)才走活动根(`useSessionRoot`)。同族第二处是**采纳判定**:工作区**内部**的 linked worktree 只有属于**同一仓库**(`--git-common-dir` 相等)才算「会话搬走了」,嵌套仓库(含 bare 仓库的 main/local 检出)的 worktree 不再抢根(#952)。判定与基准都按**新增可选入参**向前兼容:`activeWorktreeRootOf` 多一个 `ignorePin` 选项(给「显式根」的读取路径用,见 `src/session-root.ts`),既有调用方零改动。回归 `tests/worktree-address.spec.ts` / `tests/active-worktree.spec.ts`;设计与实测见 [docs/plans/2026-10-14-worktree-root-and-address-base.md](plans/2026-10-14-worktree-root-and-address-base.md)。
## C. 未保存草稿与宿主关闭路径(#1072 / #1071,2026-11-04)
- **宿主没有「关闭前可确认」的钩子**。`@deepseek-ai/dsh-client-ui-sidebar-right` 0.2.1-rc.1 的 `SidebarRightTabDefinition`(`lib/types/client/tab-registry.d.ts`)是纯静态的类型描述,没有 `onClose` / `beforeClose`;唯一的前置回调是 `ctx.sidebarRight.registerCloseHandler(kind, handler)`(`lib/types/client/service.d.ts` 的 `SidebarRightCloseHandler`),契约是「同步清理,失败则保留页签」,没有「用户取消」这一返回形态:要阻止关闭只能 `throw`。宿主自己的 terminal tab 就只用它做资源清理(`dsh-client-ui-sidebar-terminal/lib/client.js`)。
- 显式关闭(页签条 × / 中键 / 上下文菜单 / `page.close` / `replaceTab`)都汇到 `lib/client.js` 的 `removeAfterCleanup`,但异常只在 seat 的 `closeTab` 里被捕获并打印 `Sidebar tab close failed:`;`replaceTab` 与公共 `ctx.sidebarRight.close()` **没有捕获**,用异常冒充「用户取消」会把错误抛进无关调用方。故插件不把它当确认通道,只当 flush 点。
- **桌面壳的 Cmd+Q 在页面之外**。macOS Desktop(`DSH Tauri.app`,内置 Electron 44.7.0)的主进程 `Contents/Resources/runtime/darwin-arm64/main.cjs` 订阅了 `app.on('before-quit')`:`preventDefault()` 后经 IPC 发 `app.exitRequested`,由壳自行完成退出;页面拿不到可取消的 quit 事件。壳内**没有** `will-prevent-unload` 处理(runtime 目录与壳可执行文件 grep 0 命中),因此若关闭最终走 `webContents.close()`,Electron 对 `beforeunload` 返回值的默认语义是**静默取消关闭**——这是 #1071「有脏草稿时 Cmd+Q 偶发退不掉、也没有确认框」的合理机制,但尚无 instrumentation 证据,不当作已证实根因。插件无法区分「被静默取消」与「页面成功拦截」,因此**不移除** `Sidebar.tsx` 的 `beforeunload`(浏览器刷新仍需要它);该 guard 现在会先 flush 草稿备份再拦截。
- **插件侧结论**:不伪造拦截,改为**降低损失**——`src/client/editor-draft-backup.ts` 在草稿变脏时按 1 s 节流写 `localStorage`(key = `sessionId::path`;单条 200k 字符、总计 600k 字符、最多 8 条、FIFO 淘汰),并在原生 `registerCloseHandler('editor')` 与 `beforeunload` 里立即 flush;重开同一文件由 `TextEditor` 提示恢复。保存成功、确认丢弃、确认刷新 / 就地换文件都会删除对应备份。
- **宿主若补上能力**:`will-prevent-unload` 对话框(Electron 主进程)或退出前可取消钩子,就能做真正的「保存 / 丢弃 / 取消」。届时在 `Sidebar.tsx` 的 `beforeunload` 与 `native/index.ts` 的关闭回调处接入 `confirmDiscardDraft`,再删掉这条降级路径。
+10 -2
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 { clearDraftBackup } from './editor-draft-backup.ts'
import { clearEditorDirty, isEditorDirty, setEditorDirty } from './editor-dirty.ts'
import { baseName } from './FileTree.tsx'
import { createFrameBatcher } from './frame-batcher.ts'
@@ -223,6 +224,9 @@ export function EditorHost(props: {
// reload (the editor instance remounts), so confirm before discarding it.
const refreshFile = (): void => {
if (toolbar?.dirty === true && !confirmDiscard(t('refreshUnsavedConfirm'))) return
// The confirmed reload discards the live draft: its durable backup must
// not offer the discarded bytes back on the next open.
if (toolbar?.dirty === true) clearDraftBackup(scope.sessionId, path)
setReloadSeq(sequence => sequence + 1)
}
@@ -293,8 +297,12 @@ export function EditorHost(props: {
// that instance — ask before dropping it, reading the same dirty
// registry the tab close uses. Re-opening the current path is not a
// switch.
if (absolute !== path && isEditorDirty(tab.id, scope.sessionId)
&& !confirmDiscard(t('switchUnsavedConfirm'))) return
if (absolute !== path && isEditorDirty(tab.id, scope.sessionId)) {
if (!confirmDiscard(t('switchUnsavedConfirm'))) return
// The confirmed switch discards the live draft: drop its durable
// backup too, or the next open would offer the discarded bytes back.
clearDraftBackup(scope.sessionId, path)
}
ctx.get('betterSidebar')?.updateTab(tab.id, { path: absolute, title: baseName(absolute) }, scope.sessionId)
} else {
openSidebarFile(ctx, scope.sessionId, absolute, { cwd: scope.cwd })
+6
View File
@@ -43,6 +43,7 @@ import { Workbench, type WorkbenchActions } from './split-pane.tsx'
import { useViewportSize } from './breakpoints.ts'
import { bottomPushHeight } from './layout-push.ts'
import { TabContent, buildNewTabOptions } from './sidebar/TabContent.tsx'
import { flushDraftBackups } from './editor-draft-backup.ts'
import { confirmDiscardDraft, dirtyCount, editorDirtyRevision, subscribeEditorDirty } from './editor-dirty.ts'
import { createOpenInApp } from './open-in-app.ts'
import { useCenterColumn } from './sidebar/use-center-column.ts'
@@ -231,6 +232,11 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) {
useEffect(() => {
const onBeforeUnload = (event: BeforeUnloadEvent): void => {
if (dirtyCount() === 0) return
// Persist the latest drafts before the page may go away: the Desktop
// shell's quit is shell-owned and can complete without ever rendering
// this guard's prompt (docs/host-contracts.md), so the durable copy is
// the only record of the draft left.
flushDraftBackups()
event.preventDefault()
event.returnValue = ''
}
+38 -1
View File
@@ -36,6 +36,7 @@ import { rewriteLocalMarkdownLinks } from './markdown-navigation.ts'
import { languageForPath } from './lang.ts'
import { cmSurfaceTheme, CmThemeCompartment } from './cm-themes.ts'
import { cmSearchExtensions, CmSearchPhrases } from './cm-search.ts'
import { clearDraftBackup, flushDraftBackups, readDraftBackup, registerDraftSource, scheduleDraftBackup } from './editor-draft-backup.ts'
import { flashQuoteLines, quoteFlashField, quoteFlashHighlight } from './quote-flash.ts'
import { isDarkScheme, subscribeColorScheme } from './theme.ts'
import { SandboxStatusBar } from './SandboxStatusBar.tsx'
@@ -357,6 +358,25 @@ export function TextEditor(props: FileViewerProps) {
editScrollRef.current = editScrollOf(scope, path)
}, [scope, path])
/**
* Offer this file's durable backup back to the reader (see
* editor-draft-backup.ts): the native tab strip's × and the Desktop shell's
* quit can drop the tab without a prompt, so the draft is kept in storage.
* Declining drops it; accepting makes it the live draft, which the normal
* dirty path then owns.
*/
const restoreDraftBackup = (): string | null => {
if (content === undefined) return null
const backup = readDraftBackup(scope.sessionId, path, content)
if (backup === null) return null
const confirmed = typeof window.confirm === 'function' ? window.confirm(t('draftRestoreConfirm')) : false
if (!confirmed) {
clearDraftBackup(scope.sessionId, path)
return null
}
return backup
}
// Create the CodeMirror editor once the content is loaded. The view owns
// the document; React only tracks dirty state through the update listener
// (the draft — the preview's text — is snapshotted from the live view on
@@ -376,8 +396,9 @@ export function TextEditor(props: FileViewerProps) {
searchPhrasesRef.current = searchPhrases
const gitComp = new CmGitGutterCompartment()
gitCompRef.current = gitComp
const restored = restoreDraftBackup()
const state = EditorState.create({
doc: content,
doc: restored ?? content,
extensions: [
CodeMirrorView.lineWrapping,
// The change bar sits BEFORE the line numbers (VS Code's own order):
@@ -406,6 +427,7 @@ export function TextEditor(props: FileViewerProps) {
CodeMirrorView.updateListener.of((update) => {
if (update.docChanged) {
setDirty(true)
scheduleDraftBackup(scope.sessionId, path)
}
}),
keymap.of([
@@ -465,6 +487,14 @@ export function TextEditor(props: FileViewerProps) {
})
const view = new CodeMirrorView({ state, parent: host })
viewRef.current = view
const releaseDraft = registerDraftSource(scope.sessionId, path, () => viewRef.current?.state.doc.toString() ?? null)
if (restored !== null) {
setDirty(true)
setDraft(restored)
// Re-persist the adopted draft from the live document: the entry must
// not disappear just because the app quits before the next edit.
scheduleDraftBackup(scope.sessionId, path)
}
// Edit-mode scroll memory. The native sidebar re-seats a tab while it is
// being saved (the chip's dirty mark, the change gutter), and a scroller
// that is detached from the document comes back with `scrollTop` 0 — the
@@ -479,6 +509,10 @@ export function TextEditor(props: FileViewerProps) {
scroller.addEventListener('scroll', onScroll, { passive: true })
return () => {
scroller.removeEventListener('scroll', onScroll)
// The throttled entry may still be pending: write it while this view
// (the only reader of its text) is still alive.
flushDraftBackups()
releaseDraft()
view.destroy()
viewRef.current = null
themeCompRef.current = null
@@ -788,6 +822,9 @@ export function TextEditor(props: FileViewerProps) {
setDirty(false)
setConflict(false)
setSaveState('saved')
// Saved: nothing is unsaved any more, so the durable backup must not
// offer itself back on the next open.
clearDraftBackup(scope.sessionId, path)
// The saved bytes are a new revision of the uncommitted diff: re-read
// the change set (the file's XY status code usually stays the same, so
// the status store alone would never wake the gutter up again).
+23 -6
View File
@@ -9,6 +9,10 @@
* - the browser unload (refresh / close tab / navigate away) through a
* `beforeunload` guard.
*
* A confirmed discard also drops the file's durable draft backup
* (`editor-draft-backup.ts`): that backup is the same draft and must not be
* offered back on the next open.
*
* Module-level and keyed by `sessionId::tabId`: a tab id is unique only WITHIN
* one session — the native right column counts its own `tab1`…, and the bottom
* workbench reuses `editor:<path>` for the same file in every session. Keyed by
@@ -21,9 +25,12 @@
* stale entry can never keep a guard armed.
*/
/** One registered draft: the id it was recorded under and the file. */
import { clearDraftBackup } from './editor-draft-backup.ts'
/** One registered draft: the id it was recorded under, its session, and the file. */
interface DirtyEntry {
tabId: string
sessionId: string
path: string
}
@@ -55,7 +62,7 @@ export function setEditorDirty(tabId: string, dirty: boolean, sessionId: string,
}
const previous = dirtyTabs.get(key)
if (previous !== undefined && previous.path === path) return
dirtyTabs.set(key, { tabId, path })
dirtyTabs.set(key, { tabId, sessionId, path })
notify()
}
@@ -118,13 +125,23 @@ export function editorDirtyRevision(): number {
* 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.
* both paths warn exactly once, with the same copy, and drop the durable
* backup of every discarded draft.
* @param sessionId - the owning session (see {@link isEditorDirty} for the
* omitted case).
*/
export function confirmDiscardDraft(tabId: string, message: string, sessionId?: string): boolean {
if (!isEditorDirty(tabId, sessionId)) return true
const matches = [...dirtyTabs.entries()].filter(([key, entry]) =>
entry.tabId === tabId && (sessionId === undefined || key === keyOf(sessionId, tabId)))
if (matches.length === 0) return true
const confirmed = typeof window.confirm === 'function' ? window.confirm(message) : true
if (confirmed) clearEditorDirty(tabId, sessionId)
return confirmed
if (!confirmed) return false
for (const [key, entry] of matches) {
dirtyTabs.delete(key)
// The durable backup is the same draft: a confirmed discard must not be
// offered back on the next open.
clearDraftBackup(entry.sessionId, entry.path)
}
notify()
return true
}
+224
View File
@@ -0,0 +1,224 @@
/**
* Durable backups of unsaved editor drafts.
*
* Why this exists: the two host-owned paths that can take an editor tab away
* without asking are not interceptable with a confirmation.
*
* - The native right column's tab strip (its × / middle click / context menu /
* page.close) runs `ctx.sidebarRight.registerCloseHandler` before removing
* the record, but that hook is a synchronous CLEANUP callback
* ("Failure preserves the tab"), not a confirmation channel: vetoing means
* throwing, which the host logs as "Sidebar tab close failed:" and which
* escapes from `replaceTab` and the public `close()` callers. It may flush a
* draft, never ask.
* - The Desktop shell quits on its own (Electron main intercepts `before-quit`
* and the page receives no cancellable quit event), so Cmd+Q cannot show a
* page-level prompt either.
*
* The remaining protection is to keep the draft somewhere that survives both:
* a small localStorage entry keyed by `sessionId::path`, offered back when the
* same file is opened again (TextEditor shows the restore prompt).
*
* Cost rules (steady-state):
* - Writing is a single trailing throttle armed only by an edit and disarmed
* by the flush; idle tabs hold no timer and no polling is added.
* - At most {@link DRAFT_BACKUP_LIMIT} drafts and {@link DRAFT_BACKUP_TOTAL_CHARS}
* characters live in storage; the oldest entry is evicted first (FIFO).
* - A draft larger than {@link DRAFT_BACKUP_CHARS} is not stored at all (a
* single entry would evict the whole budget).
* - An entry is deleted the moment its draft stops being unsaved (save, or a
* confirmed discard) and when the throttle is cleared.
*/
/** localStorage prefix; every key under it is one of our drafts. */
const STORAGE_PREFIX = 'dsh-better-sidebar:draft:'
/** How many drafts are kept (oldest evicted first). */
export const DRAFT_BACKUP_LIMIT = 8
/** Longest draft persisted, in characters; bigger drafts are skipped. */
export const DRAFT_BACKUP_CHARS = 200_000
/** Total characters across all kept drafts. */
export const DRAFT_BACKUP_TOTAL_CHARS = 600_000
/** Delay after an edit before the draft is written. */
export const DRAFT_BACKUP_THROTTLE_MS = 1000
/** How many live editor sources are remembered (open editor bodies). */
const SOURCE_LIMIT = 32
/** What one stored entry carries. */
interface StoredDraft {
text: string
/** Write time; the FIFO order for eviction. */
savedAt: number
}
/**
* One mounted editor's live text reader, keyed by `sessionId::path`.
* Reading at flush time (rather than per keystroke) keeps the backup free of
* the O(document) stringification the editor deliberately avoids on every key.
*/
const sources = new Map<string, () => string | null>()
/** Keys whose draft changed since the last write. */
const pending = new Set<string>()
let timer: ReturnType<typeof setTimeout> | null = null
/** The map/storage key of one draft: ids and paths only mean something in a session. */
function keyOf(sessionId: string, path: string): string {
return `${sessionId}::${path}`
}
/** localStorage, when this runtime has it (specs, SSR). */
function storage(): Storage | undefined {
try {
return typeof localStorage === 'undefined' ? undefined : localStorage
} catch {
return undefined
}
}
/** One stored entry; malformed values are treated as absent. */
function readStored(key: string): StoredDraft | undefined {
const store = storage()
const raw = store?.getItem(STORAGE_PREFIX + key)
if (raw === undefined || raw === null) return undefined
try {
const parsed: unknown = JSON.parse(raw)
if (typeof parsed !== 'object' || parsed === null) return undefined
const { text, savedAt } = parsed as { text?: unknown; savedAt?: unknown }
if (typeof text !== 'string' || typeof savedAt !== 'number') return undefined
return { text, savedAt }
} catch {
return undefined
}
}
/** Every stored key with its timestamp, oldest first. */
function storedDrafts(store: Storage): Array<{ key: string; savedAt: number; chars: number }> {
const entries: Array<{ key: string; savedAt: number; chars: number }> = []
for (let index = 0; index < store.length; index += 1) {
const key = store.key(index)
if (key === null || !key.startsWith(STORAGE_PREFIX)) continue
const bare = key.slice(STORAGE_PREFIX.length)
const entry = readStored(bare)
entries.push({ key, savedAt: entry?.savedAt ?? 0, chars: entry?.text.length ?? 0 })
}
return entries.sort((left, right) => left.savedAt - right.savedAt)
}
/** Evict the oldest entries until both budgets hold. */
function evict(store: Storage): void {
const entries = storedDrafts(store)
let chars = entries.reduce((sum, entry) => sum + entry.chars, 0)
while (entries.length > 0 && (entries.length > DRAFT_BACKUP_LIMIT || chars > DRAFT_BACKUP_TOTAL_CHARS)) {
const oldest = entries.shift()
if (oldest === undefined) break
store.removeItem(oldest.key)
chars -= oldest.chars
}
}
/** Persist one draft, dropping older ones when storage is full. */
function writeDraft(key: string, text: string): void {
const store = storage()
if (store === undefined) return
if (text.length === 0 || text.length > DRAFT_BACKUP_CHARS) return
const previous = readStored(key)
// An unchanged draft keeps its original timestamp (and therefore its place
// in the FIFO order), so a restore that is re-persisted does not look new.
if (previous?.text === text) return
const payload = JSON.stringify({ text, savedAt: Date.now() } satisfies StoredDraft)
try {
store.setItem(STORAGE_PREFIX + key, payload)
} catch {
// Quota exceeded: make room by dropping every older draft, then retry once.
const older = storedDrafts(store).filter(entry => entry.key !== STORAGE_PREFIX + key)
for (const entry of older) store.removeItem(entry.key)
try {
store.setItem(STORAGE_PREFIX + key, payload)
} catch {
return
}
}
evict(store)
}
/** Write every pending draft now (the close / unload flush). */
export function flushDraftBackups(): void {
if (timer !== null) {
clearTimeout(timer)
timer = null
}
const keys = [...pending]
pending.clear()
for (const key of keys) {
const text = sources.get(key)?.()
if (text !== null && text !== undefined) writeDraft(key, text)
}
}
/**
* Remember one mounted editor's live text and return its disposer.
*
* The reader runs at flush time and must answer `null` once its editor is
* gone, so a flush after an unmount can never write a destroyed view's text.
* @param sessionId - the session owning the tab.
* @param path - the file the draft belongs to.
* @param read - the live document's text, or null.
* @returns the disposer (idempotent; a newer source for the same file wins).
*/
export function registerDraftSource(sessionId: string, path: string, read: () => string | null): () => void {
const key = keyOf(sessionId, path)
sources.set(key, read)
if (sources.size > SOURCE_LIMIT) {
const oldest = sources.keys().next().value
if (oldest !== undefined && oldest !== key) sources.delete(oldest)
}
return () => {
if (sources.get(key) === read) sources.delete(key)
}
}
/**
* Mark one draft as changed; a single shared throttle writes the pending set
* once {@link DRAFT_BACKUP_THROTTLE_MS} has passed since the first change.
* @param sessionId - the session owning the tab.
* @param path - the file the draft belongs to.
*/
export function scheduleDraftBackup(sessionId: string, path: string): void {
const key = keyOf(sessionId, path)
if (!sources.has(key)) return
pending.add(key)
if (timer !== null) return
timer = setTimeout(() => {
timer = null
flushDraftBackups()
}, DRAFT_BACKUP_THROTTLE_MS)
}
/**
* The pending draft of one file, if its content differs from the bytes on
* disk; otherwise the stale entry is dropped.
* @param sessionId - the session owning the tab.
* @param path - the file the draft belongs to.
* @param content - the bytes just loaded from disk.
* @returns the stored text, or null.
*/
export function readDraftBackup(sessionId: string, path: string, content: string): string | null {
const entry = readStored(keyOf(sessionId, path))
if (entry === undefined) return null
if (entry.text === content) {
clearDraftBackup(sessionId, path)
return null
}
return entry.text
}
/** Drop one file's backup (saved, discarded, or restored). Idempotent. */
export function clearDraftBackup(sessionId: string, path: string): void {
const key = keyOf(sessionId, path)
pending.delete(key)
storage()?.removeItem(STORAGE_PREFIX + key)
}
+1
View File
@@ -159,6 +159,7 @@ export const ar: Record<string, string> = {
showInFolder: 'إظهار في المجلد',
refreshUnsavedConfirm: 'تغيّر الملف على القرص. سيؤدي التحديث إلى فقدان التعديلات غير المحفوظة. متابعة؟',
closeUnsavedConfirm: 'يحتوي هذا الملف على تعديلات غير محفوظة. سيؤدي إغلاق علامة التبويب إلى تجاهلها. المتابعة؟',
draftRestoreConfirm: 'تم العثور على مسودة غير محفوظة. هل تريد استعادتها؟ (الإلغاء يهمل المسودة.)',
switchUnsavedConfirm: 'يحتوي هذا الملف على تعديلات غير محفوظة. سيؤدي تبديل الملف إلى تجاهلها. المتابعة؟',
save: 'حفظ',
saved: 'تم الحفظ',
+1
View File
@@ -144,6 +144,7 @@ export const de: Record<string, string> = {
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?',
draftRestoreConfirm: 'Es wurde ein ungespeicherter Entwurf gefunden. Wiederherstellen? (Abbrechen verwirft den Entwurf.)',
switchUnsavedConfirm: 'Diese Datei hat ungespeicherte Änderungen. Beim Wechseln der Datei gehen sie verloren. Fortfahren?',
save: 'Speichern',
saved: 'Gespeichert',
+1
View File
@@ -151,6 +151,7 @@ export const fr: Record<string, string> = {
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 ?',
draftRestoreConfirm: 'Un brouillon non enregistré a été trouvé. Le restaurer ? (Annuler le supprime.)',
switchUnsavedConfirm: 'Ce fichier contient des modifications non enregistrées. Changer de fichier les perdra. Continuer ?',
save: 'Enregistrer',
saved: 'Enregistré',
+1
View File
@@ -158,6 +158,7 @@ export const hi: Record<string, string> = {
showInFolder: 'फ़ोल्डर में दिखाएँ',
refreshUnsavedConfirm: 'डिस्क पर फ़ाइल बदल गई है। रीफ़्रेश करने पर असहेज किए गए संपादन खो जाएँगे। जारी रखें?',
closeUnsavedConfirm: 'इस फ़ाइल में सहेजे नहीं गए संपादन हैं। टैब बंद करने पर वे हट जाएँगे। जारी रखें?',
draftRestoreConfirm: 'एक असहेजा ड्राफ़्ट मिला। इसे पुनर्स्थापित करें? (रद्द करने पर ड्राफ़्ट हट जाएगा।)',
switchUnsavedConfirm: 'इस फ़ाइल में सहेजे नहीं गए संपादन हैं। फ़ाइल बदलने पर वे हट जाएँगे। जारी रखें?',
save: 'सहेजें',
saved: 'सहेजा गया',
+1
View File
@@ -156,6 +156,7 @@ export const id: Record<string, string> = {
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?',
draftRestoreConfirm: 'Draf yang belum disimpan ditemukan. Pulihkan? (Batal akan membuang draf.)',
switchUnsavedConfirm: 'File ini memiliki edit yang belum disimpan. Mengganti file akan membuangnya. Lanjutkan?',
save: 'Simpan',
saved: 'Tersimpan',
+1
View File
@@ -149,6 +149,7 @@ export const it: Record<string, string> = {
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?',
draftRestoreConfirm: 'Trovata una bozza non salvata. Ripristinarla? (Annulla la scarta.)',
switchUnsavedConfirm: 'Questo file ha modifiche non salvate. Cambiare file le perderà. Continuare?',
save: 'Salva',
saved: 'Salvato',
+1
View File
@@ -158,6 +158,7 @@ export const ja: Record<string, string> = {
showInFolder: 'フォルダーで表示',
refreshUnsavedConfirm: 'ディスク上のファイルが変更されました。更新すると未保存の編集が失われます。続行しますか?',
closeUnsavedConfirm: 'このファイルには未保存の編集があります。タブを閉じると破棄されます。続行しますか?',
draftRestoreConfirm: '未保存の下書きが見つかりました。復元しますか?(キャンセルすると破棄されます)',
switchUnsavedConfirm: 'このファイルには未保存の編集があります。ファイルを切り替えると破棄されます。続行しますか?',
save: '保存',
saved: '保存済み',
+1
View File
@@ -150,6 +150,7 @@ export const ko: Record<string, string> = {
showInFolder: '폴더에서 표시',
refreshUnsavedConfirm: '디스크의 파일이 변경되었습니다. 새로고침하면 저장되지 않은 편집 내용이 손실됩니다. 계속하시겠습니까?',
closeUnsavedConfirm: '이 파일에 저장되지 않은 편집이 있습니다. 탭을 닫으면 삭제됩니다. 계속하시겠습니까?',
draftRestoreConfirm: '저장되지 않은 초안이 있습니다. 복원할까요? (취소하면 초안이 삭제됩니다.)',
switchUnsavedConfirm: '이 파일에 저장되지 않은 편집이 있습니다. 파일을 전환하면 삭제됩니다. 계속하시겠습니까?',
save: '저장',
saved: '저장됨',
+1
View File
@@ -156,6 +156,7 @@ export const nl: Record<string, string> = {
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?',
draftRestoreConfirm: 'Er is een niet-opgeslagen concept gevonden. Herstellen? (Annuleren verwijdert het concept.)',
switchUnsavedConfirm: 'Dit bestand heeft niet-opgeslagen wijzigingen. Het wisselen van bestand gooit ze weg. Doorgaan?',
save: 'Opslaan',
saved: 'Opgeslagen',
+1
View File
@@ -160,6 +160,7 @@ export const pl: Record<string, string> = {
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ć?',
draftRestoreConfirm: 'Znaleziono niezapisany szkic. Przywrócić? (Anulowanie go odrzuci.)',
switchUnsavedConfirm: 'Ten plik ma niezapisane zmiany. Przełączenie pliku je odrzuci. Kontynuować?',
save: 'Zapisz',
saved: 'Zapisano',
+1
View File
@@ -141,6 +141,7 @@ export const pt: Record<string, string> = {
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?',
draftRestoreConfirm: 'Foi encontrado um rascunho não salvo. Restaurar? (Cancelar descarta o rascunho.)',
switchUnsavedConfirm: 'Este arquivo tem edições não salvas. Trocar de arquivo irá descartá-las. Continuar?',
save: 'Salvar',
saved: 'Salvo',
+1
View File
@@ -154,6 +154,7 @@ export const ru: Record<string, string> = {
showInFolder: 'Показать в папке',
refreshUnsavedConfirm: 'Файл изменился на диске. Обновление отбросит несохранённые изменения. Продолжить?',
closeUnsavedConfirm: 'В файле есть несохранённые изменения. Закрытие вкладки их отменит. Продолжить?',
draftRestoreConfirm: 'Найден несохранённый черновик. Восстановить? (Отмена отбросит черновик.)',
switchUnsavedConfirm: 'В файле есть несохранённые изменения. При переключении на другой файл они будут отброшены. Продолжить?',
save: 'Сохранить',
saved: 'Сохранено',
+1
View File
@@ -141,6 +141,7 @@ export const sv: Record<string, string> = {
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?',
draftRestoreConfirm: 'Ett osparat utkast hittades. Återställa? (Avbryt kastar utkastet.)',
switchUnsavedConfirm: 'Filen har osparade ändringar. Att byta fil kastar dem. Fortsätta?',
save: 'Spara',
saved: 'Sparad',
+1
View File
@@ -158,6 +158,7 @@ export const th: Record<string, string> = {
showInFolder: 'แสดงในโฟลเดอร์',
refreshUnsavedConfirm: 'ไฟล์เปลี่ยนบนดิสก์ การรีเฟรชจะทิ้งการแก้ไขที่ยังไม่ได้บันทึก ดำเนินการต่อหรือไม่',
closeUnsavedConfirm: 'ไฟล์นี้มีการแก้ไขที่ยังไม่ได้บันทึก การปิดแท็บจะทิ้งการแก้ไขนั้น ดำเนินการต่อหรือไม่',
draftRestoreConfirm: 'พบฉบับร่างที่ยังไม่ได้บันทึก จะกู้คืนหรือไม่? (ยกเลิกจะทิ้งฉบับร่าง)',
switchUnsavedConfirm: 'ไฟล์นี้มีการแก้ไขที่ยังไม่ได้บันทึก การสลับไฟล์จะทิ้งการแก้ไขนั้น ดำเนินการต่อหรือไม่',
save: 'บันทึก',
saved: 'บันทึกแล้ว',
+1
View File
@@ -158,6 +158,7 @@ export const tr: Record<string, string> = {
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?',
draftRestoreConfirm: 'Kaydedilmemiş bir taslak bulundu. Geri yüklensin mi? (İptal taslağı atar.)',
switchUnsavedConfirm: 'Bu dosyada kaydedilmemiş değişiklikler var. Dosya değiştirmek bunları atacak. Devam edilsin mi?',
save: 'Kaydet',
saved: 'Kaydedildi',
+1
View File
@@ -158,6 +158,7 @@ export const vi: Record<string, string> = {
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?',
draftRestoreConfirm: 'Đã tìm thấy bản nháp chưa lưu. Khôi phục? (Hủy sẽ bỏ bản nháp.)',
switchUnsavedConfirm: 'Tệp này có chỉnh sửa chưa lưu. Chuyển tệp sẽ loại bỏ chúng. Tiếp tục?',
save: 'Lưu',
saved: 'Đã lưu',
+1
View File
@@ -173,6 +173,7 @@ export const zhHK: Record<string, string> = {
showInFolder: '在文件夾中顯示',
refreshUnsavedConfirm: '檔案已在磁碟上變更。重新整理會丟失尚未儲存的編輯。繼續?',
closeUnsavedConfirm: '此檔案有未儲存的編輯,關閉後將被丟棄。繼續嗎?',
draftRestoreConfirm: '偵測到未儲存的草稿,要復原嗎?(選擇取消將捨棄該草稿)',
switchUnsavedConfirm: '此檔案有未儲存的編輯,切換檔案將丟棄這些內容。繼續嗎?',
save: '儲存',
saved: '已儲存',
+1
View File
@@ -173,6 +173,7 @@ export const zhMO: Record<string, string> = {
showInFolder: '在文件夾中顯示',
refreshUnsavedConfirm: '檔案已在磁碟上變更。重新整理會丟失尚未儲存的編輯。繼續?',
closeUnsavedConfirm: '此檔案有未儲存的編輯,關閉後將被丟棄。繼續嗎?',
draftRestoreConfirm: '偵測到未儲存的草稿,要復原嗎?(選擇取消將捨棄該草稿)',
switchUnsavedConfirm: '此檔案有未儲存的編輯,切換檔案將丟棄這些內容。繼續嗎?',
save: '儲存',
saved: '已儲存',
+1
View File
@@ -173,6 +173,7 @@ export const zhTW: Record<string, string> = {
showInFolder: '在資料夾中顯示',
refreshUnsavedConfirm: '檔案已在磁碟上變更。重新整理會丟失尚未儲存的編輯。繼續?',
closeUnsavedConfirm: '此檔案有未儲存的編輯,關閉後將被丟棄。繼續嗎?',
draftRestoreConfirm: '偵測到未儲存的草稿,要復原嗎?(選擇取消將捨棄該草稿)',
switchUnsavedConfirm: '此檔案有未儲存的編輯,切換檔案將丟棄這些內容。繼續嗎?',
save: '儲存',
saved: '已儲存',
+2
View File
@@ -169,6 +169,7 @@ export const zh = {
refresh: '刷新',
refreshUnsavedConfirm: '文件已在磁盘更新,刷新将丢弃未保存编辑。继续吗?',
closeUnsavedConfirm: '该文件有未保存的编辑,关闭后将丢弃。继续吗?',
draftRestoreConfirm: '检测到未保存的草稿,恢复吗?(选择取消将丢弃该草稿)',
switchUnsavedConfirm: '该文件有未保存的编辑,切换文件将丢弃这些内容。继续吗?',
save: '保存',
saved: '已保存',
@@ -827,6 +828,7 @@ export const en: Record<keyof typeof zh, string> = {
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?',
draftRestoreConfirm: 'An unsaved draft was found. Restore it? (Cancel discards the draft.)',
switchUnsavedConfirm: 'This file has unsaved edits. Switching files will discard them. Continue?',
save: 'Save',
saved: 'Saved',
+32 -1
View File
@@ -24,6 +24,7 @@
*/
import type { Context } from '../../context-types.ts'
import { addressBaseOf, resolveAddressPath } from '../address-base.ts'
import { flushDraftBackups } from '../editor-draft-backup.ts'
import { t } from '../locales.ts'
import { splitTrailingLineSpec } from '../path-line.ts'
import { baseName } from '../paths.ts'
@@ -85,6 +86,16 @@ function hostOwnedPath(path: string): boolean {
return dot > 0 && HOST_OWNED_EXTS.has(name.slice(dot + 1).toLowerCase())
}
/**
* The close-hook slice of `ctx.sidebarRight`: `registerCloseHandler` lives on
* the concrete controller, not on `ISidebarRight`, so it is probed
* structurally (same shape the host's own terminal tab uses).
*/
interface CloseHandlerHost {
/** Run one kind's cleanup before its record is removed; a throw vetoes the close. */
registerCloseHandler(kind: string, handler: (sessionId: string, tab: { kind: string }) => void): () => void
}
/** The native tab-type registry face (`ctx.sidebarRightTabs`). */
interface NativeTabRegistry {
register(definition: {
@@ -283,11 +294,30 @@ export function registerNativeSurface(deps: NativeSurfaceDeps): () => void {
// `sidebarRightTabs` undefined, and the registry appeared a moment later.
// `ctx.inject` re-runs this body whenever the service appears/reappears,
// which is the lifecycle the registrations need.
const seat = ctx.inject(['sidebarRightTabs'], (injected) => {
//
// The close handler below needs `sidebarRight` as well; both services are
// provided by the same host package, so waiting for both changes nothing
// about WHEN the types register.
const seat = ctx.inject(['sidebarRightTabs', 'sidebarRight'], (injected) => {
const tabs = injected.get('sidebarRightTabs') as unknown as NativeTabRegistry | undefined
if (tabs === undefined) return
const right = injected.get('sidebarRight') as unknown as CloseHandlerHost | undefined
const live = new Map<string, Registration>()
// The host runs this hook before removing a record (the strip's ×, its
// context menu, `page.close`, and a `replaceTab`). Flush the throttled
// draft here so the keystrokes of the last second survive the body's
// unmount; the hook is a synchronous cleanup, not a veto, so it cannot
// ask first (see editor-draft-backup.ts).
let disposeClose: (() => void) | undefined
if (typeof right?.registerCloseHandler === 'function') {
try {
disposeClose = right.registerCloseHandler(EDITOR_KIND, () => { flushDraftBackups() })
} catch (error) {
reportFailure?.('register editor close handler', error)
}
}
const fileSessionIdOf = (info: NativeTabInfo): string | undefined => {
const address = parseFileAddress(info.tab.contentId)
return address !== undefined && address.scope === 'session' ? address.sessionId : undefined
@@ -528,6 +558,7 @@ export function registerNativeSurface(deps: NativeSurfaceDeps): () => void {
}
live.clear()
for (const dispose of disposeSubscriptions.reverse()) disposeSafely(dispose, 'a native tab subscription')
if (disposeClose !== undefined) disposeSafely(disposeClose, 'the editor close handler')
}
})
return () => {
+237
View File
@@ -0,0 +1,237 @@
/**
* Durable draft backups (src/client/editor-draft-backup.ts).
*
* The host-owned ways to lose an editor draft — the native right column's tab
* strip (its × / context menu / page.close) and the Desktop shell's quit —
* expose no confirmation hook (the close handler is a cleanup callback whose
* only veto is a throw, see docs/host-contracts.md). The plugin therefore keeps
* a throttled localStorage copy and offers it back when the file is reopened.
*
* These tests pin the behavior a user gets, not the implementation: the
* throttle delay, the FIFO budget, the restore prompt driving the REAL
* TextEditor (CodeMirror) document, and the host close hook flushing what the
* throttle has not written yet.
*/
// @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 { TextEditor } from '../src/client/TextEditor.tsx'
import { createSidebarStore } from '../src/client/state.ts'
import type { FileViewerProps } from '../src/client/service.ts'
import { createBetterSidebarService } from '../src/client/service.ts'
import { createNativeTabRecords } from '../src/client/native/tab-adapter.tsx'
import { registerNativeSurface } from '../src/client/native/index.ts'
import {
DRAFT_BACKUP_CHARS,
DRAFT_BACKUP_LIMIT,
DRAFT_BACKUP_THROTTLE_MS,
flushDraftBackups,
readDraftBackup,
registerDraftSource,
scheduleDraftBackup,
} from '../src/client/editor-draft-backup.ts'
setupReactAct()
const fsWrite = vi.fn()
vi.mock('../src/client/api.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/client/api.ts')>()
return {
...actual,
api: { ...actual.api, fsWrite: (...args: unknown[]) => fsWrite(...args) },
}
})
/** Write one draft through the public path (a live source + the throttle). */
function seedDraft(sessionId: string, path: string, text: string): void {
const release = registerDraftSource(sessionId, path, () => text)
scheduleDraftBackup(sessionId, path)
flushDraftBackups()
release()
}
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(() => {
localStorage.clear()
fsWrite.mockReset()
fsWrite.mockResolvedValue({ ok: true, mtimeMs: 456 })
})
afterEach(() => {
document.body.innerHTML = ''
vi.useRealTimers()
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
/** Every stored key under the module's prefix (the budget assertions). */
function storedKeys(): string[] {
const keys: string[] = []
for (let index = 0; index < localStorage.length; index += 1) {
const key = localStorage.key(index)
if (key !== null && key.startsWith('dsh-better-sidebar:draft:')) keys.push(key)
}
return keys
}
describe('editor-draft-backup store', () => {
it('writes a changed draft only after the throttle, and reads it back', () => {
vi.useFakeTimers()
let text = 'first edit'
const release = registerDraftSource('s1', '/p/a.ts', () => text)
try {
scheduleDraftBackup('s1', '/p/a.ts')
expect(readDraftBackup('s1', '/p/a.ts', 'disk'), 'nothing is written before the throttle').toBeNull()
text = 'second edit'
vi.advanceTimersByTime(DRAFT_BACKUP_THROTTLE_MS - 1)
expect(readDraftBackup('s1', '/p/a.ts', 'disk')).toBeNull()
vi.advanceTimersByTime(1)
// The flush reads the LIVE document, so the throttled write carries the
// latest text, not the text at schedule time.
expect(readDraftBackup('s1', '/p/a.ts', 'disk')).toBe('second edit')
} finally {
release()
}
})
it('keeps at most the configured number of drafts, evicting the oldest first', () => {
vi.useFakeTimers()
const total = DRAFT_BACKUP_LIMIT + 1
for (let index = 0; index < total; index += 1) {
seedDraft('s' + index, '/p/a.ts', 'draft ' + index)
vi.advanceTimersByTime(1)
}
expect(storedKeys()).toHaveLength(DRAFT_BACKUP_LIMIT)
expect(readDraftBackup('s0', '/p/a.ts', 'disk'), 'the oldest draft was evicted').toBeNull()
expect(readDraftBackup('s' + (total - 1), '/p/a.ts', 'disk'), 'the newest draft was kept').toBe('draft ' + (total - 1))
})
it('skips a draft larger than the per-entry budget instead of evicting the whole store', () => {
seedDraft('s1', '/p/big.ts', 'x'.repeat(DRAFT_BACKUP_CHARS + 1))
expect(readDraftBackup('s1', '/p/big.ts', 'disk')).toBeNull()
expect(storedKeys()).toHaveLength(0)
})
it('drops an entry that is identical to the bytes on disk (the edit was undone)', () => {
seedDraft('s1', '/p/a.ts', 'same as disk')
expect(readDraftBackup('s1', '/p/a.ts', 'same as disk')).toBeNull()
expect(storedKeys()).toHaveLength(0)
})
})
describe('TextEditor draft restore', () => {
it('offers a stored draft back and saves it as the document', async () => {
seedDraft('s1', '/p/a.ts', 'const restored = 2\n')
const confirmSpy = vi.fn().mockReturnValue(true)
vi.stubGlobal('confirm', confirmSpy)
const mounted = renderRoot(createElement(TextEditor, viewerProps()))
try {
expect(confirmSpy).toHaveBeenCalledTimes(1)
click(saveButton(mounted.container))
await act(async () => { await Promise.resolve() })
expect(fsWrite).toHaveBeenCalledTimes(1)
// The restored text, not the disk bytes, is what the editor writes.
expect(fsWrite.mock.calls[0]![2]).toBe('const restored = 2\n')
// Saving ends the draft: a later open must not offer it back.
expect(readDraftBackup('s1', '/p/a.ts', 'const a = 1\n')).toBeNull()
} finally {
mounted.unmount()
}
})
it('drops the draft and opens the disk bytes when the restore is declined', async () => {
seedDraft('s1', '/p/a.ts', 'const restored = 2\n')
const confirmSpy = vi.fn().mockReturnValue(false)
vi.stubGlobal('confirm', confirmSpy)
const mounted = renderRoot(createElement(TextEditor, viewerProps()))
try {
expect(confirmSpy).toHaveBeenCalledTimes(1)
click(saveButton(mounted.container))
await act(async () => { await Promise.resolve() })
expect(fsWrite.mock.calls[0]![2]).toBe('const a = 1\n')
expect(readDraftBackup('s1', '/p/a.ts', 'const a = 1\n')).toBeNull()
} finally {
mounted.unmount()
}
})
it('never prompts when the file has no stored draft', () => {
const confirmSpy = vi.fn().mockReturnValue(true)
vi.stubGlobal('confirm', confirmSpy)
const mounted = renderRoot(createElement(TextEditor, viewerProps()))
try {
expect(confirmSpy).not.toHaveBeenCalled()
} finally {
mounted.unmount()
}
})
})
describe('native tab close', () => {
it('flushes a pending draft through the host close hook before the body unmounts', () => {
vi.useFakeTimers()
const store = createSidebarStore()
store.setSession('s1')
const service = createBetterSidebarService(store)
service.registerTab({ id: 'editor', title: 'Files', component: () => null })
const records = createNativeTabRecords()
let closeHandler: (() => void) | undefined
const tabsRegistry = { register: () => () => {} }
const closeHost = {
registerCloseHandler: (_kind: string, handler: () => void) => {
closeHandler = handler
return () => { closeHandler = undefined }
},
}
const ctx = {
inject: (_deps: readonly string[], callback: (injected: { get: (name: string) => unknown }) => (() => void) | void) => {
const teardown = callback({ get: (name: string) => (name === 'sidebarRight' ? closeHost : tabsRegistry) })
return { dispose: () => { if (typeof teardown === 'function') teardown() } }
},
get: () => tabsRegistry,
slots: {
inject: (_key: string, callback: () => () => void) => callback(),
register: () => () => {},
},
}
const dispose = registerNativeSurface({ ctx: ctx as never, store, service, records })
const release = registerDraftSource('s1', '/work/a.ts', () => 'typed just now')
try {
expect(closeHandler, 'the editor kind registered a close handler').toBeTypeOf('function')
// The last keystroke is still inside the throttle window.
scheduleDraftBackup('s1', '/work/a.ts')
expect(readDraftBackup('s1', '/work/a.ts', 'disk')).toBeNull()
closeHandler?.()
expect(readDraftBackup('s1', '/work/a.ts', 'disk')).toBe('typed just now')
} finally {
release()
dispose()
}
})
})
+39
View File
@@ -24,6 +24,7 @@ import {
isEditorDirty, setEditorDirty, subscribeEditorDirty,
} from '../src/client/editor-dirty.ts'
import { clearRetargetedPath, closePathTabs, consumeRetargetedPath, pathTabKey, retargetPathTabs } from '../src/client/tree-mutations.ts'
import { flushDraftBackups, readDraftBackup, registerDraftSource, scheduleDraftBackup } from '../src/client/editor-draft-backup.ts'
import { createNativeSurface } from '../src/client/native/surface.ts'
import { createNativeTabRecords } from '../src/client/native/tab-adapter.tsx'
@@ -239,6 +240,44 @@ describe('editor-dirty registry', () => {
expect(confirmDiscardDraft('t1', 'sure?', 's1')).toBe(true)
expect(isEditorDirty('t1', 's9')).toBe(true)
})
it('a confirmed discard drops the durable draft backup too, a declined one keeps it', () => {
// The backup is the same draft: offering it back after the user chose to
// discard would resurrect what they just dropped.
const release = registerDraftSource('s1', '/tmp/durable.ts', () => 'live draft')
scheduleDraftBackup('s1', '/tmp/durable.ts')
flushDraftBackups()
release()
const confirmSpy = vi.fn().mockReturnValue(false)
vi.stubGlobal('confirm', confirmSpy)
setEditorDirty('t1', true, 's1', '/tmp/durable.ts')
expect(confirmDiscardDraft('t1', 'sure?', 's1')).toBe(false)
expect(readDraftBackup('s1', '/tmp/durable.ts', 'disk')).toBe('live draft')
confirmSpy.mockReturnValue(true)
expect(confirmDiscardDraft('t1', 'sure?', 's1')).toBe(true)
expect(readDraftBackup('s1', '/tmp/durable.ts', 'disk')).toBeNull()
})
})
describe('sidebar unload guard', () => {
it('flushes a pending durable draft and blocks the unload while a draft is dirty', () => {
const mounted = mountSidebarWithEditor()
const release = registerDraftSource(mounted.sessionId, '/tmp/a.ts', () => 'pending draft')
try {
scheduleDraftBackup(mounted.sessionId, '/tmp/a.ts')
// The throttle has not fired: only the unload guard's flush persists it.
expect(readDraftBackup(mounted.sessionId, '/tmp/a.ts', 'hello')).toBeNull()
const event = new Event('beforeunload', { cancelable: true })
act(() => { window.dispatchEvent(event) })
expect(readDraftBackup(mounted.sessionId, '/tmp/a.ts', 'hello')).toBe('pending draft')
expect(event.defaultPrevented, 'a dirty draft still arms the browser prompt').toBe(true)
} finally {
release()
mounted.unmount()
}
})
})
describe('tree close-on-delete', () => {
+1 -1
View File
@@ -551,7 +551,7 @@ describe('registerNativeSurface lifecycle (service-driven registration)', () =>
const ctx = {
inject: (deps: readonly string[], callback: (injected: { get: (name: string) => unknown }) => void) => {
expect(deps).toEqual(['sidebarRightTabs'])
expect(deps).toEqual(['sidebarRightTabs', 'sidebarRight'])
runInjected = () => { callback({ get: () => registry.current }) }
return { dispose: () => { runInjected = undefined } }
},