Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(editor): a history row moved the document and left the disk where it was

esengine5ccd4264cb04
diff --git a/desktop/electron/fileJournal.ts b/desktop/electron/fileJournal.ts
index e23267b5c..743f0d83f 100644
--- a/desktop/electron/fileJournal.ts
+++ b/desktop/electron/fileJournal.ts
@@ -274,6 +274,32 @@ async function restore(root: string, entry: Entry): Promise<void> {
else await rm(meta, { force: true });
}
+/**
+ * Revert several transactions as one gesture — a whole session, not one turn.
+ * NEWEST FIRST, in this module's order rather than the caller's: each holds
+ * what the project was when IT opened, so any other order restores an older
+ * image and then writes a newer one back over it.
+ */
+export async function revertMany(ids: readonly string[]): Promise<RevertResult> {
+ const wanted = new Set(ids);
+ const ordered = [...finished, ...(active ? [active.id] : [])].filter((id) => wanted.has(id));
+ // An id the ring has already dropped cannot be ordered, and reverting it out
+ // of order is worse than not reverting it — reported, not guessed at.
+ const unknown = ids.filter((id) => !transactions.has(id));
+ const out: RevertResult = {
+ restored: [],
+ unjournaled: [],
+ failed: unknown.map((id) => ({ path: id, error: 'this run is too old to still be held' })),
+ };
+ for (const id of ordered.reverse()) {
+ const one = await revert(id);
+ out.restored.push(...one.restored);
+ out.unjournaled.push(...one.unjournaled);
+ out.failed.push(...one.failed);
+ }
+ return out;
+}
+
/** Forget a transaction and delete its copies — the user kept the work. */
export async function discard(id: string): Promise<void> {
const tx = transactions.get(id);
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 09559d94b..b58fa3c9c 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -789,13 +789,13 @@ ipcMain.handle(
(_e, callId: string, answer: ConfirmAnswer, declined?: number[]) => agentHost.confirm(callId, answer, declined),
);
/**
- * Put the project files a turn wrote back, and tell the window which paths
- * moved so its ordinary external-change path picks them up. Reverting the
- * DOCUMENT is the window's own half (EditorHistory.undoToMark) — this side owns
- * only the disk.
+ * Put back the project files one or more runs wrote, and tell the window which
+ * paths moved so its ordinary external-change path picks them up. A LIST
+ * because going back past several runs is one gesture, and the order they come
+ * apart in is the journal's to know. The DOCUMENT half is the window's.
*/
-ipcMain.handle('agent:revertFiles', async (_e, txId: string) => {
- const result = await journal.revert(txId);
+ipcMain.handle('agent:revertFiles', async (_e, txIds: readonly string[]) => {
+ const result = await journal.revertMany(txIds);
const touched = [...result.restored, ...result.failed.map((f) => f.path)];
if (touched.length) notifyFsChanged(touched);
return result;
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index 264c58866..5ea53caf4 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -130,10 +130,11 @@ const api = {
/** Answer the pending confirmation for an irreversible tool. */
confirm: (callId: string, answer: ConfirmAnswer, declined?: readonly number[]): Promise<void> =>
ipcRenderer.invoke('agent:confirm', callId, answer, declined),
- /** Put back the project files a turn wrote (its file-journal transaction) and
- * say what came back. The DOCUMENT half is this window's own undo. */
- revertFiles: (txId: string): Promise<RevertResult> =>
- ipcRenderer.invoke('agent:revertFiles', txId),
+ /** Put back the project files these runs wrote (their file-journal
+ * transactions) and say what came back. The DOCUMENT half is this window's
+ * own undo — see src/engine/rewind.ts. */
+ revertFiles: (txIds: readonly string[]): Promise<RevertResult> =>
+ ipcRenderer.invoke('agent:revertFiles', txIds),
/** The turn was kept — drop the copies held for its revert. */
keepFiles: (txId: string): Promise<void> => ipcRenderer.invoke('agent:keepFiles', txId),
/** Drop the conversation and start a new one. */
diff --git a/desktop/src/components/AgentCheckpoint.tsx b/desktop/src/components/AgentCheckpoint.tsx
index dcb3357d8..3e5cf434b 100644
--- a/desktop/src/components/AgentCheckpoint.tsx
+++ b/desktop/src/components/AgentCheckpoint.tsx
@@ -23,7 +23,7 @@ import { Undo2, Check, Loader } from 'lucide-react';
import { useAgent, dismissCheckpoint, revertScope } from '@/store/AgentStore';
import { EditorHistory } from '@/engine/EditorHistory';
import type { HistoryMark } from '@/engine/EditorHistory';
-import { Toasts } from '@/store/Toasts';
+import { planRewind, rewind, reportRewind } from '@/engine/rewind';
import { t } from '@/i18n';
export function AgentCheckpoint() {
@@ -45,20 +45,11 @@ export function AgentCheckpoint() {
const revert = async (): Promise<void> => {
setReverting(true);
try {
- const steps = mark ? EditorHistory.undoToMark(mark) : 0;
- const result = last.tx ? await window.estella?.agent?.revertFiles?.(last.tx) : null;
+ // The same one-way operation a History row runs, over this turn's own
+ // point — there is one way to put the project back, not two.
+ const result = await rewind(planRewind(mark?.seq ?? 0, [last]));
dismissCheckpoint(last.id);
- const restored = result?.restored.length ?? 0;
- Toasts.push(t('agent.checkpoint.undone', { count: steps, files: restored }), 'info');
- // Every failure is named. A revert that could not put a file back leaves
- // the project in a state neither the turn nor the user asked for, and a
- // toast saying it worked is how that goes unnoticed until it breaks.
- for (const f of result?.failed ?? []) {
- Toasts.push(t('agent.checkpoint.failed', { path: f.path, error: f.error }), 'error');
- }
- if (result?.unjournaled.length) {
- Toasts.push(t('agent.checkpoint.stranded', { paths: result.unjournaled.join(', ') }), 'warn');
- }
+ reportRewind(result);
} finally {
setReverting(false);
}
diff --git a/desktop/src/engine/historyGroups.ts b/desktop/src/engine/historyGroups.ts
index 49ceb9946..eefde02cf 100644
--- a/desktop/src/engine/historyGroups.ts
+++ b/desktop/src/engine/historyGroups.ts
@@ -75,7 +75,6 @@ export function historyRows(
const owner = (id: number) => windows.find((w) => id > w.from && id <= w.until);
const claimed = new Map<number, TurnRow>();
const rows: HistoryRow[] = [];
- let newestEnd = -Infinity;
for (const step of steps) {
const w = owner(step.id);
@@ -104,17 +103,12 @@ export function historyRows(
}
}
- const newest = lastTurnRow(rows);
- if (newest) newestEnd = newest.endSeq;
- // Anything on the stack past the newest run is the person's own work, and
- // undoing to a mark takes it back too — so the offer is withdrawn rather than
- // reaching further than the row it sits on claims to.
- const past = steps.some((s) => !s.undone && s.id > newestEnd);
-
for (const row of rows) {
if (row.kind !== 'turn') continue;
- row.revertable = row === newest && !past && row.steps.every((s) => !s.undone);
row.undone = row.steps.length > 0 && row.steps.every((s) => s.undone);
+ // A files-only run has no steps to undo, and its transaction is the whole
+ // of what there is to take back.
+ row.revertable = !row.undone && (row.steps.length > 0 || row.files.length > 0);
}
return rows;
}
@@ -136,14 +130,6 @@ function turnRow(turn: AgentTurn, endSeq: number): TurnRow {
};
}
-function lastTurnRow(rows: readonly HistoryRow[]): TurnRow | null {
- for (let i = rows.length - 1; i >= 0; i--) {
- const row = rows[i];
- if (row.kind === 'turn') return row;
- }
- return null;
-}
-
/** `+`/`~`/`−` counts for a row's header, over both kinds of change. */
export interface ChangeTally { add: number; modify: number; remove: number }
diff --git a/desktop/src/engine/rewind.ts b/desktop/src/engine/rewind.ts
new file mode 100644
index 000000000..0814d9059
--- /dev/null
+++ b/desktop/src/engine/rewind.ts
@@ -0,0 +1,97 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file rewind.ts
+ * @brief Putting the project back to a point on the timeline — both halves of
+ * it, which is the only version of the operation that is true.
+ *
+ * The document alone can walk the undo stack in either direction, and for a
+ * while that was all a click on a history row did. It left the disk where it
+ * was, so going back past an agent run gave the scene from before it and the
+ * scripts from after: a state the project had never actually been in.
+ *
+ * So a rewind takes the runs with it. That makes it ONE-WAY — a reverted
+ * transaction hands back its copies and cannot re-apply them — which is why the
+ * plan is computed first and shown before anything moves, and why this is not
+ * folded into EditorHistory.goTo, which is reversible and must stay so.
+ */
+import { EditorHistory, type HistoryMark } from './EditorHistory';
+import { Toasts } from '@/store/Toasts';
+import type { AgentTurn } from '@/store/AgentStore';
+import type { FileChange } from '../../electron/agent/types';
+import { t } from '@/i18n';
+
+/** What going back to a point would take with it. */
+export interface RewindPlan {
+ /** The timeline point — every step past it is undone. */
+ point: number;
+ /** Agent runs whose whole transaction is past the point, oldest first. */
+ runs: readonly { id: number; prompt: string; tx: string }[];
+ /** Every project path those runs touched. */
+ files: readonly FileChange[];
+ /** Paths the journal could not hold, which a rewind therefore leaves. */
+ stranded: readonly FileChange[];
+}
+
+/**
+ * What a rewind to `point` would cover.
+ *
+ * A run counts only when ALL of it is past the point: a transaction is atomic
+ * on disk, so there is no half of one to give back, and a point inside a run is
+ * not a place the project can be put.
+ */
+export function planRewind(point: number, turns: readonly AgentTurn[]): RewindPlan {
+ const runs: RewindPlan['runs'] = turns
+ .filter((t) => t.tx && ((t.mark as HistoryMark | null)?.seq ?? -1) >= point)
+ .map((t) => ({ id: t.id, prompt: t.prompt, tx: t.tx! }));
+ const files = turns
+ .filter((t) => runs.some((r) => r.id === t.id))
+ .flatMap((t) => [...t.files]);
+ return { point, runs, files, stranded: files.filter((f) => f.unjournaled) };
+}
+
+/** What actually happened, so the caller can report it rather than assume. */
+export interface RewindResult {
+ steps: number;
+ restored: readonly string[];
+ unjournaled: readonly string[];
+ failed: readonly { path: string; error: string }[];
+}
+
+/**
+ * Carry out `plan`. The DOCUMENT moves first, so it is already at its pre-run
+ * state when the restored files land and the reload that follows has nothing to
+ * ask about.
+ */
+export async function rewind(plan: RewindPlan): Promise<RewindResult> {
+ const before = EditorHistory.list().filter((s) => !s.undone).length;
+ EditorHistory.goTo(plan.point);
+ const steps = before - EditorHistory.list().filter((s) => !s.undone).length;
+ if (plan.runs.length === 0) return { steps, restored: [], unjournaled: [], failed: [] };
+
+ const result = await window.estella?.agent?.revertFiles?.(plan.runs.map((r) => r.tx));
+ return {
+ steps,
+ restored: result?.restored ?? [],
+ unjournaled: result?.unjournaled ?? [],
+ failed: result?.failed ?? [],
+ };
+}
+
+/**
+ * Say what a rewind managed, including what it could not. A toast reporting
+ * success over a file still sitting there is how the one failure this whole
+ * mechanism exists to prevent goes unnoticed until something breaks on it.
+ */
+export function reportRewind(result: RewindResult): void {
+ Toasts.push(
+ t('agent.checkpoint.undone', { count: result.steps, files: result.restored.length }),
+ 'info',
+ );
+ for (const f of result.failed) {
+ Toasts.push(t('agent.checkpoint.failed', { path: f.path, error: f.error }), 'error');
+ }
+ if (result.unjournaled.length) {
+ Toasts.push(t('agent.checkpoint.stranded', { paths: result.unjournaled.join(', ') }), 'warn');
+ }
+}
diff --git a/desktop/src/i18n/messages/history.ts b/desktop/src/i18n/messages/history.ts
index a64c4ae5c..50b231e90 100644
--- a/desktop/src/i18n/messages/history.ts
+++ b/desktop/src/i18n/messages/history.ts
@@ -22,6 +22,21 @@ export const historyMessages = defineMessages({
zh: '{count} 步,但都没有声明改了什么',
},
'hist.revert': { en: 'Revert', zh: '撤回' },
+ // Going back past an agent run hands its held copies back, and they cannot
+ // be re-applied — so this one stops and says how far it reaches.
+ 'hist.rewind.title': {
+ en: 'Go back past {runs} agent run(s)?',
+ zh: '要退到 {runs} 轮 Agent 工作之前吗?',
+ },
+ 'hist.rewind.body': {
+ en: 'The scene goes back, and {files} project file(s) go back with it. This one cannot be redone — the copies held for those runs are handed back.',
+ zh: '场景会回退,{files} 个项目文件也一起回退。这一步无法重做 —— 为那几轮留的备份会被交还。',
+ },
+ 'hist.rewind.stranded': {
+ en: 'These were too large to hold and will stay as they are: {paths}',
+ zh: '这些太大没留备份,会保持现状:{paths}',
+ },
+ 'hist.rewind.go': { en: 'Go back', zh: '退回' },
'hist.revert.why': {
en: 'Take the whole run back — the scene edits and the files it wrote.',
zh: '整轮撤回 —— 场景改动和它写的文件一起。',
diff --git a/desktop/src/panels/HistoryPanel.tsx b/desktop/src/panels/HistoryPanel.tsx
index 8997330ba..9b995bd84 100644
--- a/desktop/src/panels/HistoryPanel.tsx
+++ b/desktop/src/panels/HistoryPanel.tsx
@@ -22,7 +22,8 @@ import { historyRows, tally, turnChanges, type HistoryRow, type TurnRow } from '
import { useAgent, dismissCheckpoint } from '@/store/AgentStore';
import { useSelection } from '@/store/selectionStore';
import { EmptyState } from '@/components/EmptyState';
-import { Toasts } from '@/store/Toasts';
+import { planRewind, rewind, reportRewind } from '@/engine/rewind';
+import { confirm } from '@/components/confirm';
import { t } from '@/i18n';
export function HistoryPanel() {
@@ -49,6 +50,30 @@ export function HistoryPanel() {
const rowKey = (row: HistoryRow): string =>
(row.kind === 'turn' ? `t${row.id}` : `s${row.step.id}`);
+/**
+ * Put the project back to a point — the ONE operation, whichever row asked.
+ * Walking the undo stack is reversible and asks nothing; taking agent runs with
+ * it is not, so that case stops first and states how many runs, how many files,
+ * and what it would leave behind. Answers whether it happened.
+ */
+async function goBackTo(point: number): Promise<boolean> {
+ const plan = planRewind(point, useAgent.getState().turns);
+ if (plan.runs.length > 0) {
+ const ok = await confirm({
+ title: t('hist.rewind.title', { runs: plan.runs.length }),
+ body: plan.stranded.length > 0
+ ? `${t('hist.rewind.body', { files: plan.files.length })}\n\n`
+ + t('hist.rewind.stranded', { paths: plan.stranded.map((f) => f.path).join(', ') })
+ : t('hist.rewind.body', { files: plan.files.length }),
+ confirmLabel: t('hist.rewind.go'),
+ danger: true,
+ });
+ if (!ok) return false;
+ }
+ reportRewind(await rewind(plan));
+ return true;
+}
+
function Row({ row }: { row: HistoryRow }) {
if (row.kind === 'turn') return <TurnGroup row={row} />;
const { step } = row;
@@ -56,7 +81,7 @@ function Row({ row }: { row: HistoryRow }) {
<button
type="button"
className={`hist-row${step.undone ? ' undone' : ''}`}
- onClick={() => EditorHistory.goTo(step.id)}
+ onClick={() => void goBackTo(step.id)}
>
<span className="hist-lbl">{step.label}</span>
<Tally counts={tally(step.changes)} />
@@ -73,17 +98,12 @@ function TurnGroup({ row }: { row: TurnRow }) {
const revert = async (): Promise<void> => {
setReverting(true);
try {
- const steps = row.mark ? EditorHistory.undoToMark(row.mark as HistoryMark) : 0;
- const result = row.tx ? await window.estella?.agent?.revertFiles?.(row.tx) : null;
- // The floating checkpoint bar is about this same turn; leaving it up after
- // its offer has been taken would invite taking it twice.
- dismissCheckpoint(row.id);
- Toasts.push(
- t('agent.checkpoint.undone', { count: steps, files: result?.restored.length ?? 0 }),
- 'info',
- );
- for (const f of result?.failed ?? []) {
- Toasts.push(t('agent.checkpoint.failed', { path: f.path, error: f.error }), 'error');
+ // Its mark is the point just before it — the same operation a bare row
+ // runs, aimed at where this run began.
+ if (await goBackTo((row.mark as HistoryMark | null)?.seq ?? 0)) {
+ // The floating checkpoint bar is about this same turn; leaving it up
+ // after its offer has been taken would invite taking it twice.
+ dismissCheckpoint(row.id);
}
} finally {
setReverting(false);
diff --git a/desktop/tests/file-journal.test.ts b/desktop/tests/file-journal.test.ts
index decf6d615..0ed0678fc 100644
--- a/desktop/tests/file-journal.test.ts
+++ b/desktop/tests/file-journal.test.ts
@@ -14,7 +14,7 @@ import { tmpdir } from 'node:os';
import path from 'node:path';
import {
beginTransaction, endTransaction, activeTransaction, capture, changes,
- revert, discard, discardAll, touchedPaths, isRestorable, __testing,
+ revert, revertMany, discard, discardAll, touchedPaths, isRestorable, __testing,
} from '../electron/fileJournal';
let root = '';
@@ -253,3 +253,64 @@ describe('a transaction lifetime', () => {
expect(await read('a.txt')).toBe('before');
});
});
+
+describe('a whole session, not one turn', () => {
+ // Each transaction holds what the project was when IT opened, so unwinding
+ // them newest-first lands on the state before the earliest. Any other order
+ // restores an older image and then writes a newer one back over it.
+ it('unwinds several runs to what was there before the first', async () => {
+ await write('HUD.esscene', 'v0');
+ const ids: string[] = [];
+ for (const v of ['v1', 'v2', 'v3']) {
+ beginTransaction(root);
+ await capture('HUD.esscene', 'write');
+ await write('HUD.esscene', v);
+ ids.push(endTransaction()!);
+ }
+ expect(await read('HUD.esscene')).toBe('v3');
+
+ await revertMany(ids);
+ expect(await read('HUD.esscene')).toBe('v0');
+ });
+
+ it('lands the same way whatever order it is handed them in', async () => {
+ await write('HUD.esscene', 'v0');
+ const ids: string[] = [];
+ for (const v of ['v1', 'v2', 'v3']) {
+ beginTransaction(root);
+ await capture('HUD.esscene', 'write');
+ await write('HUD.esscene', v);
+ ids.push(endTransaction()!);
+ }
+ await revertMany([ids[1], ids[2], ids[0]]);
+ expect(await read('HUD.esscene')).toBe('v0');
+ });
+
+ it('takes back every path the runs touched, not just the shared ones', async () => {
+ beginTransaction(root);
+ await capture('a.txt', 'write');
+ await write('a.txt', 'A');
+ const first = endTransaction()!;
+ beginTransaction(root);
+ await capture('b.txt', 'write');
+ await write('b.txt', 'B');
+ const second = endTransaction()!;
+
+ const result = await revertMany([first, second]);
+ expect(result.restored.sort()).toEqual(['a.txt', 'b.txt']);
+ expect(existsSync(abs('a.txt'))).toBe(false);
+ expect(existsSync(abs('b.txt'))).toBe(false);
+ });
+
+ // Retention drops the oldest. A run it can no longer reach is reported rather
+ // than skipped, because "the session came back" would then be a lie.
+ it('reports a run it no longer holds', async () => {
+ beginTransaction(root);
+ await capture('a.txt', 'write');
+ const id = endTransaction()!;
+ await discard(id);
+
+ const result = await revertMany([id]);
+ expect(result.failed).toEqual([{ path: id, error: 'this run is too old to still be held' }]);
+ });
+});
diff --git a/desktop/tests/history-groups.test.ts b/desktop/tests/history-groups.test.ts
index 5f61bc655..9772be5f7 100644
--- a/desktop/tests/history-groups.test.ts
+++ b/desktop/tests/history-groups.test.ts
@@ -111,11 +111,12 @@ describe('folding the timeline into rows', () => {
});
describe('which turn may offer a Revert', () => {
- // The stack is linear: undoing to an older turn's mark takes back every turn
- // after it too. Only the newest can honestly claim to revert itself.
- it('offers it on the newest turn only', () => {
+ // The stack is linear, so going back to an older run takes every later run
+ // with it — which the confirmation states before anything moves. Offering it
+ // only on the newest is what left a session with no way back at all.
+ it('offers it on every run that still has work in it', () => {
const rows = historyRows([step(1), step(2)], [turn(0, 0, 1), turn(1, 1, 2)]);
- expect(turns(rows).map((r) => r.revertable)).toEqual([false, true]);
+ expect(turns(rows).map((r) => r.revertable)).toEqual([true, true]);
});
it('withdraws it once the turn has been undone by hand', () => {
@@ -125,15 +126,19 @@ describe('which turn may offer a Revert', () => {
it('keeps offering it while only part of the turn is undone', () => {
const rows = historyRows([step(1), step(2, 'b', true)], [turn(0, 0, 2)]);
- expect(turns(rows)[0]).toMatchObject({ revertable: false, undone: false });
+ expect(turns(rows)[0]).toMatchObject({ revertable: true, undone: false });
});
- // A linear stack has no out-of-order undo: reverting to the run's mark would
- // take the person's later edit with it, so the offer goes rather than
- // reaching past what the row it sits on claims.
- it('withdraws it once the person has edited past the run', () => {
+ // Its steps are all undone, but the files it wrote are still on disk, and the
+ // transaction is the only thing that takes them back.
+ it('offers it on a files-only run whose steps are gone', () => {
+ const rows = historyRows([], [turn(0, 0, 0, { tx: 'tx-1', files: [file('src/HP.ts')] })]);
+ expect(turns(rows)[0].revertable).toBe(true);
+ });
+
+ it('still offers it when the person has edited past the run', () => {
const rows = historyRows([step(1), step(2)], [turn(0, 0, 1)]);
- expect(turns(rows)[0].revertable).toBe(false);
+ expect(turns(rows)[0].revertable).toBe(true);
});
});
diff --git a/desktop/tests/rewind-plan.test.ts b/desktop/tests/rewind-plan.test.ts
new file mode 100644
index 000000000..3c652e17c
--- /dev/null
+++ b/desktop/tests/rewind-plan.test.ts
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file How far going back to a point on the timeline reaches.
+ *
+ * The plan is what the confirmation states, so it is also what makes the
+ * gesture honest: a plan that under-counts lets a rewind take runs nobody was
+ * told about, and one that over-counts scares people off the only way back.
+ */
+import { describe, it, expect } from 'vitest';
+import { planRewind } from '@/engine/rewind';
+import type { AgentTurn } from '@/store/AgentStore';
+import type { FileChange } from '../electron/agent/types';
+
+const file = (path: string): FileChange => ({ path, kind: 'add', unjournaled: false });
+
+const turn = (id: number, from: number, to: number, over: Partial<AgentTurn> = {}): AgentTurn => ({
+ id, prompt: `run ${id}`, model: 'opus-5', entries: [],
+ inputTokens: 0, outputTokens: 0, context: null,
+ steps: to - from, mark: { seq: from }, endMark: { seq: to },
+ tx: `tx-${id}`, files: [file(`src/run${id}.ts`)],
+ acceptance: { verdict: 'unverified', results: [] },
+ reason: 'end_turn', startedAt: 0, endedAt: 1,
+ ...over,
+});
+
+describe('what going back to a point takes with it', () => {
+ it('takes nothing when no run is past the point', () => {
+ const plan = planRewind(9, [turn(0, 0, 3)]);
+ expect(plan.runs).toEqual([]);
+ expect(plan.files).toEqual([]);
+ });
+
+ it('takes the run that begins at the point', () => {
+ const plan = planRewind(0, [turn(0, 0, 3)]);
+ expect(plan.runs.map((r) => r.id)).toEqual([0]);
+ expect(plan.files.map((f) => f.path)).toEqual(['src/run0.ts']);
+ });
+
+ // The session-level case: going back past the first of five runs has to take
+ // the other four's files too, or the project lands somewhere it never was.
+ it('takes every run after the point, not just the one clicked', () => {
+ const plan = planRewind(0, [turn(0, 0, 3), turn(1, 3, 6), turn(2, 6, 9)]);
+ expect(plan.runs.map((r) => r.id)).toEqual([0, 1, 2]);
+ expect(plan.files).toHaveLength(3);
+ });
+
+ it('leaves the runs that finished before the point alone', () => {
+ const plan = planRewind(3, [turn(0, 0, 3), turn(1, 3, 6), turn(2, 6, 9)]);
+ expect(plan.runs.map((r) => r.id)).toEqual([1, 2]);
+ });
+
+ // A transaction is atomic on disk, so there is no half of one to hand back —
+ // a point inside a run is not a place the project can be put. (The panel
+ // never offers one: a run's steps are inside its group, not clickable rows.)
+ it('does not take a run the point falls inside', () => {
+ const plan = planRewind(2, [turn(0, 0, 5)]);
+ expect(plan.runs).toEqual([]);
+ });
+
+ it('ignores a run that never opened a transaction', () => {
+ const plan = planRewind(0, [turn(0, 0, 3, { tx: null, files: [] })]);
+ expect(plan.runs).toEqual([]);
+ });
+
+ // What it cannot put back is named in the plan, so the confirmation can say
+ // it BEFORE the gesture rather than a toast saying it afterwards.
+ it('names what it would leave behind', () => {
+ const big: FileChange = { path: 'Video/intro.mp4', kind: 'modify', unjournaled: true };
+ const plan = planRewind(0, [turn(0, 0, 3, { files: [file('src/a.ts'), big] })]);
+ expect(plan.files).toHaveLength(2);
+ expect(plan.stranded.map((f) => f.path)).toEqual(['Video/intro.mp4']);
+ });
+
+ it('carries the prompts, so the confirmation can name the runs', () => {
+ const plan = planRewind(0, [turn(0, 0, 3, { prompt: 'make a health bar' })]);
+ expect(plan.runs[0]).toMatchObject({ prompt: 'make a health bar', tx: 'tx-0' });
+ });
+});