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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(agent): one Revert takes back both halves of a turn
esengineed2ca111e555
diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 935c87e35..09559d94b 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -788,6 +788,20 @@ ipcMain.handle('agent:confirm',(_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.+ */+ipcMain.handle('agent:revertFiles', async (_e, txId: string) => {+ const result = await journal.revert(txId);+ const touched = [...result.restored, ...result.failed.map((f) => f.path)];+ if (touched.length) notifyFsChanged(touched);+ return result;+});+/** The user kept the work — drop the held copies. */+ipcMain.handle('agent:keepFiles', (_e, txId: string) => journal.discard(txId));ipcMain.handle('agent:reset', () => agentHost.reset());ipcMain.handle('agent:retry', (_e, n: number, text: string) => agentHost.retry(n, text));// — Saved conversations (agent/store.ts). Project-local, so an unopened projectdiff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex f508840b5..264c58866 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -8,6 +8,7 @@ import type { ScaffoldScriptResult, ScriptKind } from './scriptScaffold';import type { ScanAssetsResult, AssetIndex, IncrementalScanResult } from './assetDb';import type { CookResult } from './cookAssets';import type { ExportGameResult } from './exportGame';+import type { RevertResult } from './fileJournal';import type {PlatformStatus, CreatePlatformResult, PlayableNetworkOption, ProjectPlatformKind,} from './platformCatalog';@@ -129,6 +130,12 @@ 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),+ /** 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. */reset: (): Promise<AgentStatus> => ipcRenderer.invoke('agent:reset'),/** Ask the n-th turn again, discarding it and everything after it. */diff --git a/desktop/src/components/AgentCheckpoint.tsx b/desktop/src/components/AgentCheckpoint.tsxindex 442c39b56..dcb3357d8 100644--- a/desktop/src/components/AgentCheckpoint.tsx+++ b/desktop/src/components/AgentCheckpoint.tsx@@ -5,18 +5,22 @@* @brief The one gesture that takes a whole agent turn back, floating over the* viewport where the result of that turn actually is.*- * It appears only when the turn left steps behind. A bar offering to undo zero- * steps is a claim the user has to disprove by clicking it, and the kernel- * already reports 0 for exactly that reason.+ * A turn can change two things — the document and the project on disk — and this+ * takes back both: `EditorHistory.undoToMark` here, then main's file journal+ * over IPC. Undo runs FIRST so the document is at its pre-turn state before the+ * restored files arrive, which is what lets the reload land without a prompt.*- * The revert runs in this window, not through main: the checkpoint is a mark in- * THIS EditorHistory, and the agent that made the edits deliberately has no tool- * for rolling them back — a model that can undo its own work can undo the user's- * and call it a correction.+ * It appears whenever the turn left EITHER behind. A turn that only wrote files+ * has zero undo steps, and a bar that asked about steps alone offered nothing+ * for exactly the work undo could not reach.+ *+ * The revert runs from this window, not from main: the agent that made the edits+ * deliberately has no tool for rolling them back — a model that can undo its own+ * work can undo the user's and call it a correction.*/-import { useSyncExternalStore } from 'react';-import { Undo2, Check } from 'lucide-react';-import { useAgent, dismissCheckpoint } from '@/store/AgentStore';+import { useState, useSyncExternalStore } from 'react';+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';@@ -25,38 +29,68 @@ import { t } from '@/i18n';export function AgentCheckpoint() {const turns = useAgent((s) => s.turns);const done = useAgent((s) => s.checkpointDone);+ const [reverting, setReverting] = useState(false);// Re-read across every edit: what an Undo would now take back changes as the// user keeps working, and the bar has to say so before they press it.const version = useSyncExternalStore(EditorHistory.subscribe, EditorHistory.getVersion);const last = turns[turns.length - 1];- if (!last || last.reason === null || last.steps === 0 || done === last.id) return null;+ if (!last || done === last.id) return null;const mark = last.mark as HistoryMark | null;- if (!mark) return null;-- // More steps on the stack than the turn recorded means the user has edited- // since. Undo would take those back too, so say so rather than quietly doing it.void version;- const now = EditorHistory.stepsSince(mark);- const stale = now > last.steps;+ const scope = revertScope(last, mark ? EditorHistory.stepsSince(mark) : 0);+ if (!scope) return null;+ const { files, stale, stranded } = scope;++ 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;+ 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');+ }+ } finally {+ setReverting(false);+ }+ };++ const keep = (): void => {+ dismissCheckpoint(last.id);+ if (last.tx) void window.estella?.agent?.keepFiles?.(last.tx);+ };return (<div className={`ag-cp${stale ? ' stale' : ''}`}><span className="ag-cp-what">{last.prompt}</span>- <span className="ag-cp-stat">{t('agent.checkpoint.steps', { count: last.steps })}</span>+ <span className="ag-cp-stat">+ {scope.steps > 0 && t('agent.checkpoint.steps', { count: scope.steps })}+ {scope.steps > 0 && files.length > 0 && ' · '}+ {files.length > 0 && t('agent.checkpoint.files', { count: files.length })}+ </span>{stale && <span className="ag-cp-stale">{t('agent.checkpoint.stale')}</span>}+ {stranded.length > 0 && (+ <span className="ag-cp-stale" title={stranded.map((f) => f.path).join('\n')}>+ {t('agent.checkpoint.tooBig', { count: stranded.length })}+ </span>+ )}<span className="ag-cp-acts">- <button- type="button"- onClick={() => {- const undone = EditorHistory.undoToMark(mark);- dismissCheckpoint(last.id);- Toasts.push(t('agent.checkpoint.undone', { count: undone }), 'info');- }}- >- <Undo2 size={13} strokeWidth={1.9} />{t('agent.checkpoint.undo')}+ <button type="button" disabled={reverting} onClick={() => void revert()}>+ {reverting+ ? <Loader size={13} strokeWidth={1.9} className="ag-spin" />+ : <Undo2 size={13} strokeWidth={1.9} />}+ {t('agent.checkpoint.undo')}</button>- <button type="button" className="keep" onClick={() => dismissCheckpoint(last.id)}>+ <button type="button" className="keep" disabled={reverting} onClick={keep}><Check size={13} strokeWidth={2} />{t('agent.checkpoint.keep')}</button></span>diff --git a/desktop/src/components/AgentDrawer.tsx b/desktop/src/components/AgentDrawer.tsxindex 1645f3271..09f0d6101 100644--- a/desktop/src/components/AgentDrawer.tsx+++ b/desktop/src/components/AgentDrawer.tsx@@ -518,19 +518,19 @@ function Skeleton() {* What the turn actually changed — the work product of a run, so it gets* first-class presentation rather than a popover hung off the undo bar.*- * Read from EditorHistory rather than from the tool calls: the calls say what- * was ASKED for, and the history says what the scene now differs by. Steps that- * declared nothing contribute nothing, so this is a floor — which is why an- * empty one renders nothing at all rather than "no changes".+ * Both halves it could have touched, in one list: entities from EditorHistory,+ * files from the turn's journal transaction. Neither re-reads the tool calls —+ * 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 }) {const [open, setOpen] = useState(true);useSyncExternalStore(EditorHistory.subscribe, EditorHistory.getVersion);const mark = turn.mark as HistoryMark | null;const changes = mark ? EditorHistory.changesSince(mark, until) : [];- // Counted from the list already read rather than by walking the stack a+ // Counted from the lists already read rather than by walking the stack a// second time for the same window.- const counts = countKinds(changes);+ const counts = countKinds([...changes, ...turn.files]);if (!counts) return null;return (<div className={`ag-changes${open ? ' open' : ''}`}>@@ -544,6 +544,22 @@ function ChangeSet({ turn, until }: { turn: AgentTurn; until: HistoryMark | null</button><Fold open={open}><div className="ag-changes-l">+ {turn.files.map((f) => (+ <div+ className={`ag-chg ag-chg--${f.kind} file`}+ key={`f:${f.path}`}+ onClick={() => useSelection.getState().selectAsset(f.path)}+ >+ <span className="ag-chg-s">{f.kind === 'add' ? '+' : f.kind === 'remove' ? '−' : '~'}</span>+ <span className="ag-chg-p" title={f.path}>+ <FileIcon size={10} strokeWidth={1.8} className="ag-chg-i" />+ {f.path}+ </span>+ {/* Named on the row that claims to be revertible, because that row+ is the whole basis for pressing Undo. */}+ {f.unjournaled && <span className="ag-chg-v ag-mod">{t('agent.changes.tooBig')}</span>}+ </div>+ ))}{changes.map((c, i) => (<divclassName={`ag-chg ag-chg--${c.kind}`}@@ -583,7 +599,8 @@ function ChangeSet({ turn, until }: { turn: AgentTurn; until: HistoryMark | null*/function changeCounts(turn: AgentTurn, until: HistoryMark | null): ChangeCounts | null {const mark = turn.mark as HistoryMark | null;- return mark ? countKinds(EditorHistory.changesSince(mark, until)) : null;+ const entities = mark ? EditorHistory.changesSince(mark, until) : [];+ return countKinds([...entities, ...turn.files]);}interface ChangeCounts { add: number; modify: number; remove: number }diff --git a/desktop/src/i18n/messages/agent.ts b/desktop/src/i18n/messages/agent.tsindex feacbd431..2be1d5b18 100644--- a/desktop/src/i18n/messages/agent.ts+++ b/desktop/src/i18n/messages/agent.ts@@ -151,6 +151,7 @@ export const agentMessages = defineMessages({'agent.turn.queuedMessage': { en: 'Queued: {text}', zh: '已排队:{text}' },'agent.copy': { en: 'Copy', zh: '复制' },'agent.changes': { en: 'What changed', zh: '改动集' },+ 'agent.changes.tooBig': { en: 'too large to restore', zh: '太大,收不回来' },'agent.reask.label': { en: 'Ask this again', zh: '重新提问' },'agent.reask.go': { en: 'Ask again', zh: '重新提问' },'agent.reask.cancel': { en: 'Cancel', zh: '取消' },@@ -213,11 +214,27 @@ export const agentMessages = defineMessages({'agent.checkpoint.undo': { en: 'Undo', zh: '撤销' },'agent.checkpoint.keep': { en: 'Keep', zh: '保留' },'agent.checkpoint.steps': { en: '{count} steps', zh: '{count} 步' },- 'agent.checkpoint.undone': { en: 'Took back this turn · {count} steps', zh: '已撤销这一轮 · {count} 步' },+ 'agent.checkpoint.files': { en: '{count} files', zh: '{count} 个文件' },+ 'agent.checkpoint.undone': {+ en: 'Took back this turn · {count} steps, {files} files',+ zh: '已撤销这一轮 · {count} 步、{files} 个文件',+ },'agent.checkpoint.stale': {en: 'You have edited since — Undo would take those back too.',zh: '之后你自己编辑过 —— 撤销会连那些一起退回。',},+ 'agent.checkpoint.tooBig': {+ en: '{count} too large to restore',+ zh: '{count} 个太大,收不回来',+ },+ 'agent.checkpoint.stranded': {+ en: 'Left as the turn wrote them (too large to hold): {paths}',+ zh: '这些保持了本轮写入的状态(太大,没留备份):{paths}',+ },+ 'agent.checkpoint.failed': {+ en: 'Could not restore {path} — {error}',+ zh: '无法还原 {path} —— {error}',+ },// — The status-bar segment —'agent.status.running': { en: 'Agent is working', zh: 'Agent 正在干活' },diff --git a/desktop/src/store/AgentStore.ts b/desktop/src/store/AgentStore.tsindex b6ba60769..fd7b25fc2 100644--- a/desktop/src/store/AgentStore.ts+++ b/desktop/src/store/AgentStore.ts@@ -394,6 +394,34 @@ export async function selectAgentModel(providerId: string, model: string): Promi}export const dismissCheckpoint = (turnId: number): void => useAgent.setState({ checkpointDone: turnId });+/** What a finished turn's Revert would cover. See {@link revertScope}. */+export interface RevertScope {+ steps: number;+ files: readonly FileChange[];+ /** Undo steps beyond the turn's own — the user has edited since, and a linear+ * stack takes those back too. Said out loud rather than done quietly. */+ stale: boolean;+ /** Files the revert cannot put back (past the journal's budget). */+ stranded: readonly FileChange[];+}++/**+ * Whether `turn` is worth offering a revert for and what one covers — null for+ * a turn that left nothing behind. BOTH halves count: a files-only turn has+ * zero undo steps, and reading steps alone offers nothing for exactly the work+ * undo cannot reach. `stepsNow` is the stack past the mark, the caller's to read.+ */+export function revertScope(turn: AgentTurn, stepsNow: number): RevertScope | null {+ if (turn.reason === null) return null;+ if (turn.steps === 0 && turn.files.length === 0) return null;+ return {+ steps: turn.steps,+ files: turn.files,+ stale: stepsNow > turn.steps,+ stranded: turn.files.filter((f) => f.unjournaled),+ };+}+/** The run still taking events, if any. Only the last one can be open. */const openTurn = (turns: readonly AgentTurn[]): AgentTurn | null => {const last = turns[turns.length - 1];diff --git a/desktop/src/theme/agent.css b/desktop/src/theme/agent.cssindex cc8e19dd2..e1e9eb874 100644--- a/desktop/src/theme/agent.css+++ b/desktop/src/theme/agent.css@@ -979,6 +979,7 @@.ag-chg--modify .ag-chg-s { color: var(--warn); }.ag-chg--remove .ag-chg-s { color: var(--error); }.ag-chg-p { color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.ag-chg-i { color: var(--text-faint); vertical-align: -1px; margin-right: 5px; }.ag-chg-d { color: var(--text-faint); }.ag-chg-v { display: flex; align-items: center; gap: 6px; font-size: var(--fs-2xs); white-space: nowrap; }.ag-chg-arrow { color: var(--text-faint); }diff --git a/desktop/tests/agent-revert-scope.test.ts b/desktop/tests/agent-revert-scope.test.tsnew file mode 100644index 000000000..5a37bfe0a--- /dev/null+++ b/desktop/tests/agent-revert-scope.test.ts@@ -0,0 +1,67 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file When a finished turn is worth offering a revert for, and what it covers.+ *+ * The policy, not the bar that renders it: the interesting cases are about which+ * halves of a turn's work exist, and a turn that only wrote files is the one a+ * steps-only checkpoint had nothing to say about.+ */+import { describe, it, expect } from 'vitest';+import { revertScope, type AgentTurn } from '@/store/AgentStore';+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: [],+ reason: 'end_turn', startedAt: 0, endedAt: 1,+ ...over,+});++const file = (path: string, over: Partial<FileChange> = {}): FileChange =>+ ({ path, kind: 'add', unjournaled: false, ...over });++describe('what a turn offers to take back', () => {+ it('offers nothing for a turn that changed nothing', () => {+ expect(revertScope(turn({}), 0)).toBeNull();+ });++ it('offers nothing while the turn is still running', () => {+ expect(revertScope(turn({ reason: null, steps: 4 }), 4)).toBeNull();+ });++ it('offers the scene edits a turn recorded', () => {+ expect(revertScope(turn({ steps: 7 }), 7)).toMatchObject({ steps: 7, files: [] });+ });++ // The case a steps-only checkpoint could not see: writing a script and a+ // 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);+ expect(scope).toMatchObject({ steps: 0, files: [{ path: 'src/HealthBar.ts' }] });+ });++ it('says when the user has edited past the turn', () => {+ expect(revertScope(turn({ steps: 2 }), 5)).toMatchObject({ stale: true });+ expect(revertScope(turn({ steps: 2 }), 2)).toMatchObject({ stale: false });+ });++ // Undone by hand down past the mark: fewer steps than the turn recorded is not+ // stale, and the bar must not claim the user edited over it.+ it('is not stale when the stack has shrunk instead', () => {+ expect(revertScope(turn({ steps: 5 }), 1)).toMatchObject({ stale: false });+ });++ // Named separately rather than folded into the count: a revert that leaves+ // them behind must not be shown as having taken the whole turn back.+ it('separates the files it cannot put back', () => {+ const scope = revertScope(turn({+ tx: 'tx-1',+ files: [file('src/HP.ts'), file('Video/intro.mp4', { kind: 'modify', unjournaled: true })],+ }), 0);+ expect(scope?.files).toHaveLength(2);+ expect(scope?.stranded.map((f) => f.path)).toEqual(['Video/intro.mp4']);+ });+});