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(editor): the change set, from a history that can say what it did
esenginee61d7b93072e
diff --git a/desktop/electron/agent/anthropic.ts b/desktop/electron/agent/anthropic.tsindex dba9db0da..40962cfc9 100644--- a/desktop/electron/agent/anthropic.ts+++ b/desktop/electron/agent/anthropic.ts@@ -253,9 +253,9 @@ class AnthropicSession implements AgentSession {const block = event.content_block;if (block.type === 'tool_use') {toolAt.set(event.index, block.id);- // The row exists from the moment the model commits to the call, so- // arguments are watched being written instead of appearing whole.- yield { type: 'tool_call', call: { id: block.id, name: block.name, input: {} } };+ // An announcement, not a call: the kernel dispatches `tool_call`, and+ // sharing the type here would run every tool twice.+ yield { type: 'tool_pending', id: block.id, name: block.name };}continue;}diff --git a/desktop/electron/agent/types.ts b/desktop/electron/agent/types.tsindex 5a41ff5d8..4284b46c0 100644--- a/desktop/electron/agent/types.ts+++ b/desktop/electron/agent/types.ts@@ -50,10 +50,17 @@ export interface ToolOutcome {export type StepEvent =| { type: 'text'; delta: string }| { type: 'thinking'; delta: string }+ /** A call to MAKE. Exactly one per call — the kernel dispatches these. */| { type: 'tool_call'; call: ToolCall }- /** The model is still WRITING a call's arguments. Emitted before the call is- * complete, so the editor can show it being composed rather than appearing- * finished out of a silence. */+ /**+ * The model has committed to a call but is still writing its arguments.+ *+ * Deliberately NOT a `tool_call`: the kernel executes those, and an+ * announcement that shared the type would run every tool twice. This one is+ * for the editor, so a row can appear and fill in rather than arriving+ * finished out of a silence.+ */+ | { type: 'tool_pending'; id: string; name: string }| { type: 'tool_args'; id: string; delta: string }/** Why the model stopped. `refusal` is a provider-level decline, not an error. */| { type: 'stop'; reason: 'end_turn' | 'tool_use' | 'refusal' | 'max_tokens' }diff --git a/desktop/src/components/AgentDrawer.tsx b/desktop/src/components/AgentDrawer.tsxindex 5071f1137..b19083836 100644--- a/desktop/src/components/AgentDrawer.tsx+++ b/desktop/src/components/AgentDrawer.tsx@@ -41,6 +41,8 @@ import { secretStatus, subscribeSecrets, secretRevision } from '@/store/SecretStimport { useSettings } from '@/store/settingsStore';import { MarkdownView } from '@/components/MarkdownView';import { dockApi } from '@/layout/dockApi';+import { EditorHistory, type HistoryMark } from '@/engine/EditorHistory';+import { useSelection } from '@/store/selectionStore';import { t } from '@/i18n';const TOOL_ICON: Record<string, typeof Eye> = {@@ -224,6 +226,77 @@ 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".+ */+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) : [];+ if (changes.length === 0) return null;++ const counts = {+ add: changes.filter((c) => c.kind === 'add').length,+ modify: changes.filter((c) => c.kind === 'modify').length,+ remove: changes.filter((c) => c.kind === 'remove').length,+ };+ return (+ <div className={`ag-changes${open ? ' open' : ''}`}>+ <button type="button" className="ag-changes-h" onClick={() => setOpen((o) => !o)}>+ <ChevronRight size={11} strokeWidth={2} className="ag-car" />+ <span className="ag-changes-t">{t('agent.changes')}</span>+ <span className="ag-sp" />+ {counts.add > 0 && <span className="ag-add">+{counts.add}</span>}+ {counts.modify > 0 && <span className="ag-mod">~{counts.modify}</span>}+ {counts.remove > 0 && <span className="ag-del">−{counts.remove}</span>}+ </button>+ {open && (+ <div className="ag-changes-l">+ {changes.map((c, i) => (+ <div+ className={`ag-chg ag-chg--${c.kind}`}+ key={i}+ onMouseEnter={() => peekEntities([c.entity])}+ onMouseLeave={() => peekEntities([])}+ onClick={() => useSelection.getState().select(c.entity)}+ >+ <span className="ag-chg-s">{c.kind === 'add' ? '+' : c.kind === 'remove' ? '−' : '~'}</span>+ <span className="ag-chg-p">+ {c.name}+ {c.component && <span className="ag-chg-d"> · {c.component}</span>}+ {c.field && <span className="ag-chg-d">{c.component ? '.' : ' · '}{c.field}</span>}+ </span>+ {c.kind === 'modify' && (c.before !== undefined || c.after !== undefined) && (+ <span className="ag-chg-v">+ <span className="ag-del">{brief(c.before)}</span>+ <span className="ag-chg-arrow">→</span>+ <span className="ag-add">{brief(c.after)}</span>+ </span>+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ );+}++/** A field value in one cell. Long values are cut — the row is a summary, and+ * the field itself is one click away in Details. */+function brief(value: unknown): string {+ if (value === undefined) return '—';+ if (value === null) return 'null';+ const text = typeof value === 'object' ? JSON.stringify(value) : String(value);+ return text.length > 22 ? `${text.slice(0, 21)}…` : text;+}+/** Ticks while the turn runs, then freezes at what it took. A turn that takes* two minutes should say so as it happens, not only afterwards. */function Elapsed({ turn }: { turn: AgentTurn }) {@@ -287,6 +360,7 @@ function Turn({ turn, isLast, running }: { turn: AgentTurn; isLast: boolean; runthe model is being asked again. Without this the transcript looksfinished while a request is in flight. */}{running && isLast && turn.entries.length > 0 && lastIsSettled(turn.entries) && <Waiting />}+ {turn.reason !== null && <ChangeSet turn={turn} />}</div>)}</div>diff --git a/desktop/src/engine/EditorHistory.ts b/desktop/src/engine/EditorHistory.tsindex 6a6c833bb..96759ad52 100644--- a/desktop/src/engine/EditorHistory.ts+++ b/desktop/src/engine/EditorHistory.ts@@ -30,6 +30,29 @@ interface HistoryEntry {/** Owning document: null = the scene, else an AssetDocument docId. */doc: string | null;ops: HistoryOp[];+ changes: readonly HistoryChange[];+}++/**+ * What a recorded step did, in terms someone can read back.+ *+ * The ops themselves are opaque closures — they can undo an edit but cannot say+ * what it was — so a step that wants to be reviewable declares it. Optional by+ * design: a gesture with nothing worth naming records none, and the stack still+ * works exactly as before.+ *+ * `name` is captured AT RECORD TIME because the point of reading this back is+ * often that the entity is gone.+ */+export interface HistoryChange {+ kind: 'add' | 'remove' | 'modify';+ /** Scene-source entity id (the id the Outliner and tools speak in). */+ entity: number;+ name: string;+ component?: string;+ field?: string;+ before?: unknown;+ after?: unknown;}/**@@ -70,9 +93,27 @@ export class EditorHistoryImpl {// the whole gesture lands as ONE entry when the group closes.private groupOps: HistoryOp[] | null = null;+ // Declared by the gesture's owner before it commits; a group accumulates them+ // across its inner records, since those do not commit on their own.+ private pendingChanges: HistoryChange[] = [];++ /**+ * Say what the step about to be recorded actually did. Call before the+ * `record`/`run` that commits it; inside a `group`, calls accumulate until the+ * group closes.+ */+ describe(...changes: HistoryChange[]): void {+ this.pendingChanges.push(...changes);+ }+private commit(label: string, ops: HistoryOp[], doc: string | null): void {- if (ops.length === 0) return;- this.undoStack.push({ id: ++this.seq, label, doc, ops });+ if (ops.length === 0) {+ this.pendingChanges.length = 0;+ return;+ }+ const changes = this.pendingChanges;+ this.pendingChanges = [];+ this.undoStack.push({ id: ++this.seq, label, doc, ops, changes });if (this.undoStack.length > HISTORY_LIMIT) this.undoStack.shift();this.redoStack.length = 0;this.bump();@@ -207,6 +248,20 @@ export class EditorHistoryImpl {* expected to stop offering the revert once its own steps are no longer the* newest, which {@link stepsSince} plus a version bump is enough to detect.*/+ /**+ * What every step since `mark` declared, oldest first — the review of an agent+ * turn. Steps that declared nothing contribute nothing, so this is a FLOOR on+ * what happened rather than a claim to be the whole of it. Reads the undo+ * stack, so an undone step stops being listed.+ */+ changesSince(mark: HistoryMark): HistoryChange[] {+ const out: HistoryChange[] = [];+ for (const entry of this.undoStack) {+ if (entry.id > mark.seq) out.push(...entry.changes);+ }+ return out;+ }+undoToMark(mark: HistoryMark): number {let n = 0;while (this.undoStack.length && this.undoStack[this.undoStack.length - 1].id > mark.seq) {diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 4c4bf004c..5955e3d0e 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -269,6 +269,15 @@ export class SceneCommandsImpl {return false;}+ /**+ * The entity's name as it stands NOW, for a change record. Captured at record+ * time on purpose: half the value of reading these back is that the entity is+ * gone by then.+ */+ private nameOf(sourceId: EntityId): string {+ return this.model.entityBySource(sourceId)?.name || `Entity ${sourceId}`;+ }+/*** Open a coalescing edit gesture. Every `setField` until {@link endGesture}* folds into one undo step. Idempotent-safe: a dangling gesture is committed@@ -288,6 +297,15 @@ export class SceneCommandsImpl {.map((e) => ({ ...e, after: structuredClone(this.modelFieldValue(e.sourceId, e.comp, e.key)) })).filter((e) => !valueEqual(e.before, e.after));if (edits.length === 0) return;+ this.history.describe(...edits.map((e) => ({+ kind: 'modify' as const,+ entity: e.sourceId,+ name: this.nameOf(e.sourceId),+ component: e.comp,+ field: e.key,+ before: e.before,+ after: e.after,+ })));this.history.record(g.label,() => edits.forEach((e) => this.model.setField(e.sourceId, e.comp, e.key, e.after)),@@ -721,6 +739,7 @@ export class SceneCommandsImpl {{ type: 'Transform', data: structuredClone(DEFAULT_TRANSFORM) } as SceneComponent,], parent);let record: SceneEntity | undefined;+ this.history.describe({ kind: 'add', entity: sourceId, name: this.nameOf(sourceId) });this.history.record('Add Entity',() => {@@ -751,6 +770,9 @@ export class SceneCommandsImpl {let records = remove();if (records.length === 0) return;+ this.history.describe(...records.map((r) => ({+ kind: 'remove' as const, entity: r.id, name: r.name || `Entity ${r.id}`,+ })));this.history.record(`Delete ${name}`,() => {@@ -936,6 +958,11 @@ export class SceneCommandsImpl {}};apply();+ // The whole subtree is new, and each of its entities is what a reviewer+ // wants listed — "created 1 thing" is not what building a menu looks like.+ this.history.describe(...this.model.collectSubtree(rootId).map((id) => ({+ kind: 'add' as const, entity: id, name: this.nameOf(id),+ })));this.history.record(linked ? `Instantiate ${prefab.name || 'Prefab'}` : `Create ${prefab.name || 'Entity'}`,apply,@@ -1009,6 +1036,9 @@ export class SceneCommandsImpl {const before = this.model.entityBySource(sourceId)?.name;if (before === undefined || before === name) return;this.model.setName(sourceId, name);+ this.history.describe({+ kind: 'modify', entity: sourceId, name, field: 'name', before, after: name,+ });this.history.record(`Rename ${name || 'Entity'}`,() => this.model.setName(sourceId, name),@@ -1273,7 +1303,11 @@ export class SceneCommandsImpl {addComponent(sourceId: EntityId, compName: string): void {const ops = this.addComponentOpsWithDeps(sourceId, compName);- if (ops.length) this.history.batch(`Add ${prettyLabel(compName)}`, ops);+ if (!ops.length) return;+ this.history.describe({+ kind: 'modify', entity: sourceId, name: this.nameOf(sourceId), component: compName, after: 'added',+ });+ this.history.batch(`Add ${prettyLabel(compName)}`, ops);}/**@@ -1304,7 +1338,11 @@ export class SceneCommandsImpl {/** Remove a component from an entity (Transform / Name are protected). Undoable. */removeComponent(sourceId: EntityId, compName: string): void {const op = this.removeComponentOp(sourceId, compName);- if (op) this.history.record(`Remove ${prettyLabel(compName)}`, op.forward, op.reverse);+ if (!op) return;+ this.history.describe({+ kind: 'modify', entity: sourceId, name: this.nameOf(sourceId), component: compName, before: 'present',+ });+ this.history.record(`Remove ${prettyLabel(compName)}`, op.forward, op.reverse);}/** Add a component to many entities (multi-select) as ONE undo step. */diff --git a/desktop/src/i18n/messages/agent.ts b/desktop/src/i18n/messages/agent.tsindex 698182580..9d9dbbb18 100644--- a/desktop/src/i18n/messages/agent.ts+++ b/desktop/src/i18n/messages/agent.ts@@ -62,6 +62,7 @@ export const agentMessages = defineMessages({'agent.turn.refusal': { en: 'The model declined this one.', zh: '模型拒绝了这个请求。' },'agent.turn.queuedMessage': { en: 'Queued: {text}', zh: '已排队:{text}' },'agent.copy': { en: 'Copy', zh: '复制' },+ 'agent.changes': { en: 'What changed', zh: '改动集' },'agent.rerun': { en: 'Ask this again, discarding what followed', zh: '从这里重跑(丢弃之后的内容)' },// — The decision it needs from you —diff --git a/desktop/src/store/AgentStore.ts b/desktop/src/store/AgentStore.tsindex 11e2d089b..fc1a433cf 100644--- a/desktop/src/store/AgentStore.ts+++ b/desktop/src/store/AgentStore.ts@@ -265,19 +265,21 @@ export function applyAgentEvent(turns: readonly AgentTurn[], event: AgentEvent):case 'thinking':return withEntries(turns, appendProse(open.entries, event.type, event.delta));- // Twice per call: once when the model commits to it (no arguments yet), and- // again with the parsed ones. The second is an UPDATE — a second row for the- // same call would double every tool the model uses.+ // The row opens on the announcement and is completed by the call, so+ // arguments are watched being written rather than appearing whole.+ case 'tool_pending':case 'tool_call': {- const known = open.entries.some((e) => e.kind === 'tool' && e.id === event.call.id);- if (known) {- return withEntries(turns, patchTool(open.entries, event.call.id, { input: event.call.input }));+ const id = event.type === 'tool_call' ? event.call.id : event.id;+ const name = event.type === 'tool_call' ? event.call.name : event.name;+ const input = event.type === 'tool_call' ? event.call.input : {};+ if (open.entries.some((e) => e.kind === 'tool' && e.id === id)) {+ return withEntries(turns, patchTool(open.entries, id, { input }));}return withEntries(turns, [...open.entries, {kind: 'tool',- id: event.call.id,- name: event.call.name,- input: event.call.input,+ id,+ name,+ input,effect: null,state: 'queued',summary: null,diff --git a/desktop/src/theme/agent.css b/desktop/src/theme/agent.cssindex f3d4e7cf5..774415101 100644--- a/desktop/src/theme/agent.css+++ b/desktop/src/theme/agent.css@@ -602,3 +602,40 @@}.ag-th:hover .ag-rerun, .ag-rerun:focus-visible { opacity: 1; }.ag-rerun:hover { color: var(--text-hi); background: var(--hover); }++/* ── The change set ─────────────────────────────────────────────────────────+ The work product of a run, so it gets real +/~/− semantics and a field-level+ before→after inline — not a popover hung off the undo bar. */+.ag-changes { margin: 2px 0; }+.ag-changes-h {+ display: flex; align-items: center; gap: 9px;+ width: 100%;+ padding: 8px 0;+ border-bottom: 1px solid var(--line);+ font: var(--fs-xs) var(--font-mono);+}+.ag-changes-t { font: 500 var(--fs-sm) var(--font-ui); color: var(--text-hi); }+.ag-changes .ag-car { color: var(--text-faint); transition: transform 0.18s ease; }+.ag-changes.open .ag-car { transform: rotate(90deg); }+.ag-changes-l { padding: 4px 0 2px; }+.ag-chg {+ display: grid;+ grid-template-columns: 14px minmax(0, 1fr) auto;+ gap: 9px;+ align-items: center;+ padding: 4px 6px;+ border-radius: var(--r-sm);+ font: var(--fs-xs) var(--font-mono);+ cursor: pointer;+}+.ag-chg:hover { background: var(--hover); }+.ag-chg-s { text-align: center; font-weight: 600; }+.ag-chg--add .ag-chg-s { color: var(--run); }+.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-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); }+.ag-mod { color: var(--warn); }+.ag-del { color: var(--error); }diff --git a/desktop/tests/agent-kernel.test.ts b/desktop/tests/agent-kernel.test.tsindex cbdf61259..bf83385c7 100644--- a/desktop/tests/agent-kernel.test.ts+++ b/desktop/tests/agent-kernel.test.ts@@ -77,6 +77,21 @@ describe('the agent turn', () => {expect(events.at(-1)).toEqual({ type: 'turn_end', steps: 3, mark: { seq: 7 }, reason: 'end_turn' });});+ // The provider announces a call while the model writes its arguments, and+ // again when they parse. Only the second is a call — collecting both would+ // run every tool the model asks for twice.+ it('runs a call once, however many times the provider mentions it', async () => {+ const s = fakeSession([[+ { type: 'tool_pending', id: 'cadd_entity', name: 'add_entity' },+ { type: 'tool_args', id: 'cadd_entity', delta: '{}' },+ { type: 'tool_call', call: call('add_entity') },+ { type: 'stop', reason: 'tool_use' },+ ], ends()]);+ await runTurn(deps(s), 'add one', null, new AbortController().signal);+ expect(events.filter((e) => e.type === 'tool_start')).toHaveLength(1);+ expect(s.results[0]).toHaveLength(1);+ });+it('runs an undoable edit without asking — the checkpoint is the approval', async () => {const s = fakeSession([asks(call('add_entity')), ends()]);await runTurn(deps(s), 'add one', null, new AbortController().signal);diff --git a/desktop/tests/history-changes.test.ts b/desktop/tests/history-changes.test.tsnew file mode 100644index 000000000..74be0f260--- /dev/null+++ b/desktop/tests/history-changes.test.ts@@ -0,0 +1,78 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What a recorded step SAYS it did.+ *+ * The ops on an entry are opaque closures — they can undo an edit but+ * cannot describe it — which is why "what changed since this mark" was+ * previously unanswerable and the agent's change set could not be built.+ * Declaring is optional, so the guarantee is a FLOOR: everything listed+ * happened, not everything that happened is listed.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { EditorHistoryImpl } from '@/engine/EditorHistory';++describe('describing a step', () => {+ let history: EditorHistoryImpl;+ const noop = () => {};++ beforeEach(() => {+ history = new EditorHistoryImpl();+ });++ it('attaches what was declared to the step that follows it', () => {+ const mark = history.mark();+ history.describe({ kind: 'add', entity: 7, name: 'PauseRoot' });+ history.record('Add Entity', noop, noop);+ expect(history.changesSince(mark)).toEqual([{ kind: 'add', entity: 7, name: 'PauseRoot' }]);+ });++ it('leaves a step that declared nothing empty rather than guessing', () => {+ const mark = history.mark();+ history.record('Something', noop, noop);+ expect(history.changesSince(mark)).toEqual([]);+ });++ // Each step consumes its own declarations; otherwise one described edit would+ // colour every step recorded after it.+ it('does not carry declarations into the next step', () => {+ history.describe({ kind: 'add', entity: 1, name: 'A' });+ history.record('First', noop, noop);+ const mark = history.mark();+ history.record('Second', noop, noop);+ expect(history.changesSince(mark)).toEqual([]);+ });++ // A group is one undo step, so it is also one description — inner records do+ // not commit on their own and must not lose what they declared.+ it('gathers a group into the single step it becomes', () => {+ const mark = history.mark();+ history.group('Build a menu', () => {+ history.describe({ kind: 'add', entity: 1, name: 'Root' });+ history.record('a', noop, noop);+ history.describe({ kind: 'add', entity: 2, name: 'Panel' });+ history.record('b', noop, noop);+ });+ expect(history.changesSince(mark).map((c) => c.name)).toEqual(['Root', 'Panel']);+ });++ it('reports only what happened after the mark', () => {+ history.describe({ kind: 'add', entity: 1, name: 'Before' });+ history.record('before', noop, noop);+ const mark = history.mark();+ history.describe({ kind: 'add', entity: 2, name: 'After' });+ history.record('after', noop, noop);+ expect(history.changesSince(mark).map((c) => c.name)).toEqual(['After']);+ });++ // Undo puts the step back on the redo stack, so it is no longer something+ // that happened — a change set still listing it would be describing a scene+ // the user is not looking at.+ it('drops a step that has been undone', () => {+ const mark = history.mark();+ history.describe({ kind: 'add', entity: 1, name: 'Gone' });+ history.record('add', noop, noop);+ history.undo();+ expect(history.changesSince(mark)).toEqual([]);+ });+});