Skip to content

fix(editor): restore unsaved editor buffers after Emdash ends without saving - #3676

Draft
kdcokenny wants to merge 17 commits into
mainfrom
fix/restore-unsaved-editor-buffers
Draft

kdcokenny wants to merge 17 commits into
mainfrom
fix/restore-unsaved-editor-buffers

Conversation

@kdcokenny

@kdcokenny kdcokenny commented Dec 5, 2026 •

Copy link
Copy Markdown
Member

Description

What users saw: when Emdash ended with unsaved editor changes and no chance to ask (a Windows
restart or shutdown, "Restart anyway", a forced shutdown, a crash, kill -9), the edit was gone at
the next start.

Cause: Emdash already keeps a crash-recovery copy of unsaved buffers, but never restored it.
The copy is written by the main process to its own SQLite file (*-editor-buffers.db, beside the
app database) about 2 s after typing stops. The only restore was a one-time listing when the editor
mounted. That listing applied rows only to files whose buffers were already open, and the restored
tabs open their buffers after it, so every row was skipped. Reproduced on main in the real app:
edit, kill -9, start. The row was in the database, the tab came back, and the buffer showed the
text on disk.

Now: a buffer fetches its own backup when it opens (editor.getBuffer), so the copy is
applied however and whenever the file is opened again: restored tab or opened later. Nothing
depends on what happens while the OS is ending the session. Every copy is already written before
then, by the main process, which already wrote the copy before this change.

Rules:

  • Backup: written 2 s after typing stops (the delay on main), together with the etag of the
    disk version the edit started from (base_etag, new column). Every pending backup is also
    written at once when:

    • the page loses focus or is hidden (DOM blur, visibilitychange);
    • the native window loses focus (main-process blur);
    • Windows starts ending the session (main-process query-session-end / session-end on the
      window, Windows only).

    For a session end, the main process asks the renderer to flush. It never holds or vetoes the
    session end, and does not wait for the writes. The backups are written by the main process
    (the editor Wire controller in the desktop gateway), not a worker. On Windows the main process
    outlives the workers by about a second after a restart click.

  • A backup exists exactly while its buffer differs from disk. Every change of the dirty flag
    goes through one place. A buffer that turns clean by any route loses its backup: save, Save All,
    undo back to the disk text, the disk catching up to the buffer, Discard (tab close, quit prompt,
    conflict reload). One stated exception: when a renamed file's unsaved text is carried to a path
    whose entry has no editable buffer open yet (for example only a diff), its backup exists before
    that buffer does. It is applied as unsaved when the buffer opens, or restored on the next open.

  • Rename or move keeps the disk version the edit started from, in the backup row and in the
    open buffer. A file changed after the rename is still marked conflicted.

  • Restored as an unsaved buffer, with one toast per file: "Unsaved changes to a.txt were
    restored. They were not saved before Emdash last closed." Save and Discard then work as for any
    unsaved buffer. A backup equal to the file on disk is dropped silently. A lookup that returns
    after the user edited, undid, saved or discarded the buffer is not applied.

  • Disk changed since the backup: the buffer keeps the backed-up text and is marked conflicted,
    the editor's existing state for a disk change under a dirty buffer. Saving then opens the existing
    "which version to keep" dialog. The toast says: "The file on disk has changed since then. Saving
    will ask which version to keep."

  • Conflict dialog (also broken on main): it opened from a MobX autorun. Opening a modal
    reads and writes the modal stack, so the autorun re-triggered itself until MobX's cycle limit and
    stacked ~99 dialogs whose backdrops turned the window black. It now runs from one reaction per
    task, shared by split panes. Conflicts are queued per file and asked one after another. Each
    answer applies to the file it was asked for. A dialog closed without a choice leaves that file
    conflicted and writes nothing, and its next save asks again. Closing a file closes its dialog
    (the conflict stays pending), and the next file is asked only after the current dialog has
    settled, so dialogs never stack or repeat. The dialog itself still blocks
    Escape (its existing close guard), so in practice it closes only through a choice.

  • Task deletion: a deleted task's unsaved buffers and backups are dropped only when the host
    actually removed its worktree from disk. The host does that only when no other task, archived
    ones included, uses the workspace. If the worktree is kept (Delete worktree unchecked, a
    directory or repository workspace, a failed removal), its unsaved edits stay. The quit prompt
    then still counts that kept worktree's buffers after its task is deleted.
    This is intended:
    the files still exist and can be saved.

  • Size cap: 1,000,000 characters per buffer (about 2 MB), applied to every backup write,
    rename included. Above it no backup is kept (an older, smaller one is removed); nothing else
    changes. Binary and preview-only tabs have no text buffer and are not backed up.

  • The backup store can never stop Emdash from starting or editing, and is never deleted
    unless corrupt.
    Only a file SQLite reports as SQLITE_NOTADB or SQLITE_CORRUPT is deleted
    and recreated; that case also failed on main. Any other failure leaves every file as it is
    and turns backups off for that run: a lock held by a second instance or scanner, read-only,
    permissions, full disk, or I/O. This applies at open and during the upgrade rebuild, which
    runs in one transaction. The reason is logged once. A locked store delays startup by SQLite's
    5 s busy timeout before giving up.

  • Rename onto a path the editor already holds: the moved buffer is torn down, as on main,
    but its unsaved text is not lost. It goes to the entry at the new path:

    • applied at once as unsaved if that buffer is open and clean;
    • otherwise applied when its buffer opens.

    Its backup is kept for the new path with the disk version the edit started from, so a crash or
    a closed target restores it with the notice. This handing-over was chosen over keeping only the
    backup: with only the backup, an open clean target would not show the text, and the user's next
    keystroke there would overwrite it. Limit: if the open file at the new path already has
    unsaved edits of its own, those are kept, and the moved text is not carried.

  • Known limit: an edit followed by an undo, made before the restore lookup returns (one Wire
    round trip after the file opens), removes the previous run's backup without a notice.

  • Remote (SSH) files: handled the same way; the backup is keyed by host and path and stored on
    the desktop.

  • Ordinary quit is unchanged: "Save changes before quitting?" still appears; Save All and
    Discard clear the backups through the same save/discard paths.

The buffer store is a self-managed derived SQLite store, not a Drizzle database, so adding the
column needs no migration. Its schema fingerprint changes, so the store is recreated once on
upgrade and existing copies are dropped (they were never restored before).

The one-time restoreBuffers() mount effect and OpenFileStore.hydrateBuffer() are removed; the
per-buffer restore replaces them. deleteTasks now also returns removedWorktreeTaskIds. No new
setting, no new dependency.

Commits:

  1. Restore unsaved buffers.
  2. Conflict dialog opens once.
  3. Drop a deleted task's unsaved buffers.
  4. Write pending backups on blur/hide.

After review:

  1. Backup exactly while dirty, cap on every write, delay back to 2 s.
  2. Rename keeps the base; late restores skipped.
  3. Conflict answers bound per file, one prompt per task.
  4. Task deletion only for removed worktrees.
  5. Backup store open never fails the app.

After the re-review:

  1. Delete the store only when corrupt.
  2. Flush on Windows session end and native window blur.
  3. No backup after a rename onto an open file.
  4. Conflict dialog closes with its file and never stacks.
  5. Property-test backup law.
  6. Formatting.

After re-review 2:

  1. A rename onto an open file keeps its unsaved text (replaces 12).
  2. Model-based property for the backup invariant in both directions.

Related issues

Fixes #3590

This replaces the approach in #3675 (holding the Windows session end), which failed on a real
Windows machine.

Testing

On Linux (apps/emdash-desktop):

Check Result
pnpm run format:check (root) pass
pnpm run lint (root) pass
nx run @emdash/emdash-desktop:typecheck pass
vitest run --project node --project main-db 6156 passed, 1 failed, 11 skipped (before the review fixes). The failure is xterm-tmux.test.ts, which also fails on main here
Editor, tasks, shutdown and renderer app tests after the re-review fixes (node + main-db) 760 passed
Buffer property test with the new backup law, FC_NUM_RUNS=2000 pass; against the store before the review fixes it shrinks to [Acquire, Edit, DiskChange]
New model-based property "backup exactly while unsaved" (two files; open, close, type, revert, save, discard, disk write, wait, flush, rename incl. onto an open path) passes FC_NUM_RUNS=2000 (3.6 s; about 0.2 s at the default 100). Reverting each of the disk catch-up, reconcile, write-guard, discard and rename-onto-open fixes makes it fail at the default 100 runs: 5 of 5
Editor, tasks, shutdown and renderer app tests (node + main-db) at the final head 763 passed
New and updated tests each fails without its commit (15 restore, 1 conflict dialog, 3 deleted task, 2 blur flush; after review: 3 backup lifecycle, 4 rename and late restore, 3 conflict queue, 6 task deletion, 3 store open)

Tests cover: backup written after the debounce with its base etag; removed on save, on discard,
on typing back to the saved text, and above the size cap. Restore on open as unsaved with one
notice; conflicted, with the disk-changed notice, when the disk etag differs; a backup equal to
disk dropped silently; edits typed before the backup arrives are not overwritten. Service
getBuffer/clearBuffersUnder (scoped to root and host). deleteTask forgets backups for local,
SSH and kept-worktree deletions, and not for a shared workspace.

Manual, built app on a Linux VM (pinned Electron 45.4.1, scratch HOME and EMDASH_DB_FILE):

  • On main first: edit a.txt, wait, kill -9, start. The tab came back with the text on disk;
    the edit was lost although its row was in the backup database.
  • This branch: edit a.txt, kill -9, start. The tab came back with the edit and the unsaved dot,
    and a toast "Unsaved changes to a.txt were restored". The file on disk was unchanged.
  • This branch: Ctrl+S, kill -9, start. The saved text was shown, no unsaved dot, nothing
    restored, and the backup table was empty.
  • Conflict dialog, on main first: edit, change the file from a terminal, Ctrl+S. The window
    went black with 99 dialogs in the DOM and [mobx] cycle in reaction in the console. After Keep
    Mine (disk got my text) or Accept Incoming (disk kept), 98 dialogs stayed and the window stayed
    black. This branch: one dialog with the normal backdrop. Keep Mine wrote my text, Accept
    Incoming loaded the disk text, the window came back, and there was no cycle error.
  • Deleted task: two tasks, each with an unsaved a.txt. Ctrl+Q said "2 files have unsaved
    changes". After deleting the second task it said "1 file", and only the first task's backup
    row was left.
  • Blur flush, driven with xdotool and no DevTools client (DevTools focus emulation swallows blur):
    typing without leaving the window produced no backup row within 900 ms. Typing and then focusing
    another window wrote the row 25 ms and 28 ms after the focus moved.
  • Once, while a script was polling the window over the DevTools protocol during startup, the
    window stayed blank. The renderer was idle and did not answer. A plain relaunch was normal. I
    did not see it again.

After the review fixes, in the built app on Linux:

  • Store open: the backup file replaced with garbage before launch. Emdash started normally, the
    log had one line ("Unsaved-editor backup store was unreadable and has been recreated"), and the
    file was a valid SQLite database again.
  • Backup exactly while dirty: typed in a.txt and the backup row appeared. Writing the same text
    to the file from a terminal removed the row. Changing the file again on disk made the buffer
    follow, with no unsaved dot.
  • Conflict queue: a.txt and b.txt both edited and changed on disk. Saving b.txt opened one
    dialog for b.txt (Escape does not close it; its close guard). Keep Mine wrote only b.txt.
    Saving a.txt then opened one dialog for a.txt, and Accept Incoming kept a.txt's disk text
    without touching b.txt. There is no Save All command to try in the app, so asking several
    files in turn is covered by unit tests only.

For the Windows tester, session-end flush: with an unsaved edit typed less than 2 s before
Start > Restart, the app log should show, from the main process,
query-session-end: asking the renderer to write pending editor backups (and/or session-end: …), followed by the renderer's Session end: wrote 1 pending editor backup(s). A count of 0
means the edit had already been backed up, for example by the blur flush. Whether the
main-process window blur fires for a Start-menu click can only be seen on Windows. It is logged
only through the renderer flush and not at info level, so check whether the edit comes back.

Windows and macOS: not yet tested in the running app.

Checklist
  • I kept this PR small and focused
  • I ran a self-review before opening this PR
  • I ran the relevant local checks or explained why not
  • I updated docs when behavior or setup changed (no docs change needed)
  • I added or updated tests when behavior changed, or explained why not
  • I only added comments where the logic is not obvious
  • I used Conventional Commits for commit
    messages and, when possible, the PR title

… saving

The crash-recovery copy of unsaved buffers was written but never came back:
the one-shot restore on editor mount listed rows before the restored tabs
had opened their buffers, so every row was skipped. A buffer now fetches its
own backup when it opens and comes back as unsaved, with a one-time notice.

The backup also stores the disk version the edit started from; if the file
changed since, the buffer is marked conflicted and saving asks which version
to keep. Backups are written 1 s after typing stops, removed on save, discard
and typing back to the saved text, skipped above 1,000,000 characters, and
dropped with their task's workspace when the task is deleted.

Fixes #3590
…ed copies

The conflict prompt ran inside a MobX autorun. Opening a modal reads and
writes the modal stack, so the autorun re-triggered itself until MobX's
cycle limit, stacking about 100 dialogs whose backdrops turned the window
black. Choosing Keep Mine or Accept Incoming closed only the top one, so the
window looked frozen. Reproduced on main on Linux. A reaction runs its
effect untracked and opens the dialog once.
Deleting a task removed its backups on disk but kept its unsaved buffers in
memory, so the quit prompt still counted them until the next start. The
renderer now discards dirty buffers under the deleted task's workspace,
unless another live task still uses that workspace.
…es focus

A restart can end Emdash about a second after the click, and clicking Start
takes focus from the window first. An edit typed within the 1 s backup
debounce was lost. Pending backups are now also written at once on window
blur and when the document becomes hidden; the debounce is unchanged.

Copy link
Copy Markdown
Member Author

@greptile review

@greptile-apps

greptile-apps Bot commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5RetriggerView in Greptile

[Medium impact] The changes affect editor recovery and conflict flows, plus cleanup during task deletion.

Fix the rename transfer before merging because a delayed disk update can erase an unsaved edit.

Findings

  1. P1 Renaming loses unsaved text ▶
Fix with agent prompt
### Issue 1
apps/emdash-desktop/src/core/features/editor/api/browser/open-file-store/open-file-store.ts:973-978
`carryUnsavedText` can compare the moved edit with stale disk text from the destination. Keep `b.txt` open after deleting it outside Emdash, then rename dirty `a.txt` to `b.txt`. If the edit equals `b.txt`'s old text, `reconcileDirty` marks the destination clean and this branch deletes its backup. The delayed disk update then makes `applyDiskText` replace the buffer with `a.txt`'s saved text, losing the edit.

Compare against the moved file's disk version before clearing the backup or allowing the buffer to follow disk.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Restores unsaved editor text when each file opens and preserves its starting disk version.

  • Files bring back unsaved text from their own backup when they open.
  • Conflict questions appear one at a time and stay tied to their file.
  • Task deletion drops unsaved edits only when its worktree leaves disk.

Diagram

%%{init: {'theme': 'neutral', 'htmlLabels': false}}%%
flowchart TD
  A[Rename edited file] --> B[Write backup at new path]
  B --> C[Transfer edit to open destination]
  C --> D{Edit matches cached disk text?}
  D -->|No| E[Keep buffer unsaved]
  D -->|Yes| F[Mark clean and delete backup]
  F --> G[Delayed disk update arrives]
  G --> H[Replace buffer and lose edit]
Loading

Reviews (4) · Last reviewed commit: "test(editor): property-test that a backu..." · Reviewed by Greptile

Every change of an entry's dirty flag now goes through one place, and a
buffer that turns clean by any route (save, Save All, undo back to the disk
text, the disk catching up, discard) loses its backup. Before, a buffer the
disk had caught up with kept its row and came back later as restored
unsaved changes. Every backup write, including rename, now honours the
1,000,000-character cap; the post-save re-write that skipped it is gone.
The backup delay is back to 2 s as on main; the write on focus loss covers
the short window.
…d skip late restores

A renamed dirty buffer now carries the disk version its edit started from,
both in its backup row and in the open buffer, so a file changed after the
rename is still marked conflicted instead of being overwritten by a plain
save. A backup lookup that returns after the user edited, undid, saved or
discarded the buffer is no longer applied.
…pt per task

The conflict prompt kept a single pending path, so with two conflicted
files an answer could be applied to the other file, and after Escape the
same file never asked again. Conflicts are now queued per file and asked
one after another; an answer applies to the file it was asked for, and
dismissing leaves that file conflicted so its next save asks again. Split
panes share one prompt per task instead of opening a dialog each.
…e was removed

Task deletion dropped unsaved buffers and their backups even when the
worktree stayed on disk (Delete worktree unchecked, a directory workspace,
or a failed removal), and the renderer's shared-workspace check missed
archived tasks. The host now drops backups only after it removed the
worktree, which it does only when no task (archived ones included) still
uses the workspace, and deleteTasks reports those tasks so the renderer
discards exactly their buffers. A kept worktree keeps its unsaved edits.
…om starting

Opening the backup store at boot was unguarded, so a corrupt file (already
failing on main), or a read-only file or full disk during the rebuild that
this branch's schema change forces on upgrade, failed the launch. The store
is disposable: an unopenable file is now deleted and recreated, and if that
also fails Emdash runs with backups off. The reason is logged once.

Copy link
Copy Markdown
Member Author

@greptile review

Any error opening the unsaved-buffer backup store used to delete it,
including a lock held by a second instance or a scanner, a read-only file,
a full disk or an I/O error. That could destroy the only copy of unsaved
edits. The store is now recreated only for SQLITE_NOTADB or SQLITE_CORRUPT;
every other failure, at open or during the schema rebuild (which runs in one
transaction), leaves the files as they are and turns backups off for the
run, logged once.
…sion

Clicking Start before a restart did not move focus away from the window in
a way the renderer saw, so an edit typed within the backup delay was lost
on restart. The main process now asks the renderer to write every pending
backup when the window gets query-session-end or session-end (Windows only)
and when the native window loses focus. The session end is never held or
vetoed and nothing waits for the writes; the backup store is written by the
main process, which outlives the worker processes at session end. Both sides
log the session-end flush.
…n file

The moved entry is torn down in that case (unchanged behaviour), so the
backup written for it at the new path described a buffer that no longer
existed and the open target file is clean.
…e next one

Closing a file while its conflict dialog was open prompted the next file on
top of it, and reopening the file could open a duplicate. The dialog now
dismisses itself when its file closes (the file stays conflicted, so its
next save asks again), and the next conflict is asked only after the
current dialog has settled.
…ists while dirty

Against the store before the review fixes it shrinks to
[Acquire, Edit, DiskChange] (a backup kept after the disk caught up).

Copy link
Copy Markdown
Member Author

@greptile review

747b9e4 stopped writing the backup when a dirty file was renamed onto a path
the editor already held, so the moved edit was lost for good (for example
when the target was open only as a diff). The unsaved text now goes to the
entry at the new path: applied as unsaved at once if its buffer is open and
clean, or when its buffer opens, and its backup is kept for the new path
with the disk version the edit started from. An open target that already
has unsaved edits keeps them.
…ffer is unsaved

A model-based property over two files with open, close, typing, revert by
typing, save, discard, disk writes, waits, flushes and renames (onto a free
or an open path). It checks both directions: a backup always belongs to an
unsaved buffer, and after the delay or a flush every unsaved buffer has a
backup with its text; a rename never loses unsaved text. Reverting any of
the disk catch-up, reconcile, write-guard, discard or rename-onto-open fixes
fails it at the default 100 runs.

Copy link
Copy Markdown
Member Author

@greptile review

Comment on lines +973 to 978
this.reconcileDirty(target);
if (!target.dirty) {
const uri = target.uri;
void getEditorClient()
.then((client) => client.saveBuffer({ uri, content }))
.then((client) => client.clearBuffer({ uri }))
.catch(() => undefined);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Renaming loses unsaved text

carryUnsavedText can compare the moved edit with stale disk text from the destination. Keep b.txt open after deleting it outside Emdash, then rename dirty a.txt to b.txt. If the edit equals b.txt's old text, reconcileDirty marks the destination clean and this branch deletes its backup. The delayed disk update then makes applyDiskText replace the buffer with a.txt's saved text, losing the edit.

Compare against the moved file's disk version before clearing the backup or allowing the buffer to follow disk.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/emdash-desktop/src/core/features/editor/api/browser/open-file-store/open-file-store.ts
Line: 973-978

Comment:
**Renaming loses unsaved text**

`carryUnsavedText` can compare the moved edit with stale disk text from the destination. Keep `b.txt` open after deleting it outside Emdash, then rename dirty `a.txt` to `b.txt`. If the edit equals `b.txt`'s old text, `reconcileDirty` marks the destination clean and this branch deletes its backup. The delayed disk update then makes `applyDiskText` replace the buffer with `a.txt`'s saved text, losing the edit.

Compare against the moved file's disk version before clearing the backup or allowing the buffer to follow disk.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug]: Windows restart or shutdown with unsaved editor changes loses them without a prompt

1 participant