Files
openidea/src/features/code-insight/workspaceUndo.ts
T
7fdf1d62c3 fix(refactor): preserve versions and recover multi-file workspace edits (#488)
Multi-file refactorings could drop LSP document versions, overwrite content changed after a preview, or leave earlier files saved after a later write failed. Workspace edits now keep server versions and preview fingerprints, are validated on a staging copy, snapshot disk and open buffers, and roll back on commit failure (retaining recovery files if rollback fails). The whole edit is one Undo/Redo step in editors and in the notification. Version reads and transaction work run off the async workers. Closes #461.

Co-authored-by: shohruh-genius <7658451+shohruh-genius@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:18:16 +08:00

56 lines
2.0 KiB
TypeScript

import { onWorkspaceEditHistory, whenAllSynced, workspaceEditHistory } from "@/editor/api";
import { onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { notifications } from "@/workbench/contributions";
/** The notification follows the same history state as editor Undo/Redo. */
export function installWorkspaceEditUndo(): () => void {
let current: { id: number; project: ReturnType<typeof useProject.getState>["project"]; undone: boolean } | null =
null;
const show = () => {
if (!current) return;
const entry = current;
const { id, project, undone } = entry;
notifications().notify({
level: "info",
title: undone ? "Refactoring undone" : "Refactoring applied",
key: "refactor.workspaceEdit",
actions: [
{
label: undone ? "Redo" : "Undo",
run: async () => {
try {
await whenAllSynced();
if (project !== useProject.getState().project)
throw new Error("The project for this refactoring is no longer open");
if (current !== entry || current.undone !== undone) return;
if (undone) await workspaceEditHistory(id, true);
else await workspaceEditHistory(id);
} catch (error) {
notifications().notify({
level: "error",
title: "Cannot undo refactoring",
body: error instanceof Error ? error.message : String(error),
});
}
},
},
],
});
};
const stopApplied = onIdeEvent("workspaceEditApplied", ({ id }) => {
current = { id, project: useProject.getState().project, undone: false };
show();
});
const stopHistory = onWorkspaceEditHistory(({ id, undone }) => {
if (!current || current.id !== id || current.project !== useProject.getState().project) return;
current = { ...current, undone };
show();
});
return () => {
stopApplied();
stopHistory();
current = null;
};
}