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.

feat(editor): a History panel where an agent run is one row

esengine4c323758897a
diff --git a/desktop/electron/agent/host.ts b/desktop/electron/agent/host.ts
index a37565071..4251b375a 100644
--- a/desktop/electron/agent/host.ts
+++ b/desktop/electron/agent/host.ts
@@ -357,7 +357,7 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
// path is reached BEFORE the turn starts (runTurn takes its checkpoint
// outside its own try), so there is no turn for it to be part of.
error = (e as Error)?.message ?? String(e);
- emit({ type: 'turn_end', steps: 0, mark: null, tx: null, files: [], reason: 'error' });
+ emit({ type: 'turn_end', steps: 0, mark: null, endMark: null, tx: null, files: [], reason: 'error' });
} finally {
settlePending();
// The run is over either way — errors included, since a conversation
diff --git a/desktop/electron/agent/kernel.ts b/desktop/electron/agent/kernel.ts
index f71abdd42..70fc34bea 100644
--- a/desktop/electron/agent/kernel.ts
+++ b/desktop/electron/agent/kernel.ts
@@ -170,7 +170,7 @@ export async function runTurn(
context: string | null,
signal: AbortSignal,
images?: readonly UserImage[],
-): Promise<{ mark: unknown; steps: number; tx: string | null }> {
+): Promise<{ mark: unknown; endMark: unknown; steps: number; tx: string | null }> {
const { driver, session, emit, model, acceptsImages } = deps;
const mark = await driver('mark', []);
// Opened before the first call and closed once, in the finally below: a
@@ -354,9 +354,12 @@ export async function runTurn(
// the result lands in the turn's own transaction.
deps.journal?.end();
const steps = await undoSteps(deps, mark);
+ // Where the turn's OWN work ends. Without it a run is bounded only by the next
+ // one, so the newest run claims every edit the person makes after it.
+ const endMark = await driver('mark', []).catch(() => null);
const files = tx ? deps.journal?.changes(tx) ?? [] : [];
- emit({ type: 'turn_end', steps, mark, tx, files, reason });
- return { mark, steps, tx };
+ emit({ type: 'turn_end', steps, mark, endMark, tx, files, reason });
+ return { mark, endMark, steps, tx };
}
/**
diff --git a/desktop/electron/agent/types.ts b/desktop/electron/agent/types.ts
index ff95124c3..aa65f9148 100644
--- a/desktop/electron/agent/types.ts
+++ b/desktop/electron/agent/types.ts
@@ -274,6 +274,9 @@ export type AgentEvent =
type: 'turn_end';
steps: number;
mark: unknown;
+ /** Where the turn's own work ENDS — what bounds it against the edits the
+ * person makes next, which a start mark alone cannot. */
+ endMark: unknown;
/** The file journal's transaction id, or null when none was open. */
tx: string | null;
files: readonly FileChange[];
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.ts
index 0f8eed2ae..4824db218 100644
--- a/desktop/src/commands/editorCommands.ts
+++ b/desktop/src/commands/editorCommands.ts
@@ -150,6 +150,14 @@ commands.register({
isEnabled: () => EditorHistory.canRedo(),
run: () => EditorHistory.redo(),
});
+commands.register({
+ id: 'edit.history',
+ label: t('hist.panelTitle'),
+ category: t('cat.edit'),
+ // Under Edit rather than View: it is the thing Ctrl+Z walks through, and where
+ // an agent run is taken back as one. Not ensured in the layout — see panels.ts.
+ run: () => dockApi.openPanel('history'),
+});
// — Entity —
commands.register({
diff --git a/desktop/src/components/AgentDrawer.tsx b/desktop/src/components/AgentDrawer.tsx
index 09f0d6101..383764f1c 100644
--- a/desktop/src/components/AgentDrawer.tsx
+++ b/desktop/src/components/AgentDrawer.tsx
@@ -523,11 +523,11 @@ function Skeleton() {
* those say what was ASKED for, these what the project differs by. A step that
* declared nothing contributes nothing, so this is a floor.
*/
-function ChangeSet({ turn, until }: { turn: AgentTurn; until: HistoryMark | null }) {
+function ChangeSet({ turn }: { turn: AgentTurn }) {
const [open, setOpen] = useState(true);
useSyncExternalStore(EditorHistory.subscribe, EditorHistory.getVersion);
const mark = turn.mark as HistoryMark | null;
- const changes = mark ? EditorHistory.changesSince(mark, until) : [];
+ const changes = mark ? EditorHistory.changesSince(mark, turn.endMark as HistoryMark | null) : [];
// Counted from the lists already read rather than by walking the stack a
// second time for the same window.
const counts = countKinds([...changes, ...turn.files]);
@@ -597,9 +597,9 @@ function ChangeSet({ turn, until }: { turn: AgentTurn; until: HistoryMark | null
* edits the person made in between — so its header would keep growing while it
* sat there finished.
*/
-function changeCounts(turn: AgentTurn, until: HistoryMark | null): ChangeCounts | null {
+function changeCounts(turn: AgentTurn): ChangeCounts | null {
const mark = turn.mark as HistoryMark | null;
- const entities = mark ? EditorHistory.changesSince(mark, until) : [];
+ const entities = mark ? EditorHistory.changesSince(mark, turn.endMark as HistoryMark | null) : [];
return countKinds([...entities, ...turn.files]);
}
@@ -643,12 +643,10 @@ function Elapsed({ from, to, className }: { from: number; to: number | null; cla
* finished run in the conversation re-rendered — and re-read the undo stack —
* on every token of the newest one.
*/
-const Turn = memo(function Turn({ turn, isLast, running, until }: {
+const Turn = memo(function Turn({ turn, isLast, running }: {
turn: AgentTurn;
isLast: boolean;
running: boolean;
- /** Where the NEXT run started, so this one counts only its own steps. */
- until: HistoryMark | null;
}) {
// A finished run folds to its header: the stat line already IS the summary, so
// the body becomes detail you ask for rather than detail you scroll past.
@@ -661,7 +659,7 @@ const Turn = memo(function Turn({ turn, isLast, running, until }: {
useSyncExternalStore(EditorHistory.subscribe, EditorHistory.getVersion);
const tokens = turn.inputTokens + turn.outputTokens;
- const counts = changeCounts(turn, until);
+ const counts = changeCounts(turn);
const empty = turn.entries.length === 0;
return (
<div className={`ag-turn${folded ? ' folded' : ''}${isLast ? ' current' : ''}`}>
@@ -761,7 +759,7 @@ const Turn = memo(function Turn({ turn, isLast, running, until }: {
<ArrowRight size={13} strokeWidth={2} />{t('agent.continue')}
</button>
)}
- {turn.reason !== null && <ChangeSet turn={turn} until={until} />}
+ {turn.reason !== null && <ChangeSet turn={turn} />}
</div>
</Fold>
</div>
@@ -1383,7 +1381,6 @@ export function AgentPanel({ docked }: { docked?: boolean }) {
turn={turn}
isLast={i === turns.length - 1}
running={status.phase !== 'idle'}
- until={(turns[i + 1]?.mark as HistoryMark | undefined) ?? null}
/>
))}
{/* Held until the run ends. Shown rather than merely promised: a message
diff --git a/desktop/src/engine/EditorHistory.ts b/desktop/src/engine/EditorHistory.ts
index 5108bfdc8..4f3b1ff0b 100644
--- a/desktop/src/engine/EditorHistory.ts
+++ b/desktop/src/engine/EditorHistory.ts
@@ -94,6 +94,20 @@ export interface HistoryMark {
readonly seq: number;
}
+/** One step as the History panel reads it. */
+export interface HistoryStep {
+ id: number;
+ label: string;
+ /** Owning document: null = the scene, else an AssetDocument docId. */
+ doc: string | null;
+ changes: readonly HistoryChange[];
+ /** Taken back — still on the timeline, and still somewhere to go forward to. */
+ undone: boolean;
+}
+
+const step = (e: HistoryEntry, undone: boolean): HistoryStep =>
+ ({ id: e.id, label: e.label, doc: e.doc, changes: e.changes, undone });
+
export class EditorHistoryImpl {
private readonly undoStack: HistoryEntry[] = [];
private readonly redoStack: HistoryEntry[] = [];
@@ -256,6 +270,27 @@ export class EditorHistoryImpl {
return { seq: this.seq };
}
+ /**
+ * The whole timeline oldest first, undone steps included and flagged — what
+ * the History panel draws. `id` addresses a row across a re-render, and
+ * against a mark's `seq` it sorts a run's steps from the rest. Undone steps
+ * stay: forward is a place you can go, and dropping them makes this a list.
+ */
+ list(): readonly HistoryStep[] {
+ const done = this.undoStack.map((e) => step(e, false));
+ // The redo stack is LIFO, so its reverse is chronological — the next step
+ // to redo sits on top and is the OLDEST of the undone ones.
+ const undone = [...this.redoStack].reverse().map((e) => step(e, true));
+ return [...done, ...undone];
+ }
+
+ /** Undo/redo until the stack's head is `id` — clicking a row in the panel.
+ * A row that is neither on the stack nor in the redo pile is a no-op. */
+ goTo(id: number): void {
+ while (this.undoStack.length && this.undoStack[this.undoStack.length - 1].id > id) this.undo();
+ while (this.redoStack.length && this.redoStack[this.redoStack.length - 1].id <= id) this.redo();
+ }
+
/**
* Steps still on the stack that were recorded after `mark`. Zero means the
* turn changed nothing (or its steps were already undone), which is what the
diff --git a/desktop/src/engine/historyGroups.ts b/desktop/src/engine/historyGroups.ts
new file mode 100644
index 000000000..49ceb9946
--- /dev/null
+++ b/desktop/src/engine/historyGroups.ts
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file historyGroups.ts
+ * @brief The undo timeline as the History panel shows it: an agent turn is one
+ * collapsible row, not the thirty-eight steps it took.
+ *
+ * A turn owns the steps recorded between its own two checkpoints, plus the
+ * project files its transaction captured. Both are needed: a turn that only
+ * wrote files has no steps at all, and one that only edited the scene has no
+ * files, and either alone would leave a turn invisible in the panel.
+ *
+ * Pure — it takes the two lists and returns rows. The panel renders them, and
+ * this is where "what belongs to which turn" can be tested without a viewport.
+ */
+import type { HistoryChange, HistoryMark, HistoryStep } from './EditorHistory';
+import type { AgentTurn } from '@/store/AgentStore';
+import type { FileChange } from '../../electron/agent/types';
+
+/** A step the person took by hand. */
+export interface StepRow {
+ kind: 'step';
+ step: HistoryStep;
+}
+
+/** One agent turn, and everything it left behind. */
+export interface TurnRow {
+ kind: 'turn';
+ /** The turn's session index — stable across re-renders, so React keys are. */
+ id: number;
+ prompt: string;
+ steps: HistoryStep[];
+ files: readonly FileChange[];
+ /** The transaction its files came from, for the Revert. Null when none was
+ * open, in which case the files list is empty too. */
+ tx: string | null;
+ mark: HistoryMark | null;
+ /** Where the turn's own work ended — the upper bound of its window. */
+ endSeq: number;
+ /**
+ * Whether reverting this turn would take back only ITSELF. The stack is
+ * linear, so undoing to a mark takes back everything recorded after it —
+ * a later turn, or the person's own work since. Only the newest group with
+ * nothing past it can honestly offer the gesture.
+ */
+ revertable: boolean;
+ /** Every step in it has been undone — the whole row reads as taken back. */
+ undone: boolean;
+}
+
+export type HistoryRow = StepRow | TurnRow;
+
+/**
+ * Fold `steps` into rows, attributing each to the turn whose window it falls in.
+ *
+ * `turns` must be in conversation order; a turn with no mark (one that failed
+ * before taking its checkpoint) owns nothing and appears only if it wrote files.
+ */
+export function historyRows(
+ steps: readonly HistoryStep[],
+ turns: readonly AgentTurn[],
+): HistoryRow[] {
+ // A turn owns what it recorded between its OWN two checkpoints. Bounded by
+ // the next run's start, the newest — which has no next — claimed every edit
+ // the person made after it, Revert included.
+ const windows = turns
+ .map((turn) => ({
+ turn,
+ from: (turn.mark as HistoryMark | null)?.seq ?? null,
+ until: (turn.endMark as HistoryMark | null)?.seq ?? null,
+ }))
+ .filter((w): w is { turn: AgentTurn; from: number; until: number } =>
+ w.from !== null && w.until !== null);
+
+ 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);
+ if (!w) {
+ rows.push({ kind: 'step', step });
+ continue;
+ }
+ // The turn takes its place at its FIRST step, so a run sits where it ran
+ // rather than at the end of the list.
+ let row = claimed.get(w.turn.id);
+ if (!row) {
+ row = turnRow(w.turn, w.until);
+ claimed.set(w.turn.id, row);
+ rows.push(row);
+ }
+ row.steps.push(step);
+ }
+
+ // A turn that recorded no steps still has its files to show — the case a
+ // steps-only reading of a turn missed entirely.
+ for (const w of windows) {
+ if (!claimed.has(w.turn.id) && w.turn.files.length > 0) {
+ const row = turnRow(w.turn, w.until);
+ claimed.set(w.turn.id, row);
+ rows.push(row);
+ }
+ }
+
+ 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);
+ }
+ return rows;
+}
+
+/** `steps` fills in as the walk goes; `revertable` cannot be known until every
+ * row exists, so both are settled after the fact. */
+function turnRow(turn: AgentTurn, endSeq: number): TurnRow {
+ return {
+ kind: 'turn',
+ id: turn.id,
+ prompt: turn.prompt,
+ steps: [],
+ files: turn.files,
+ tx: turn.tx,
+ mark: turn.mark as HistoryMark | null,
+ endSeq,
+ revertable: false,
+ undone: false,
+ };
+}
+
+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 }
+
+export function tally(
+ changes: readonly Pick<HistoryChange, 'kind'>[],
+ files: readonly FileChange[] = [],
+): ChangeTally {
+ const out: ChangeTally = { add: 0, modify: 0, remove: 0 };
+ for (const c of changes) out[c.kind]++;
+ for (const f of files) out[f.kind]++;
+ return out;
+}
+
+/** Every change a turn's steps declared, oldest first. */
+export function turnChanges(row: TurnRow): HistoryChange[] {
+ return row.steps.flatMap((s) => [...s.changes]);
+}
diff --git a/desktop/src/i18n/messages/history.ts b/desktop/src/i18n/messages/history.ts
new file mode 100644
index 000000000..a64c4ae5c
--- /dev/null
+++ b/desktop/src/i18n/messages/history.ts
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file history.ts — the History panel: the undo timeline, with an agent run
+ * folded into one row.
+ */
+import { defineMessages } from './types';
+
+export const historyMessages = defineMessages({
+ 'hist.panelTitle': { en: 'History', zh: '历史' },
+ 'hist.open': { en: 'History', zh: '历史' },
+ 'hist.empty': { en: 'Nothing has happened yet', zh: '还没有任何操作' },
+ 'hist.empty.hint': {
+ en: 'Every edit lands here in order. An agent run folds into one row you can take back whole.',
+ zh: '每一次编辑都会按顺序记在这里。Agent 的一轮会折叠成一条,可以整条撤回。',
+ },
+ 'hist.turn': { en: 'Agent · {prompt}', zh: 'Agent · {prompt}' },
+ // A run whose steps declared nothing still says how many it took, rather
+ // than showing an empty list that reads as "it did nothing".
+ 'hist.turn.silent': {
+ en: '{count} steps, none of which said what they changed',
+ zh: '{count} 步,但都没有声明改了什么',
+ },
+ 'hist.revert': { en: 'Revert', zh: '撤回' },
+ 'hist.revert.why': {
+ en: 'Take the whole run back — the scene edits and the files it wrote.',
+ zh: '整轮撤回 —— 场景改动和它写的文件一起。',
+ },
+});
diff --git a/desktop/src/i18n/messages/index.ts b/desktop/src/i18n/messages/index.ts
index 2e0696980..9305198dd 100644
--- a/desktop/src/i18n/messages/index.ts
+++ b/desktop/src/i18n/messages/index.ts
@@ -41,6 +41,7 @@ import { animatorMessages } from './animator';
import { agentMessages } from './agent';
import { eventMessages } from './events';
import { pluginMessages } from './plugins';
+import { historyMessages } from './history';
/** Every per-area module, for the uniqueness guard in i18n.test.ts. */
export const messageModules = {
@@ -67,6 +68,7 @@ export const messageModules = {
events: eventMessages,
plugins: pluginMessages,
agent: agentMessages,
+ history: historyMessages,
} as const;
export const editorMessages = {
@@ -93,4 +95,5 @@ export const editorMessages = {
...eventMessages,
...pluginMessages,
...agentMessages,
+ ...historyMessages,
} as const;
diff --git a/desktop/src/layout/panelComponents.tsx b/desktop/src/layout/panelComponents.tsx
index 584a7a852..7f7bf0295 100644
--- a/desktop/src/layout/panelComponents.tsx
+++ b/desktop/src/layout/panelComponents.tsx
@@ -32,6 +32,7 @@ import { AnimatorEditor } from '@/panels/AnimatorEditor';
import { BtTreeEditor } from '@/panels/BtTreeEditor';
import { ProfilerPanel } from '@/panels/ProfilerPanel';
import { PluginsPanel } from '@/panels/PluginsPanel';
+import { HistoryPanel } from '@/panels/HistoryPanel';
import { AgentPanel } from '@/components/AgentDrawer';
/** What a panel renderer is handed: its live panel id and dockview params. */
@@ -83,6 +84,7 @@ export const PANEL_RENDERERS: Record<string, PanelRenderer> = {
behaviortree: () => <BtTreeEditor />,
profiler: () => <ProfilerPanel />,
plugins: () => <PluginsPanel />,
+ history: () => <HistoryPanel />,
agent: () => <AgentPanel docked />,
game: () => <GamePanel />,
gameClient: ({ params }) => <GameClientPanel realmId={Number(params?.realmId ?? 0)} />,
diff --git a/desktop/src/layout/panels.ts b/desktop/src/layout/panels.ts
index 0361faf51..f87d20d83 100644
--- a/desktop/src/layout/panels.ts
+++ b/desktop/src/layout/panels.ts
@@ -99,6 +99,10 @@ const BOTTOM: PanelDef[] = [
// Opened on demand rather than ensured: most sessions have no plugins, and a
// permanent tab for an empty list is noise.
{ id: 'plugins', title: () => t('plug.panelTitle'), placement: 'bottom', refs: ['log', 'content'] },
+ // Not ensured either: it answers a question you go looking for, and a
+ // permanent tab beside the log would compete with the one you read while
+ // working. Reached from Edit and from the agent's checkpoint bar.
+ { id: 'history', title: () => t('hist.panelTitle'), placement: 'side-right', width: 320 },
// The agent docks like everything else — draggable, tabbable beside Details,
// poppable to a second screen. The drawer over the workspace is the SAME
// panel summoned, exactly as the Content Browser has both. Not ensured: a
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index be484a6c5..f2a25be72 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -39,6 +39,7 @@ import './theme/settings.css';
import './theme/agent.css';
import './theme/launcher.css';
import './theme/plugins.css';
+import './theme/history.css';
import { App } from './App';
import { ProjectStore } from './project/ProjectStore';
import { AssetRegistry } from './project/AssetRegistry';
diff --git a/desktop/src/panels/HistoryPanel.tsx b/desktop/src/panels/HistoryPanel.tsx
new file mode 100644
index 000000000..8997330ba
--- /dev/null
+++ b/desktop/src/panels/HistoryPanel.tsx
@@ -0,0 +1,169 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file HistoryPanel.tsx
+ * @brief Everything that has happened to this project, in order — with an
+ * agent turn as ONE row rather than the thirty-eight steps it took.
+ *
+ * The panel exists for the question "what did that do, and can I get out of
+ * it". A run scattered across forty identical-looking rows answers neither: you
+ * cannot see where it began, and taking it back means holding Ctrl+Z and hoping.
+ * Folded, the run states what was asked and lists what it left behind — both
+ * halves, entities and files — with one button that takes the lot.
+ *
+ * Oldest at the top, so the timeline reads downward and the place you are now
+ * is the bottom. Undone steps stay, greyed: forward is a place you can go, and
+ * a list that dropped them would be a list of the past rather than a timeline.
+ */
+import { useRef, useLayoutEffect, useState, useSyncExternalStore } from 'react';
+import { ChevronRight, Undo2, Bot, File as FileIcon, History as HistoryIcon } from 'lucide-react';
+import { EditorHistory, type HistoryChange, type HistoryMark } from '@/engine/EditorHistory';
+import { historyRows, tally, turnChanges, type HistoryRow, type TurnRow } from '@/engine/historyGroups';
+import { useAgent, dismissCheckpoint } from '@/store/AgentStore';
+import { useSelection } from '@/store/selectionStore';
+import { EmptyState } from '@/components/EmptyState';
+import { Toasts } from '@/store/Toasts';
+import { t } from '@/i18n';
+
+export function HistoryPanel() {
+ useSyncExternalStore(EditorHistory.subscribe, EditorHistory.getVersion);
+ const turns = useAgent((s) => s.turns);
+ const rows = historyRows(EditorHistory.list(), turns);
+
+ // The bottom is where you are. A panel that stayed put while a run recorded
+ // forty steps would leave the newest work out of sight for the whole run.
+ const end = useRef<HTMLDivElement>(null);
+ useLayoutEffect(() => { end.current?.scrollIntoView({ block: 'nearest' }); }, [rows.length]);
+
+ if (rows.length === 0) {
+ return <EmptyState icon={HistoryIcon} title={t('hist.empty')} hint={t('hist.empty.hint')} />;
+ }
+ return (
+ <div className="hist">
+ {rows.map((row) => <Row key={rowKey(row)} row={row} />)}
+ <div ref={end} />
+ </div>
+ );
+}
+
+const rowKey = (row: HistoryRow): string =>
+ (row.kind === 'turn' ? `t${row.id}` : `s${row.step.id}`);
+
+function Row({ row }: { row: HistoryRow }) {
+ if (row.kind === 'turn') return <TurnGroup row={row} />;
+ const { step } = row;
+ return (
+ <button
+ type="button"
+ className={`hist-row${step.undone ? ' undone' : ''}`}
+ onClick={() => EditorHistory.goTo(step.id)}
+ >
+ <span className="hist-lbl">{step.label}</span>
+ <Tally counts={tally(step.changes)} />
+ </button>
+ );
+}
+
+function TurnGroup({ row }: { row: TurnRow }) {
+ const [open, setOpen] = useState(false);
+ const [reverting, setReverting] = useState(false);
+ const changes = turnChanges(row);
+ const counts = tally(changes, row.files);
+
+ 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');
+ }
+ } finally {
+ setReverting(false);
+ }
+ };
+
+ return (
+ <div className={`hist-turn${open ? ' open' : ''}${row.undone ? ' undone' : ''}`}>
+ <div className="hist-turn-h">
+ <button type="button" className="hist-turn-t" onClick={() => setOpen((o) => !o)}>
+ <ChevronRight size={11} strokeWidth={2} className="hist-car" />
+ <Bot size={12} strokeWidth={1.8} className="hist-bot" />
+ <span className="hist-lbl">{t('hist.turn', { prompt: row.prompt })}</span>
+ <Tally counts={counts} />
+ </button>
+ {/* Only on the newest run. The stack is linear, so an older one's revert
+ would reach past itself — historyGroups decides, this renders. */}
+ {row.revertable && (
+ <button
+ type="button"
+ className="hist-revert"
+ disabled={reverting}
+ title={t('hist.revert.why')}
+ onClick={() => void revert()}
+ >
+ <Undo2 size={11} strokeWidth={2} />{t('hist.revert')}
+ </button>
+ )}
+ </div>
+ {open && (
+ <div className="hist-turn-l">
+ {row.files.map((f) => (
+ <button
+ type="button"
+ className={`hist-chg k-${f.kind}`}
+ key={`f:${f.path}`}
+ title={f.path}
+ onClick={() => useSelection.getState().selectAsset(f.path)}
+ >
+ <span className="hist-sig">{SIGIL[f.kind]}</span>
+ <FileIcon size={10} strokeWidth={1.8} className="hist-ico" />
+ <span className="hist-what">{f.path}</span>
+ {f.unjournaled && <span className="hist-note">{t('agent.changes.tooBig')}</span>}
+ </button>
+ ))}
+ {changes.map((c, i) => (
+ <button
+ type="button"
+ className={`hist-chg k-${c.kind}`}
+ key={`e:${i}`}
+ onClick={() => useSelection.getState().select(c.entity)}
+ >
+ <span className="hist-sig">{SIGIL[c.kind]}</span>
+ <span className="hist-what">{describe(c)}</span>
+ </button>
+ ))}
+ {changes.length === 0 && row.files.length === 0 && (
+ <div className="hist-chg quiet">{t('hist.turn.silent', { count: row.steps.length })}</div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+const SIGIL: Record<'add' | 'modify' | 'remove', string> = { add: '+', modify: '~', remove: '−' };
+
+/** An entity change as one line: the name it had, then what about it changed. */
+function describe(c: HistoryChange): string {
+ const what = [c.component, c.field].filter(Boolean).join('.');
+ return what ? `${c.name} · ${what}` : c.name;
+}
+
+function Tally({ counts }: { counts: { add: number; modify: number; remove: number } }) {
+ if (counts.add + counts.modify + counts.remove === 0) return null;
+ return (
+ <span className="hist-tally">
+ {counts.add > 0 && <span className="k-add">+{counts.add}</span>}
+ {counts.modify > 0 && <span className="k-modify">~{counts.modify}</span>}
+ {counts.remove > 0 && <span className="k-remove">−{counts.remove}</span>}
+ </span>
+ );
+}
diff --git a/desktop/src/store/AgentStore.ts b/desktop/src/store/AgentStore.ts
index fd7b25fc2..56a7599cc 100644
--- a/desktop/src/store/AgentStore.ts
+++ b/desktop/src/store/AgentStore.ts
@@ -140,6 +140,10 @@ export interface AgentTurn {
steps: number;
/** Where that Undo would go back to (EditorHistory.undoToMark). */
mark: unknown | null;
+ /** Where the turn's own work ended. What separates it from the edits the
+ * person makes next — a start mark alone cannot, so the newest run would
+ * claim every one of them. */
+ endMark: unknown | null;
/**
* The turn's file-journal transaction and the project paths it captured — the
* other half of what a revert takes back. A turn that only wrote files ends
@@ -491,6 +495,7 @@ export function applyAgentEvent(turns: readonly AgentTurn[], event: AgentEvent):
context: null,
steps: 0,
mark: null,
+ endMark: null,
tx: null,
files: [],
reason: null,
@@ -585,6 +590,7 @@ export function applyAgentEvent(turns: readonly AgentTurn[], event: AgentEvent):
reason: event.reason,
steps: event.steps,
mark: event.mark,
+ endMark: event.endMark,
tx: event.tx,
files: event.files,
endedAt: Date.now(),
diff --git a/desktop/src/theme/history.css b/desktop/src/theme/history.css
new file mode 100644
index 000000000..01502c56f
--- /dev/null
+++ b/desktop/src/theme/history.css
@@ -0,0 +1,97 @@
+/* SPDX-License-Identifier: Apache-2.0
+ SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+
+ The History panel. A run reads as ONE thing — a rule down its left edge holds
+ its rows together — while a hand edit is a bare line, so the eye separates
+ "the agent did this" from "I did this" without reading a word. */
+
+.hist {
+ height: 100%;
+ overflow: auto;
+ padding: 4px 0 10px;
+ font: var(--fs-xs) var(--font-ui);
+}
+
+.hist-row,
+.hist-turn-t {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ min-width: 0;
+ padding: 4px 10px;
+ background: none;
+ border: 0;
+ color: var(--text);
+ text-align: left;
+ cursor: pointer;
+}
+/* Shrinkable, so a long prompt clips itself rather than pushing the Revert out
+ of the panel — the button is the reason the row is worth having. */
+.hist-turn-t { flex: 1 1 auto; width: auto; }
+.hist-row:hover, .hist-turn-t:hover { background: var(--hover); }
+.hist-lbl { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+
+/* An undone step is still on the timeline — dimmed, not struck: it is somewhere
+ you can go forward to, not a mistake. */
+.hist-row.undone, .hist-turn.undone .hist-turn-t { color: var(--text-faint); }
+.hist-row.undone .hist-tally, .hist-turn.undone .hist-tally { opacity: 0.45; }
+
+.hist-tally {
+ display: flex;
+ gap: 6px;
+ font: var(--fs-2xs) var(--font-mono);
+ white-space: nowrap;
+}
+.hist-tally .k-add, .hist-chg.k-add .hist-sig { color: var(--run); }
+.hist-tally .k-modify, .hist-chg.k-modify .hist-sig { color: var(--warn); }
+.hist-tally .k-remove, .hist-chg.k-remove .hist-sig { color: var(--error); }
+
+.hist-turn {
+ margin: 3px 0;
+ border-left: 2px solid var(--border);
+}
+.hist-turn.open { border-left-color: var(--text-dim); }
+.hist-turn-h { display: flex; align-items: center; }
+.hist-bot { color: var(--text-dim); flex: none; }
+.hist-car { color: var(--text-faint); flex: none; transition: transform var(--t) var(--e-out); }
+.hist-turn.open .hist-car { transform: rotate(90deg); }
+
+.hist-revert {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ flex: none;
+ margin-right: 8px;
+ padding: 2px 7px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: none;
+ color: var(--text-dim);
+ font: var(--fs-2xs) var(--font-ui);
+ cursor: pointer;
+}
+.hist-revert:hover:not(:disabled) { color: var(--text-hi); border-color: var(--text-dim); }
+.hist-revert:disabled { opacity: 0.5; cursor: default; }
+
+.hist-turn-l { padding: 1px 0 5px; }
+.hist-chg {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ width: 100%;
+ padding: 3px 10px 3px 26px;
+ background: none;
+ border: 0;
+ color: var(--text-dim);
+ text-align: left;
+ font: var(--fs-2xs) var(--font-mono);
+ cursor: pointer;
+}
+.hist-chg:hover { background: var(--hover); color: var(--text); }
+.hist-chg.quiet { color: var(--text-faint); cursor: default; font-family: var(--font-ui); }
+.hist-chg.quiet:hover { background: none; }
+.hist-sig { width: 8px; text-align: center; font-weight: 600; flex: none; }
+.hist-ico { color: var(--text-faint); flex: none; }
+.hist-what { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.hist-note { color: var(--warn); flex: none; }
diff --git a/desktop/tests/agent-host.test.ts b/desktop/tests/agent-host.test.ts
index 2bab6f877..7c7f542b6 100644
--- a/desktop/tests/agent-host.test.ts
+++ b/desktop/tests/agent-host.test.ts
@@ -393,7 +393,7 @@ describe('a conversation that outlives the session', () => {
endpoint: 'fake',
events: [
{ type: 'turn_start', prompt: 'yesterday', model: 'fake-model', index: 0 },
- { type: 'turn_end', steps: 0, mark: null, tx: null, files: [], reason: 'end_turn' },
+ { type: 'turn_end', steps: 0, mark: null, endMark: null, tx: null, files: [], reason: 'end_turn' },
],
memory: { asked: ['yesterday'] },
};
diff --git a/desktop/tests/agent-kernel.test.ts b/desktop/tests/agent-kernel.test.ts
index 61ad477cc..8ca55e994 100644
--- a/desktop/tests/agent-kernel.test.ts
+++ b/desktop/tests/agent-kernel.test.ts
@@ -91,7 +91,7 @@ describe('the agent turn', () => {
// what was asked, and the point an Undo would go back to.
expect(events.at(0)).toEqual({ type: 'turn_start', prompt: 'hi', model: 'fake-model', index: 0 });
expect(events.at(-1)).toEqual({
- type: 'turn_end', steps: 3, mark: { seq: 7 }, tx: null, files: [], reason: 'end_turn',
+ type: 'turn_end', steps: 3, mark: { seq: 7 }, endMark: { seq: 7 }, tx: null, files: [], reason: 'end_turn',
});
});
diff --git a/desktop/tests/agent-queue.test.ts b/desktop/tests/agent-queue.test.ts
index b1bbceee7..35f8643f2 100644
--- a/desktop/tests/agent-queue.test.ts
+++ b/desktop/tests/agent-queue.test.ts
@@ -114,7 +114,7 @@ describe('messages typed while a turn runs', () => {
describe('asking a run again', () => {
const turn = (id: number, prompt: string) => ({
id, prompt, model: 'm', entries: [], inputTokens: 0, outputTokens: 0, context: null,
- steps: 0, mark: null, tx: null, files: [], reason: 'end_turn' as const, startedAt: 0, endedAt: 1,
+ steps: 0, mark: null, endMark: null, tx: null, files: [], reason: 'end_turn' as const, startedAt: 0, endedAt: 1,
});
beforeEach(() => {
diff --git a/desktop/tests/agent-replay.test.ts b/desktop/tests/agent-replay.test.ts
index 97bb9e7a6..b4407a007 100644
--- a/desktop/tests/agent-replay.test.ts
+++ b/desktop/tests/agent-replay.test.ts
@@ -21,10 +21,10 @@ const status: AgentStatus =
const conversation = (from = 0): AgentEvent[] => [
{ type: 'turn_start', prompt: 'add a pause menu', model: 'opus-5', index: from },
{ type: 'text', delta: 'Building it.' },
- { type: 'turn_end', steps: 7, mark: { seq: 1 }, tx: null, files: [], reason: 'end_turn' },
+ { type: 'turn_end', steps: 7, mark: { seq: 1 }, endMark: null, tx: null, files: [], reason: 'end_turn' },
{ type: 'turn_start', prompt: 'bigger buttons', model: 'opus-5', index: from + 1 },
{ type: 'text', delta: 'Done.' },
- { type: 'turn_end', steps: 3, mark: { seq: 2 }, tx: null, files: [], reason: 'end_turn' },
+ { type: 'turn_end', steps: 3, mark: { seq: 2 }, endMark: null, tx: null, files: [], reason: 'end_turn' },
];
let transcript: AgentEvent[];
diff --git a/desktop/tests/agent-revert-scope.test.ts b/desktop/tests/agent-revert-scope.test.ts
index 5a37bfe0a..e73afb880 100644
--- a/desktop/tests/agent-revert-scope.test.ts
+++ b/desktop/tests/agent-revert-scope.test.ts
@@ -14,7 +14,7 @@ import type { FileChange } from '../electron/agent/types';
const turn = (over: Partial<AgentTurn>): AgentTurn => ({
id: 0, prompt: 'add a health bar', model: 'opus-5', entries: [],
inputTokens: 0, outputTokens: 0, context: null,
- steps: 0, mark: { seq: 1 }, tx: null, files: [],
+ steps: 0, mark: { seq: 1 }, endMark: null, tx: null, files: [],
reason: 'end_turn', startedAt: 0, endedAt: 1,
...over,
});
@@ -39,7 +39,7 @@ describe('what a turn offers to take back', () => {
// prefab records no undo steps at all, so the bar never appeared for the work
// undo was least able to reach.
it('offers a turn that only wrote files', () => {
- const scope = revertScope(turn({ steps: 0, tx: 'tx-1', files: [file('src/HealthBar.ts')] }), 0);
+ const scope = revertScope(turn({ steps: 0, endMark: null, tx: 'tx-1', files: [file('src/HealthBar.ts')] }), 0);
expect(scope).toMatchObject({ steps: 0, files: [{ path: 'src/HealthBar.ts' }] });
});
diff --git a/desktop/tests/agent-store.test.ts b/desktop/tests/agent-store.test.ts
index 0692d7f4d..6b59dc9be 100644
--- a/desktop/tests/agent-store.test.ts
+++ b/desktop/tests/agent-store.test.ts
@@ -21,7 +21,7 @@ afterEach(async () => { await rm(root, { recursive: true, force: true }); });
const turn = (index: number, prompt: string): AgentEvent[] => [
{ type: 'turn_start', prompt, model: 'fake-model', index },
{ type: 'text', delta: 'sure' },
- { type: 'turn_end', steps: 1, mark: { seq: index }, tx: null, files: [], reason: 'end_turn' },
+ { type: 'turn_end', steps: 1, mark: { seq: index }, endMark: null, tx: null, files: [], reason: 'end_turn' },
];
const conversation = (over: Partial<Parameters<typeof saveConversation>[1]> = {}) => ({
@@ -63,7 +63,7 @@ describe('keeping a conversation', () => {
const withShot: AgentEvent[] = [
{ type: 'turn_start', prompt: 'look', model: 'm', index: 0 },
{ type: 'tool_end', id: 'c1', ok: true, summary: 'screenshot attached', image: 'data:image/png;base64,AAAA' },
- { type: 'turn_end', steps: 0, mark: null, tx: null, files: [], reason: 'end_turn' },
+ { type: 'turn_end', steps: 0, mark: null, endMark: null, tx: null, files: [], reason: 'end_turn' },
];
await saveConversation(root, conversation({ events: withShot }));
const back = await loadConversation(root, 'abc-123');
diff --git a/desktop/tests/agent-transcript.test.ts b/desktop/tests/agent-transcript.test.ts
index 84d43c28f..c444b35b5 100644
--- a/desktop/tests/agent-transcript.test.ts
+++ b/desktop/tests/agent-transcript.test.ts
@@ -20,7 +20,7 @@ const fold = (...events: AgentEvent[]): AgentTurn[] =>
const started = (prompt = 'add a pause menu', index = 0, model = 'opus-5'): AgentEvent =>
({ type: 'turn_start', prompt, model, index });
const ended = (over: Partial<{ steps: number; mark: unknown; reason: 'end_turn' | 'aborted' | 'error' | 'refusal' }> = {}): AgentEvent =>
- ({ type: 'turn_end', steps: 0, mark: null, tx: null, files: [], reason: 'end_turn', ...over });
+ ({ type: 'turn_end', steps: 0, mark: null, endMark: null, tx: null, files: [], reason: 'end_turn', ...over });
const call = (name: string): ToolCall => ({ id: `c-${name}`, name, input: { a: 1 } });
const tools = (t: AgentTurn): AgentToolEntry[] => t.entries.filter((e): e is AgentToolEntry => e.kind === 'tool');
@@ -300,7 +300,7 @@ describe('which entities a turn touched', () => {
});
const turn = (entries: AgentToolEntry[], id = 0): AgentTurn => ({
id, prompt: 'p', model: 'opus-5', entries, inputTokens: 0, outputTokens: 0, context: null,
- steps: 1, mark: { seq: 1 }, tx: null, files: [], reason: 'end_turn', startedAt: 0, endedAt: 1,
+ steps: 1, mark: { seq: 1 }, endMark: null, tx: null, files: [], reason: 'end_turn', startedAt: 0, endedAt: 1,
});
it('reads the ids out of the argument names the catalog uses', () => {
diff --git a/desktop/tests/editor-history-timeline.test.ts b/desktop/tests/editor-history-timeline.test.ts
new file mode 100644
index 000000000..bed53201c
--- /dev/null
+++ b/desktop/tests/editor-history-timeline.test.ts
@@ -0,0 +1,99 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file EditorHistory.list / goTo — the stack as a timeline someone can read
+ * and click through, rather than only step back along.
+ *
+ * The claim under test is that an undone step is still SOMEWHERE, and that
+ * clicking a row lands exactly there whichever direction it is in. Pure TS.
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import { EditorHistoryImpl } from '@/engine/EditorHistory';
+
+describe('the timeline a panel reads', () => {
+ let h: EditorHistoryImpl;
+ let value: number;
+ beforeEach(() => {
+ h = new EditorHistoryImpl();
+ value = 0;
+ });
+
+ const add = (n: number) => {
+ value += n;
+ h.record(`Add ${n}`, () => { value += n; }, () => { value -= n; });
+ };
+
+ it('lists the steps oldest first, with what each declared', () => {
+ h.describe({ kind: 'add', entity: 3, name: 'Canvas' });
+ add(1);
+ add(2);
+ expect(h.list().map((s) => s.label)).toEqual(['Add 1', 'Add 2']);
+ expect(h.list()[0].changes).toEqual([{ kind: 'add', entity: 3, name: 'Canvas' }]);
+ });
+
+ // Dropping them would make the panel a list of the past. They are places you
+ // can go forward to, and the panel's job is to show that they are there.
+ it('keeps undone steps on the timeline, flagged', () => {
+ add(1);
+ add(2);
+ h.undo();
+ expect(h.list().map((s) => [s.label, s.undone]))
+ .toEqual([['Add 1', false], ['Add 2', true]]);
+ });
+
+ // Reversed twice on the way through: the redo stack is LIFO, so a naive read
+ // would show two undone steps in the wrong order.
+ it('keeps undone steps in the order they happened', () => {
+ add(1);
+ add(2);
+ add(4);
+ h.undo();
+ h.undo();
+ expect(h.list().map((s) => s.label)).toEqual(['Add 1', 'Add 2', 'Add 4']);
+ expect(h.list().map((s) => s.undone)).toEqual([false, true, true]);
+ });
+
+ it('goes back to a row behind the head', () => {
+ add(1);
+ add(2);
+ add(4);
+ const target = h.list()[0].id;
+ h.goTo(target);
+ expect(value).toBe(1);
+ expect(h.list().map((s) => s.undone)).toEqual([false, true, true]);
+ });
+
+ it('goes forward to a row that had been undone', () => {
+ add(1);
+ add(2);
+ add(4);
+ h.goTo(h.list()[0].id);
+ h.goTo(h.list()[2].id);
+ expect(value).toBe(7);
+ expect(h.list().every((s) => !s.undone)).toBe(true);
+ });
+
+ it('lands on the row asked for, not one past it', () => {
+ add(1);
+ add(2);
+ add(4);
+ h.goTo(h.list()[1].id);
+ expect(value).toBe(3);
+ });
+
+ it('does nothing for an id the timeline does not hold', () => {
+ add(1);
+ h.goTo(9999);
+ expect(value).toBe(1);
+ });
+
+ // Everything back: the id before the first step. Reached by clicking the row
+ // above the oldest one is not a thing, so this is what "undo all" resolves to.
+ it('unwinds the whole timeline for an id below the first', () => {
+ add(1);
+ add(2);
+ h.goTo(0);
+ expect(value).toBe(0);
+ expect(h.list().every((s) => s.undone)).toBe(true);
+ });
+});
diff --git a/desktop/tests/editor-mcp-tools.test.ts b/desktop/tests/editor-mcp-tools.test.ts
index b30f35580..9b39b02ce 100644
--- a/desktop/tests/editor-mcp-tools.test.ts
+++ b/desktop/tests/editor-mcp-tools.test.ts
@@ -130,19 +130,31 @@ describe('editor MCP tool registry', () => {
// tool that reaches the FILESYSTEM is on the side undo cannot rescue.
it('every tool declares a tier the gates understand', () => {
for (const t of TOOLS as Array<{ name: string; effect?: string }>) {
- expect(['read', 'undoable', 'irreversible', undefined]).toContain(t.effect);
+ expect(['read', 'undoable', 'journaled', 'irreversible', undefined]).toContain(t.effect);
}
});
- it('anything that touches disk or an external target is irreversible', () => {
+ // The line is drawn where GOING BACK stops working, not where the undo stack
+ // does: a write inside the project is held by the file journal and comes back
+ // with the turn, so it must not be sitting in the tier that stops to ask.
+ it('a write inside the project is journaled', () => {
const onDisk = ['save_scene', 'write_project_file', 'create_asset', 'create_scene_file',
- 'import_assets', 'set_import_settings', 'set_project_physics', 'create_project',
- 'create_prefab_from_entity', 'export_game'];
- for (const name of onDisk) expect(irreversible(toolNamed(name))).toBe(true);
- // The arbitrary-code doors belong here too: their effect is whatever the
- // caller wrote, which no undo step can be assumed to cover.
- expect(irreversible(toolNamed('run_editor_command'))).toBe(true);
- expect(irreversible(toolNamed('play_probe'))).toBe(true);
+ 'import_assets', 'set_import_settings', 'set_project_physics',
+ 'create_prefab_from_entity', 'apply_prefab', 'create_prefab_variant',
+ 'delete_asset', 'save_asset_document'];
+ for (const name of onDisk) {
+ expect([name, toolNamed(name).effect]).toEqual([name, 'journaled']);
+ expect([name, irreversible(toolNamed(name))]).toEqual([name, false]);
+ }
+ });
+
+ it('what leaves the project, or runs code nobody enumerated, stays irreversible', () => {
+ // A new project tree elsewhere and a build output are outside the root the
+ // journal is scoped to; the arbitrary-code doors do whatever the caller
+ // wrote, which no capture can be assumed to cover.
+ for (const name of ['create_project', 'export_game', 'run_editor_command', 'play_probe']) {
+ expect([name, irreversible(toolNamed(name))]).toEqual([name, true]);
+ }
});
it('listTools without write permission omits mutating tools but keeps reads', () => {
@@ -265,7 +277,7 @@ describe('editor MCP tool registry', () => {
const driver = vi.fn() as unknown as { js: ReturnType<typeof vi.fn> } & ((...a: unknown[]) => unknown);
driver.js = vi.fn(async () => ({ docId: 'materialgraph', path: 'fx/fire.esmatgraph', saved: true }));
const save = toolNamed('save_asset_document');
- expect([!!save, irreversible(save)]).toEqual([true, true]); // it writes a file: stop and ask
+ expect([!!save, save.effect]).toEqual([true, 'journaled']); // it writes a file: hold the bytes
const res = await runTool(save, driver, { docId: 'materialgraph' });
expect(driver.js).toHaveBeenCalledWith(expect.stringContaining('saveAssetDocument("materialgraph"'));
@@ -279,7 +291,7 @@ describe('editor MCP tool registry', () => {
const driver = vi.fn() as unknown as { js: ReturnType<typeof vi.fn> } & ((...a: unknown[]) => unknown);
driver.js = vi.fn(async () => ({ path: 'assets/fx/old.esshader', type: 'shader', restoreToken: 't', usages: [] }));
const del = toolNamed('delete_asset');
- expect([!!del, irreversible(del)]).toEqual([true, true]);
+ expect([!!del, del.effect]).toEqual([true, 'journaled']);
await runTool(del, driver, { path: 'assets/fx/old.esshader' });
expect(driver.js).toHaveBeenCalledWith(expect.stringContaining('deleteAsset("assets/fx/old.esshader")'));
});
@@ -404,9 +416,11 @@ describe('the prefab-mode doors', () => {
// The tier is what an in-editor agent gates on, so it has to survive the split
// that matters: rewriting the PREFAB ASSET reaches every instance and outlives
// undo, while re-syncing or detaching THIS instance is an ordinary scene edit.
- it('separates the prefab doors that outlive undo from the ones that do not', () => {
- expect(toolNamed('apply_prefab').effect).toBe('irreversible');
- expect(toolNamed('create_prefab_variant').effect).toBe('irreversible');
+ it('separates the prefab doors that write an asset from the ones that do not', () => {
+ // Rewriting the shared prefab, or writing a variant, touches the file — held
+ // by the journal. Re-syncing or detaching THIS instance is an ordinary edit.
+ expect(toolNamed('apply_prefab').effect).toBe('journaled');
+ expect(toolNamed('create_prefab_variant').effect).toBe('journaled');
expect(toolNamed('revert_prefab').effect).toBe('undoable');
expect(toolNamed('unpack_prefab').effect).toBe('undoable');
});
diff --git a/desktop/tests/history-groups.test.ts b/desktop/tests/history-groups.test.ts
new file mode 100644
index 000000000..d694333f2
--- /dev/null
+++ b/desktop/tests/history-groups.test.ts
@@ -0,0 +1,156 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Which steps belong to which agent turn, and which turn may offer a
+ * one-gesture revert.
+ *
+ * The panel's whole claim is that a run is ONE row. Getting the window wrong
+ * either scatters a turn's work across the timeline or lets one turn swallow
+ * the edits the person made after it — and the second is worse, because the
+ * Revert on that row would then take back work the agent never touched.
+ */
+import { describe, it, expect } from 'vitest';
+import { historyRows, tally, turnChanges, type TurnRow } from '@/engine/historyGroups';
+import type { HistoryStep } from '@/engine/EditorHistory';
+import type { AgentTurn } from '@/store/AgentStore';
+import type { FileChange } from '../electron/agent/types';
+
+const step = (id: number, label = `step ${id}`, undone = false): HistoryStep =>
+ ({ id, label, doc: null, changes: [], undone });
+
+/** A run over the half-open window (from, to] — the two checkpoints it took. */
+const turn = (id: number, from: number, to: number, over: Partial<AgentTurn> = {}): AgentTurn => ({
+ id, prompt: `turn ${id}`, model: 'opus-5', entries: [],
+ inputTokens: 0, outputTokens: 0, context: null,
+ steps: to - from, mark: { seq: from }, endMark: { seq: to }, tx: null, files: [],
+ reason: 'end_turn', startedAt: 0, endedAt: 1,
+ ...over,
+});
+
+const file = (path: string, kind: FileChange['kind'] = 'add'): FileChange =>
+ ({ path, kind, unjournaled: false });
+
+const turns = (rows: ReturnType<typeof historyRows>): TurnRow[] =>
+ rows.filter((r): r is TurnRow => r.kind === 'turn');
+
+describe('folding the timeline into rows', () => {
+ it('leaves hand edits as their own rows', () => {
+ const rows = historyRows([step(1), step(2)], []);
+ expect(rows.map((r) => r.kind)).toEqual(['step', 'step']);
+ });
+
+ it('gathers a turn 38 steps long into one row', () => {
+ const steps = Array.from({ length: 38 }, (_, i) => step(i + 1));
+ const rows = historyRows(steps, [turn(0, 0, 38)]);
+ expect(rows).toHaveLength(1);
+ expect(turns(rows)[0].steps).toHaveLength(38);
+ });
+
+ // The mark is taken BEFORE the turn's first step, so the step recorded at the
+ // mark's own seq belongs to whatever came before it.
+ it('claims steps after its mark, not the one at it', () => {
+ const rows = historyRows([step(1), step(2), step(3)], [turn(0, 1, 3)]);
+ expect(rows[0]).toMatchObject({ kind: 'step', step: { id: 1 } });
+ expect(turns(rows)[0].steps.map((s) => s.id)).toEqual([2, 3]);
+ });
+
+ // The failure that matters: without the upper bound a turn owns everything
+ // after it, so its Revert would reach into the person's later work.
+ it('stops at the next turn, and does not swallow what came between', () => {
+ const rows = historyRows(
+ [step(1), step(2), step(3), step(4), step(5)],
+ [turn(0, 0, 3), turn(1, 3, 5)],
+ );
+ const [first, second] = turns(rows);
+ expect(first.steps.map((s) => s.id)).toEqual([1, 2, 3]);
+ expect(second.steps.map((s) => s.id)).toEqual([4, 5]);
+ });
+
+ it('keeps a hand edit made between two turns out of both', () => {
+ // Turn 0 marked at 0 and recorded step 1; the person then made step 2;
+ // turn 1 marked at 2.
+ const rows = historyRows([step(1), step(2), step(3)], [turn(0, 0, 2), turn(1, 2, 3)]);
+ expect(turns(rows)[0].steps.map((s) => s.id)).toEqual([1, 2]);
+ expect(turns(rows)[1].steps.map((s) => s.id)).toEqual([3]);
+ });
+
+ // Found by looking at the panel: bounded by the NEXT run's start, the newest
+ // run — which has no next — swallowed the edit made right after it, and its
+ // Revert would have taken that back under the agent's name.
+ it('leaves an edit made after the newest run out of it', () => {
+ const rows = historyRows([step(1), step(2), step(3)], [turn(0, 0, 2)]);
+ expect(rows[0].kind).toBe('turn');
+ expect((rows[0] as TurnRow).steps.map((s) => s.id)).toEqual([1, 2]);
+ expect(rows[1]).toMatchObject({ kind: 'step', step: { id: 3 } });
+ });
+
+ it('sits where it ran, not at the end of the list', () => {
+ const rows = historyRows([step(1), step(2), step(3)], [turn(0, 1, 3)]);
+ // step 1 by hand, then the turn — so the turn is the SECOND row.
+ expect(rows[0].kind).toBe('step');
+ expect(rows[1].kind).toBe('turn');
+ expect(rows).toHaveLength(2);
+ });
+
+ // The case a steps-only reading missed entirely: writing a script records no
+ // undo steps, so this turn exists only because of its files.
+ it('shows a turn that only wrote files', () => {
+ const rows = historyRows([], [turn(0, 0, 0, { tx: 'tx-1', files: [file('src/HP.ts')] })]);
+ expect(turns(rows)[0]).toMatchObject({ files: [{ path: 'src/HP.ts' }], tx: 'tx-1' });
+ });
+
+ it('shows nothing for a turn that did neither', () => {
+ expect(historyRows([], [turn(0, 0, 0)])).toEqual([]);
+ });
+
+ it('ignores a turn that never got a mark', () => {
+ const rows = historyRows([step(1)], [turn(0, 0, 1, { mark: null })]);
+ expect(rows.map((r) => r.kind)).toEqual(['step']);
+ });
+});
+
+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', () => {
+ 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]);
+ });
+
+ it('withdraws it once the turn has been undone by hand', () => {
+ const rows = historyRows([step(1, 'a', true)], [turn(0, 0, 1)]);
+ expect(turns(rows)[0]).toMatchObject({ revertable: false, undone: true });
+ });
+
+ 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 });
+ });
+
+ // 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', () => {
+ const rows = historyRows([step(1), step(2)], [turn(0, 0, 1)]);
+ expect(turns(rows)[0].revertable).toBe(false);
+ });
+});
+
+describe('what a row counts', () => {
+ it('adds entity and file changes into one tally', () => {
+ const counts = tally(
+ [{ kind: 'add' }, { kind: 'modify' }, { kind: 'modify' }],
+ [file('a.ts'), file('b.esscene', 'modify'), file('c.png', 'remove')],
+ );
+ expect(counts).toEqual({ add: 2, modify: 3, remove: 1 });
+ });
+
+ it('reads a turn changes oldest first, across its steps', () => {
+ const withChange = (id: number, name: string): HistoryStep => ({
+ ...step(id),
+ changes: [{ kind: 'add', entity: id, name }],
+ });
+ const rows = historyRows([withChange(1, 'Canvas'), withChange(2, 'HPBar')], [turn(0, 0, 2)]);
+ expect(turnChanges(turns(rows)[0]).map((c) => c.name)).toEqual(['Canvas', 'HPBar']);
+ });
+});