M1.7: crash-recovery journal and restore dialog

Dirty buffers are written atomically to <data_dir>/recovery/<project-id>/
about 1 s after the last edit (at most 2 s while typing), from pump_vfs,
never per keystroke. Entries are removed on save, close (also force),
forced project close/open and recovery.discard. project.open emits
recoveryAvailable; recovery.list/restore/discard; restored buffers are
dirty and keep line ending and BOM. Corrupt entries are moved aside and
reported as warning notifications.

UI: restore dialog in ui/src/components/recovery (Restore all, Restore
selected, Discard, time, changed-on-disk hint), catalog keys and runtime
allow-list. Tests: crash/restore with CRLF + BOM, corrupt entries, removal
paths, property test of random edits, headless control-channel test,
Vitest for the dialog. Docs: architecture, parity, gaps, ROADMAP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-16 15:54:52 +02:00
parent 6d976ed03e
commit 0b40eb90f8
27 changed files with 2222 additions and 27 deletions

View file

@ -1,12 +1,14 @@
<script setup lang="ts">
/**
* Root component: mounts the main window layout with the editor area; the
* slogan shows while no tab is open. Loads product information from the
* slogan shows while no tab is open, and the restore dialog for unsaved
* texts from the recovery journal. Loads product information from the
* engine on mount and starts following the theme (see `theme.ts`).
*/
import { onMounted, onUnmounted } from "vue";
import EditorArea from "./components/editor/EditorArea.vue";
import MainLayout from "./components/layout/MainLayout.vue";
import RecoveryDialog from "./components/recovery/RecoveryDialog.vue";
import { useAppStore } from "./stores/app";
import { startTheme } from "./theme";
@ -34,6 +36,7 @@ onUnmounted(() => {
</p>
</EditorArea>
</MainLayout>
<RecoveryDialog />
</template>
<style scoped>

View file

@ -0,0 +1,316 @@
<script setup lang="ts">
/**
* The restore dialog: lists the unsaved texts the recovery journal holds
* after a project opened, with the time each was written and a hint when
* the file changed on disk since. Restore all, Restore selected (the ticked
* files; the rest stay listed) or Discard (every listed file). Escape closes
* the dialog and keeps the journal for the next open. When a restore leaves
* failures, they are listed until the dialog is closed.
*/
import { nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { t } from "../../i18n";
import { useRecoveryStore } from "./recovery";
const recovery = useRecoveryStore();
/** The Restore all button, focused when the dialog appears. */
const restoreAllButton = ref<HTMLButtonElement | null>(null);
/** The Close button shown when only failures are left. */
const closeButton = ref<HTMLButtonElement | null>(null);
onMounted(() => {
recovery.start();
});
onUnmounted(() => {
recovery.stop();
});
/**
* What the dialog shows: the list, only failures, or nothing. Focus moves
* to the first button whenever this changes to something visible.
*/
function mode(): "list" | "failures" | "hidden" {
if (!recovery.open) {
return "hidden";
}
return recovery.entries.length > 0 ? "list" : "failures";
}
watch(
mode,
async (shown) => {
if (shown !== "hidden") {
await nextTick();
(restoreAllButton.value ?? closeButton.value)?.focus();
}
},
{ immediate: true },
);
/**
* Formats a journal time for the list.
*
* @param savedAt - ms since the Unix epoch.
*/
function formatTime(savedAt: number): string {
return new Date(savedAt).toLocaleString();
}
/**
* Closes on Escape.
*
* @param event - the key event inside the dialog.
*/
function onKeydown(event: KeyboardEvent): void {
if (event.key === "Escape") {
event.preventDefault();
recovery.close();
}
}
/**
* Ticks or unticks an entry from its checkbox.
*
* @param path - the entry's path.
* @param event - the change event of the checkbox.
*/
function onToggle(path: string, event: Event): void {
recovery.toggle(path, (event.target as HTMLInputElement).checked);
}
</script>
<template>
<div
v-if="recovery.open"
class="recovery"
data-test="recovery-dialog"
>
<div
class="recovery__dialog"
role="dialog"
aria-modal="true"
aria-labelledby="lt-recovery-title"
aria-describedby="lt-recovery-intro"
@keydown="onKeydown"
>
<h2
id="lt-recovery-title"
class="recovery__title"
>
{{ t("recovery.dialog.title") }}
</h2>
<p
id="lt-recovery-intro"
class="recovery__intro"
>
{{ t("recovery.dialog.intro") }}
</p>
<ul
v-if="recovery.entries.length > 0"
class="recovery__list"
>
<li
v-for="entry in recovery.entries"
:key="entry.path"
class="recovery__entry"
data-test="recovery-entry"
>
<label class="recovery__label">
<input
type="checkbox"
:checked="recovery.selected.has(entry.path)"
:data-test="`recovery-select-${entry.path}`"
@change="onToggle(entry.path, $event)"
>
<span class="recovery__path">{{ entry.path }}</span>
</label>
<span class="recovery__meta">
{{ t("recovery.dialog.savedAt", { time: formatTime(entry.savedAt) }) }}
</span>
<span
v-if="entry.diskChanged"
class="recovery__changed"
data-test="recovery-changed"
>
{{ t("recovery.dialog.changedOnDisk") }}
</span>
</li>
</ul>
<ul
v-if="recovery.failures.length > 0"
class="recovery__failures"
role="alert"
data-test="recovery-failures"
>
<li
v-for="failure in recovery.failures"
:key="failure.path"
>
{{ t("recovery.dialog.failed", { path: failure.path, message: failure.message }) }}
</li>
</ul>
<p
v-if="recovery.error"
class="recovery__error"
role="alert"
data-test="recovery-error"
>
{{ recovery.error }}
</p>
<div class="recovery__buttons">
<template v-if="recovery.entries.length > 0">
<button
ref="restoreAllButton"
type="button"
class="recovery__button recovery__button--primary"
data-test="recovery-restore-all"
:disabled="recovery.busy"
@click="recovery.restoreAll()"
>
{{ t("recovery.dialog.restoreAll") }}
</button>
<button
type="button"
class="recovery__button"
data-test="recovery-restore-selected"
:disabled="recovery.busy || recovery.selected.size === 0"
@click="recovery.restoreSelected()"
>
{{ t("recovery.dialog.restoreSelected") }}
</button>
<button
type="button"
class="recovery__button"
data-test="recovery-discard"
:disabled="recovery.busy"
@click="recovery.discard()"
>
{{ t("recovery.dialog.discard") }}
</button>
</template>
<button
v-else
ref="closeButton"
type="button"
class="recovery__button recovery__button--primary"
data-test="recovery-close"
@click="recovery.close()"
>
{{ t("common.close") }}
</button>
</div>
</div>
</div>
</template>
<style scoped>
.recovery {
position: fixed;
inset: 0;
display: flex;
align-items: flex-start;
justify-content: center;
padding-top: 10%;
background: color-mix(in srgb, var(--lt-bg) 50%, transparent);
z-index: 20;
}
.recovery__dialog {
min-width: 360px;
max-width: min(640px, 90vw);
max-height: 70vh;
display: flex;
flex-direction: column;
padding: 16px;
background: var(--lt-bg);
color: var(--lt-fg);
border: 1px solid var(--lt-border);
border-radius: 6px;
}
.recovery__title {
margin: 0 0 8px;
font-size: var(--lt-font-size-ui);
font-weight: 600;
}
.recovery__intro {
margin: 0 0 12px;
}
.recovery__list,
.recovery__failures {
margin: 0 0 12px;
padding: 0;
list-style: none;
overflow-y: auto;
}
.recovery__entry {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 4px 12px;
padding: 4px 0;
border-bottom: 1px solid var(--lt-border);
}
.recovery__label {
display: flex;
align-items: baseline;
gap: 6px;
}
.recovery__path {
overflow-wrap: anywhere;
}
.recovery__meta {
color: var(--lt-fg-muted);
font-size: var(--lt-font-size-small);
}
.recovery__changed {
color: var(--lt-accent);
font-size: var(--lt-font-size-small);
}
.recovery__failures,
.recovery__error {
color: var(--lt-error);
}
.recovery__error {
margin: 0 0 12px;
}
.recovery__buttons {
display: flex;
justify-content: flex-end;
gap: 8px;
}
.recovery__button {
padding: 4px 12px;
font: inherit;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: 4px;
}
.recovery__button--primary {
border-color: var(--lt-accent);
}
.recovery__button:disabled {
color: var(--lt-fg-muted);
}
.recovery__button:focus-visible,
.recovery__label input:focus-visible {
outline: 1px solid var(--lt-accent);
}
</style>

View file

@ -0,0 +1,236 @@
/**
* State of the restore dialog: the unsaved texts the engine's crash-recovery
* journal offers after a project opens (see `docs/architecture.md` ›
* Recovery journal).
*
* The list arrives with the `recoveryAvailable` event. Because that event is
* not replayed after a page reload, `projectOpened` also asks the engine with
* `recovery.list`. Every action names its paths explicitly, so entries of
* files restored earlier in the dialog are never discarded by accident.
*/
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { onEngineEvent, run, type EngineEventPayload, type JsonValue } from "../../ipc";
/** One unsaved text the journal holds. */
export interface RecoveryEntry {
/** Project-relative path with `/`. */
path: string;
/** When the text was written to the journal, ms since the Unix epoch. */
savedAt: number;
/** The file changed on disk after that, or is gone. */
diskChanged: boolean;
}
/** A path the engine could not restore, with its message. */
export interface RecoveryFailure {
/** Project-relative path. */
path: string;
/** English message from the engine. */
message: string;
}
/**
* Checks the entry list of `recoveryAvailable` or `recovery.list`; it
* crosses the IPC boundary. Malformed entries are skipped.
*
* @param raw - the `entries` value, untrusted.
* @returns the valid entries.
*/
export function toRecoveryEntries(raw: unknown): RecoveryEntry[] {
if (!Array.isArray(raw)) {
return [];
}
return raw.flatMap((item: unknown) => {
if (typeof item !== "object" || item === null) {
return [];
}
const e = item as Record<string, unknown>;
return typeof e.path === "string" &&
typeof e.savedAt === "number" &&
Number.isFinite(e.savedAt) &&
typeof e.diskChanged === "boolean"
? [{ path: e.path, savedAt: e.savedAt, diskChanged: e.diskChanged }]
: [];
});
}
/**
* Checks the `failed` list of `recovery.restore`.
*
* @param raw - the `failed` value, untrusted.
* @returns the valid failures.
*/
function toFailures(raw: unknown): RecoveryFailure[] {
if (!Array.isArray(raw)) {
return [];
}
return raw.flatMap((item: unknown) => {
if (typeof item !== "object" || item === null) {
return [];
}
const f = item as Record<string, unknown>;
return typeof f.path === "string" && typeof f.message === "string"
? [{ path: f.path, message: f.message }]
: [];
});
}
/** Store behind the restore dialog. */
export const useRecoveryStore = defineStore("recovery", () => {
/** Entries still waiting for a decision; the dialog shows while non-empty. */
const entries = ref<RecoveryEntry[]>([]);
/** Paths ticked for "Restore selected". */
const selected = ref<Set<string>>(new Set());
/** Paths the last restore could not open. */
const failures = ref<RecoveryFailure[]>([]);
/** Error of the last failed call, shown in the dialog. */
const error = ref<string | null>(null);
/** A restore or discard is running. */
const busy = ref(false);
/** Whether the dialog is shown. */
const open = computed(() => entries.value.length > 0 || failures.value.length > 0);
/** Ends the event subscription; null while not subscribed. */
let unsubscribe: (() => void) | null = null;
/**
* Shows `list` in the dialog, with nothing ticked.
*
* @param list - the entries.
*/
function show(list: RecoveryEntry[]): void {
entries.value = list;
selected.value = new Set();
failures.value = [];
error.value = null;
}
/** Hides the dialog; the journal keeps its entries for the next open. */
function close(): void {
show([]);
}
/** Asks the engine for the entries, after a project opened. */
async function refresh(): Promise<void> {
const result = await run<{ entries?: unknown }>("recovery.list");
if (result.ok) {
show(toRecoveryEntries(result.value.entries));
}
}
/**
* Reacts to an engine event.
*
* @param event - the event, untrusted.
*/
function handleEvent(event: EngineEventPayload): void {
switch (event.kind) {
case "recoveryAvailable":
show(toRecoveryEntries((event as { entries?: unknown }).entries));
break;
case "projectOpened":
void refresh();
break;
case "projectClosed":
close();
break;
default:
break;
}
}
/** Subscribes to engine events; repeated calls do nothing. */
function start(): void {
unsubscribe ??= onEngineEvent(handleEvent);
}
/** Ends the subscription. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
}
/**
* Ticks or unticks a path.
*
* @param path - the entry's path.
* @param on - whether it is ticked.
*/
function toggle(path: string, on: boolean): void {
const next = new Set(selected.value);
if (on) {
next.add(path);
} else {
next.delete(path);
}
selected.value = next;
}
/**
* Runs a recovery command on `paths` and removes them from the list when
* it succeeds.
*
* @param command - `recovery.restore` or `recovery.discard`.
* @param paths - the paths, never empty.
*/
async function act(command: string, paths: string[]): Promise<void> {
if (busy.value || paths.length === 0) {
return;
}
busy.value = true;
error.value = null;
const params: JsonValue = { paths };
const result = await run<{ failed?: unknown }>(command, params);
busy.value = false;
if (!result.ok) {
error.value = result.error.message;
return;
}
const done = new Set(paths);
entries.value = entries.value.filter((e) => !done.has(e.path));
selected.value = new Set([...selected.value].filter((p) => !done.has(p)));
failures.value = toFailures(result.value.failed);
}
/** Restores every listed entry. */
async function restoreAll(): Promise<void> {
await act(
"recovery.restore",
entries.value.map((e) => e.path),
);
}
/** Restores the ticked entries; the others stay listed. */
async function restoreSelected(): Promise<void> {
await act(
"recovery.restore",
entries.value.filter((e) => selected.value.has(e.path)).map((e) => e.path),
);
}
/** Discards every listed entry. */
async function discard(): Promise<void> {
await act(
"recovery.discard",
entries.value.map((e) => e.path),
);
}
return {
entries,
selected,
failures,
error,
busy,
open,
handleEvent,
start,
stop,
toggle,
close,
restoreAll,
restoreSelected,
discard,
};
});

View file

@ -1,6 +1,7 @@
{
"app.statusBar.version": "{name} {version}",
"common.cancel": "Cancel",
"common.close": "Close",
"common.dismiss": "Dismiss",
"common.dontSave": "Don't Save",
"common.error.unexpectedResult": "unexpected result of {command}",
@ -15,10 +16,21 @@
"editor.tabs.close": "Close {name}",
"editor.tabs.label": "Editor tabs",
"editor.tabs.unsaved": "unsaved changes",
"notification.recovery.corrupt": "Skipped an unreadable recovery file ({file}): {reason}",
"notification.recovery.unavailable": "Could not read the recovery journal: {reason}",
"notification.recovery.writeFailed": "Could not keep a recovery copy of {path}: {reason}",
"project.empty.noFolder": "No folder is open.",
"project.openFolder": "Open Folder…",
"project.toolWindow.title": "Project",
"project.tree.loading": "Loading…",
"recovery.dialog.changedOnDisk": "The file changed on disk since then",
"recovery.dialog.discard": "Discard",
"recovery.dialog.failed": "{path} could not be restored: {message}",
"recovery.dialog.intro": "Lutra stopped before these files were saved. Restore your unsaved changes?",
"recovery.dialog.restoreAll": "Restore All",
"recovery.dialog.restoreSelected": "Restore Selected",
"recovery.dialog.savedAt": "Saved {time}",
"recovery.dialog.title": "Unsaved changes found",
"theme.lutraDark": "Lutra Dark",
"theme.lutraLight": "Lutra Light"
}

View file

@ -26,7 +26,11 @@ export type EngineEventPayload =
| { kind: "bufferClosed"; id: number }
| { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean }
| { kind: "watchFailed"; message: string }
| { kind: "themeChanged"; id: string; dark: boolean; tokens: Record<string, string> };
| { kind: "themeChanged"; id: string; dark: boolean; tokens: Record<string, string> }
| {
kind: "recoveryAvailable";
entries: { path: string; savedAt: number; diskChanged: boolean }[];
};
/** Callback receiving engine events. */
export type EngineEventHandler = (event: EngineEventPayload) => void;