diff --git a/.agents/notes/implemented/feature/2026-11-26-editor-agent-rewind.md b/.agents/notes/implemented/feature/2026-11-26-editor-agent-rewind.md new file mode 100644 index 00000000..7f6f96f3 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-26-editor-agent-rewind.md @@ -0,0 +1,56 @@ +# Agent Note: Rewinding an agent thread to before a message + +Status: implemented + +## Problem + +Issue #1021 implements the "Rewind the conversation · visible undo" workflow from `docs/design/editor/Checkpoints.dc.html` on top of the editor's Agent panel ([connecting external agents](../architecture/2026-11-26-editor-agent-connect.md)). Authors need to step back to before any earlier sent message in a thread, pick whether to restore **Files and conversation**, **Files only**, or **Conversation only**, edit the returned prompt in the composer, continue the agent session from before the dropped turns, or click **Redo** to bring both files and conversation back byte for byte. + +Two design constraints shaped the implementation: + +1. Project-wide turn checkpoints (#1018) and persisted multi-thread files (#1019) are not yet merged on `main`, so rewind must capture accurate, symlink-safe multi-file checkpoints per turn now while staying decoupled from on-disk checkpoint storage. +2. Restoring files on disk must keep open scenes, inactive scene tabs, `game.yaml`, the disk-change watcher, and the file tree synchronized without triggering false external-conflict prompts. + +## Decision + +### Compact per-turn checkpoints (`agent_rewind.go`) + +- Before launching a composer turn in `Editor.SubmitAgentPrompt`, the editor captures a pre-turn snapshot (`captureTurnStartCheckpoint`) of regular files under `agentProjectRoot()` (skipping `.git`, `.nsgo`, `node_modules`, `.svn`, `.hg`, symlinks, and You-only settings files, with per-file and total byte caps) along with cloned in-memory `Doc` and `Project` snapshots and `SessionIDBefore`. +- When the turn finishes (`finishAgentRun`) or is stopped (`StopAgentRun`), `finalizeTurnCheckpoint` computes the exact diff against the pre-turn scan, retains only the changed/created/deleted pre-turn file entries (`beforeFiles`), drops the full baseline map to keep memory bounded, records sorted `AgentTurn.ChangedFiles`, and records `AgentTurn.SessionIDAfter`. +- Checkpoints live in `agentState.checkpoints[turnID]` rather than directly inside `AgentTurn` so `Editor.AgentTurns()` never clones file byte slices during UI renders. + +### Three rewind modes, atomic rollback, and Redo (`RewindAgentTurn` / `RedoAgentRewind`) + +- Rewinding to before `turnID` merges the earliest `beforeFiles` entry across turns `[idx..len-1]` so multi-turn rewinds restore every touched file to its exact state immediately before `turnID`. +- Before writing or removing any file on disk, `snapshotDiskFiles` captures the current on-disk state into `agentRewindRecord.redoFiles` and `resolveSafeCheckpointPath` rejects relative escapes, protected directories, and symlinks on any path segment. `applyFileSnapshots` writes atomically via `writeFileAtomic`, prunes empty directories created by rewound turns without ever removing the project root, and rolls back applied files if any I/O operation fails partway. +- `syncEditorAfterFileRestore` reloads modified open scenes, inactive scene tabs, and `game.yaml`, refreshes `diskWatch` snapshots (`recordSceneDiskSnapshot` / `recordProjectDiskSnapshot`) so no spurious conflict banner fires, rebuilds the active scene, clears stale object selections, and refreshes project files, changes count, and problems. +- Mode behavior: + - `AgentRewindBoth`: restores files and in-memory scene/project state, truncates `agent.turns` to `[:idx]`, and restores `agent.sessionID` to `target.SessionIDBefore`. + - `AgentRewindFilesOnly`: restores files and in-memory scene/project state while leaving `agent.turns` and `agent.sessionID` unchanged. + - `AgentRewindConversationOnly`: truncates `agent.turns` to `[:idx]` and restores `agent.sessionID` while leaving disk files untouched. +- In all three modes, the target turn's prompt returns to the composer with `AgentComposerRewound()` set (highlighting the composer card with `SpecPalette.Accent.Edge`), and `AgentRewindBanner()` exposes the post-rewind summary and **Redo** action (`RedoAgentRewind`). Sending a new prompt clears the Redo record and forwards `AgentRequest.SessionID` (the restored `SessionIDBefore`) plus `AgentRequest.PriorTurns` so the agent session continues from before the dropped turns. + +### UI & Spec tokens (`agent_ui.go`) + +- Hovering or keyboard-focusing any sent user message reveals **Rewind to here** (`lucide.Undo2`), which toggles the `"Rewind to before this message"` dialog card (`RoleDialog` + `RoleRadioGroup`, dismissed by **Cancel** or `Esc`). +- All colors come exclusively from `SpecPalette` (`SpecPaletteFor(dark)`), including `p.Accent.OnFill` on `p.Accent.Fg` (weight 600) for the primary **Rewind** button so Dark and Light appearances both satisfy WCAG 2.2 AA contrast. + +## Alternatives considered + +### Drive file rewind exclusively through `Editor.History` commands + +Reusing `Editor.History` avoids snapshotting files on disk, because scene edits made through editor commands are already undoable. It is rejected because coding agents routinely modify multiple files outside the open scene (prefabs, particle definitions, scripts, data tables, and newly created files) directly on disk during a turn; `Editor.History` only tracks in-memory editor commands and cannot undo arbitrary multi-file disk mutations or keep them separate from conversation-only rewinds. + +### Persist rewind checkpoints into `.nsgo/checkpoints` immediately + +Writing checkpoints directly to `.nsgo/checkpoints` would align upfront with issue #1018. It is rejected here because #1018 owns the versioned on-disk checkpoint file schema and History-panel preview/restore UX; keeping #1021's turn checkpoints in memory behind `agentTurnCheckpoint` avoids inventing a duplicate on-disk format that would conflict with #1018 when both merge. + +## Consequences + +- **Benefits**: Authors can rewind from any earlier message in a thread across all three modes, undo multi-file agent turns byte for byte (including newly created and deleted files), keep open scenes and tabs synchronized without false disk-watch conflicts, continue the external agent session from the rewound point, and recover instantly with **Redo**. +- **Costs**: Turn checkpoints exist in memory for the current editor session until #1018 provides persistent `.nsgo/checkpoints` storage, and each turn boundary performs a bounded directory walk of the project root (capped at 16 MiB per file and 64 MiB total). + +## Testing + +- `packages/game/editor/agent_rewind_test.go`: tests **Files and conversation** rewind and **Redo** across two file-changing requests, **Files only** (keeping the thread) and **Conversation only** (keeping the files), rewinding to before the very first message, open-scene reload and session continuation on subsequent prompts, Cancel/Play guards, and Spec Dark/Light palette assertions. +- `packages/game/editor/editorcmd/agent_rewind_screenshot_test.go`: captures real native macOS screenshots of the Rewind popover and post-rewind banner + composer in Dark and Light appearances beside `docs/design/editor/Checkpoints.dc.html`. diff --git a/changelog.d/editor-agent-rewind-1021.md b/changelog.d/editor-agent-rewind-1021.md new file mode 100644 index 00000000..73ea43c0 --- /dev/null +++ b/changelog.d/editor-agent-rewind-1021.md @@ -0,0 +1,3 @@ +### Added + +- Add per-turn file and scene checkpoints and **Rewind to here** in the editor's Agent panel (#1021), supporting **Files and conversation**, **Files only**, and **Conversation only** rewind modes, **Redo** restoration, session continuation from before the rewound message, and returning the rewound prompt to the composer. diff --git a/docs/en/editor.md b/docs/en/editor.md index f8aafa03..b96aab90 100644 --- a/docs/en/editor.md +++ b/docs/en/editor.md @@ -1451,7 +1451,6 @@ Passing feedback in the editor uses one Spec-styled toast component (`ToastView` | Agent finished a request | Review opens | Never a toast | | Check failed, broken reference | Problems | Never a toast | | Agent asks, finishes or stops while the editor is in the background | + System notification | Paired with its in-editor channel | - ## Agent automations (#1029) Project automations (`automations.yaml` beside `game.yaml`, schema `https://game.nsgo.dev/schemas/automations.v1.json`) let the agent run follow-up checks and tasks after a change while keeping every result reviewable (`docs/design/editor/Settings.dc.html`, `Tasks.dc.html`, `Checkpoints.dc.html`): @@ -1507,7 +1506,6 @@ Agent tasks (both background tasks managed via `tasks.go` / #1022 and foreground - **Click opens the task in its scene**: `cx.OnNotificationPress` (delegating to `Editor.HandleNotificationPress` / `Editor.OpenAgentTask`) brings the editor window to the front (also calling `Editor.OnFocusWindow` when set), stops Play if running, dismisses obstructing panels (Settings, History, Problem agent panel, Ask-in-place, Assets mode), switches to or safely opens the task's scene tab strictly confined inside the project root (refusing traversal and symlink escapes), opens the Tasks or Agent panel, and focuses the task and any open request card. - **Dock badge (`cx.SetBadge`)**: `Editor.AgentDockBadgeCount` counts waiting (`TaskNeedsYou`), ready to review (`TaskReadyToReview`), and failed (`TaskFailed`) tasks (`AgentTaskCounts.BadgeCount()`); running and queued tasks never add to the badge, and `0` clears it (including on scope cleanup). - **Play-mode corner dot and deferred notifications (`PlayTaskDotView`)**: while Play mode is active (`Editor.Playing()`), agent task notifications do not pop over the running game and are held (`Editor.HeldAgentNotifications`) until `Editor.Stop()` flushes any tasks still needing attention. A single 8 pt dot with a 3 pt halo stays stably mounted in the top-right corner of the viewport in the Spec color of the most urgent state (**Failed** `Removed.Fg` > **Waiting** `Warning.Fg` > **Ready to review** `Accent.Fg`), revealing its label pill (such as `"1 task needs you · stop Play to open"`) only on hover or keyboard focus. - ## Live agent edits in the viewport and scene tree (#1013) While an agent edits a scene through `editormcp` or an active agent turn (`Editor.BeginAgentTurn` / `Editor.RunAsAgent`), the editor shows its pending changes live in both the viewport and scene tree (`docs/design/editor/Working.dc.html`, `Main.dc.html`, and `Spec.dc.html`) without ever moving the 2D or 3D viewport camera on the agent's behalf: @@ -1641,3 +1639,14 @@ When an agent turn proposes Go edits alongside scene, prefab, or data YAML chang - **Checks strip, failing test card, and Round 2 fixes in the same turn**: the live status strip (`RoleStatus` + `LiveRegionPolite`) shows `nsgo check`, `nsgo test` pass/fail counts, elapsed duration and package path, **Run again** (`r`), and live streaming progress (`"nsgo test running · M of N"` / `"Agent is fixing · nsgo test running · M of N"` with an `"Agent edited :"` badge). A failing test displays its name, `file:line` failure message, and the agent's explanation, with **Ask the agent to fix** (`AskAgentToFixCodeReview`, `Editor.OnAskCodeReviewFix`, keeping the fix inside the same turn as Round 2 and rerunning checks) and **Open the test** (`OpenCodeReviewTestFile`). - **Per-file confirmation, Keep, Waiting card, and single-step Undo**: **Confirm ``** (`ConfirmCodeReviewFile`) is disabled and refused with `ErrCodeReviewChecksNotPassed` until both `nsgo check` and `nsgo test` pass for the latest pending code, then toggles to **Confirmed · undo**. **Keep** (`KeepCodeReview` / `⌘↵`) writes kept YAML files and **confirmed** Go files atomically as **one undo step** in `Editor.History` so a single `Editor.Undo()` restores old YAML and Go files and removes newly created Go files. Keeping while Go files remain unconfirmed writes only the YAML changes and leaves a waiting card in the **Agent** panel (`"patrol.go is waiting for your OK"`, explaining what that means in Play, with **Review** to resume directly on the unconfirmed Go file). Pressing `Esc` (`CloseCodeReview`) pauses the review without discarding it, and **Revert all** (`RevertCodeReview` / `⌘⌫`) discards pending changes without touching disk. - **Command and MCP tools**: `CmdReviewCode` (`agent.reviewCode`) opens or resumes an active Go review. `editormcp` exposes `code_review_propose`, `code_review_status`, and `code_review_run_checks` so agents can propose pending Go files, inspect failures, submit Round 2 fixes in the same turn, and rerun overlay checks off the UI goroutine. + +## Rewind an agent thread (#1021) + +Rewind an agent conversation to before any earlier sent message (`docs/design/editor/Checkpoints.dc.html`, styled exclusively with `docs/design/editor/Spec.dc.html` tokens): + +- **Per-turn file and scene checkpoints**: each composer request (`SubmitAgentPrompt`) snapshots the project's files on disk (skipping `.git`, `.nsgo`, `node_modules`, symlinks, and You-only settings files) alongside the open scene and `game.yaml` before the agent runs, and compacts the diff when the turn finishes (`AgentTurn.ChangedFiles`, `AgentTurn.SessionIDBefore`, `AgentTurn.SessionIDAfter`). +- **Hover or focus "Rewind to here" and three choices**: hovering or focusing any sent user message in `AgentPanelView` reveals **Rewind to here** (`OpenAgentRewindPopover` / `ToggleAgentRewindPopover`), opening the `"Rewind to before this message"` popover (`AgentRewindPreview`) with three choices (`AgentRewindMode`), **Cancel** (or `Esc`), and **Rewind** (`ConfirmAgentRewind` / `RewindAgentTurn`): + - **Files and conversation (`AgentRewindBoth`)**: restores all files touched by the target and later turns from their checkpoints (synchronizing the open scene, inactive scene tabs, `game.yaml`, and file tree), drops the target and later turns from the thread, and restores `AgentSessionID` to `SessionIDBefore` so the next request continues the session from before the rewound message. + - **Files only (`AgentRewindFilesOnly`)**: restores the files from the turns' checkpoints while keeping the conversation thread and session unchanged. + - **Conversation only (`AgentRewindConversationOnly`)**: drops the target and later turns and restores the session ID while leaving all files on disk untouched. +- **Post-rewind banner, Redo, and composer return**: after rewinding, the rewound message returns to the composer highlighted with the Spec accent ring (`AgentComposerRewound`) so you can edit and ask it differently, and a status banner above the composer (`AgentRewindBanner`) summarizes what was rewound with a **Redo** button (`RedoAgentRewind` / `CanRedoAgentRewind`) that restores the files, conversation turns, session ID, and prior composer draft. diff --git a/docs/zh/editor.md b/docs/zh/editor.md index c2be9532..1d3a4892 100644 --- a/docs/zh/editor.md +++ b/docs/zh/editor.md @@ -1451,7 +1451,6 @@ func main() { | 智能体完成请求(Agent finished a request) | Review opens | 绝不使用 Toast | | 检查失败或损坏引用(Check failed, broken reference) | Problems | 绝不使用 Toast | | 编辑器在后台时智能体提问、完成或停止 | + System notification | 与编辑器内通道配合 | - ## 智能体自动化(#1029) 项目自动化(位于 `game.yaml` 旁的 `automations.yaml`,JSON Schema 为 `https://game.nsgo.dev/schemas/automations.v1.json`)允许智能体在更改发生后自动执行后续检查与任务,同时确保每项结果均经过人工审查(对应 `docs/design/editor/Settings.dc.html`、`Tasks.dc.html`、`Checkpoints.dc.html`): @@ -1507,7 +1506,6 @@ func main() { - **点击通知回到对应场景中的任务**:`cx.OnNotificationPress`(经由 `Editor.HandleNotificationPress` / `Editor.OpenAgentTask`)将编辑器窗口置前(并触发可选的 `Editor.OnFocusWindow` 钩子)、若在播放中先停止播放、关闭遮挡面板(设置、历史、问题智能体面板、就地提问、资源模式)、切换到或严格在项目根目录内打开该任务所在的场景标签页(拒绝路径遍历与符号链接逃逸)、打开任务或智能体面板并聚焦对应任务及待处理请求卡片。 - **Dock 图标角标(`cx.SetBadge`)**:`Editor.AgentDockBadgeCount` 仅统计等待中(`TaskNeedsYou`)、待审查(`TaskReadyToReview`)与失败(`TaskFailed`)任务的总数(`AgentTaskCounts.BadgeCount()`);运行中与排队中的任务绝不计入角标,归零或在作用域清理时自动清除。 - **播放模式角落提示点与延后通知(`PlayTaskDotView`)**:在播放模式(`Editor.Playing()`)期间,运行中的游戏上方不会弹出任何智能体任务通知,系统通知会暂存(`Editor.HeldAgentNotifications`)直至 `Editor.Stop()` 停止播放后才对仍需处理的任务发出。视口右上角稳定挂载一个带 3 pt 光晕的 8 pt 圆点,颜色取当前最紧急状态的 Spec 令牌色(**失败** `Removed.Fg` > **等待处理** `Warning.Fg` > **待审查** `Accent.Fg`),仅在悬停或键盘聚焦时显示提示胶囊(例如 `"1 task needs you · stop Play to open"`)。 - ## 在视口与场景树中实时显示智能体编辑(#1013) 当智能体通过 `editormcp` 或待定智能体回合(`Editor.BeginAgentTurn` / `Editor.RunAsAgent`)编辑场景时,编辑器会在视口与场景树中实时呈现其未确认改动(对应 `docs/design/editor/Working.dc.html`、`Main.dc.html` 与 `Spec.dc.html`),且绝不会替智能体移动 2D 或 3D 视口相机: @@ -1641,3 +1639,14 @@ func main() { - **检查状态条、失败测试卡片与同回合第 2 轮修复**:状态条(`RoleStatus` + `LiveRegionPolite`)展示 `nsgo check`、`nsgo test` 通过/失败计数、耗时与包路径、**Run again**(`r`)以及运行中的实时进度(`"nsgo test running · M of N"` / `"Agent is fixing · nsgo test running · M of N"` 及 `"Agent edited :"` 徽章)。失败测试卡片会展示测试名、`file:line` 错误输出和智能体的原因说明,并提供 **Ask the agent to fix**(`AskAgentToFixCodeReview`、`Editor.OnAskCodeReviewFix`,在同一回合内作为 Round 2 修复并重新运行检查)与 **Open the test**(`OpenCodeReviewTestFile`)。 - **逐文件确认、保留、等待卡片与单步撤销**:在最新待定代码通过 `nsgo check` 和 `nsgo test` 之前,**Confirm ``**(`ConfirmCodeReviewFile`)保持禁用并返回 `ErrCodeReviewChecksNotPassed`;检查通过后解锁,确认后切换为 **Confirmed · undo**。**Keep**(`KeepCodeReview` / `⌘↵`)会将保留的 YAML 文件与**已确认**的 Go 文件作为 `Editor.History` 中的**单个撤销步骤**原子写入磁盘,一次 `Editor.Undo()` 即可还原旧 YAML/Go 文件并移除新建的 Go 文件。若保留时仍有未确认的 Go 文件,则仅写入 YAML 更改并在 **Agent** 面板保留一张等待卡片(说明哪些文件等待确认及其在运行模式中的影响,并附带 **Review** 按钮直接回到未确认的 Go 文件)。按 `Esc`(`CloseCodeReview`)可暂停审查而不丢弃更改,**Revert all**(`RevertCodeReview` / `⌘⌫`)则直接丢弃待定更改且不触碰磁盘。 - **命令与 MCP 工具**:命令 `CmdReviewCode`(`agent.reviewCode`)用于打开或恢复进行中的 Go 审查。`editormcp` 提供 `code_review_propose`、`code_review_status` 与 `code_review_run_checks`,使智能体可在不阻塞 UI goroutine 的情况下提交待审 Go 代码、读取失败详情、在同一回合提交 Round 2 修复并重新运行覆盖层检查。 + +## 回退智能体对话线程(#1021) + +可将智能体对话回退到任意已发送消息之前(对应 `docs/design/editor/Checkpoints.dc.html`,全部界面仅使用 `docs/design/editor/Spec.dc.html` 设计 Token): + +- **每轮文件与场景检查点**:每次通过输入框发送请求(`SubmitAgentPrompt`)前,编辑器会为项目磁盘文件(跳过 `.git`、`.nsgo`、`node_modules`、符号链接以及仅限用户配置文件)以及当前打开的场景与 `game.yaml` 拍摄前快照,并在回合结束或停止时压缩为差异检查点(`AgentTurn.ChangedFiles`、`AgentTurn.SessionIDBefore`、`AgentTurn.SessionIDAfter`)。 +- **悬停或聚焦显示“回退到此处”与三种选项**:在 `AgentPanelView` 中悬停或键盘聚焦任意已发送的用户消息即可显示 **Rewind to here** / **回退到此处**(`OpenAgentRewindPopover` / `ToggleAgentRewindPopover`),打开“回退到此消息之前”弹层(`AgentRewindPreview`),提供三个选项(`AgentRewindMode`)、**Cancel** / **取消**(或按 `Esc`)与 **Rewind** / **回退**(`ConfirmAgentRewind` / `RewindAgentTurn`): + - **文件与对话(`AgentRewindBoth`)**:从检查点还原目标回合及之后所有受影响的文件(并同步刷新当前场景、其他打开的场景标签页、`game.yaml` 与文件树),从对话中移除后续请求与回复,并将 `AgentSessionID` 恢复至 `SessionIDBefore`,使下一次提问直接从该消息之前继续会话。 + - **仅文件(`AgentRewindFilesOnly`)**:从回合检查点还原文件,同时保持对话记录与会话不变。 + - **仅对话(`AgentRewindConversationOnly`)**:移除目标及后续回合与会话推进,同时保持磁盘文件现状不变。 +- **回退横幅、重做与消息回到输入框**:回退完成后,被回退的消息会重新填入输入框并以规范强调色边框高亮(`AgentComposerRewound`),方便修改后重新发送;输入框上方会显示状态横幅(`AgentRewindBanner`)说明已回退的范围,并提供 **Redo** / **重做** 按钮(`RedoAgentRewind` / `CanRedoAgentRewind`)一键恢复文件、对话回合、会话 ID 与原有输入框草稿。 diff --git a/packages/game/editor/agent.go b/packages/game/editor/agent.go index 2c7f0989..afc713e6 100644 --- a/packages/game/editor/agent.go +++ b/packages/game/editor/agent.go @@ -280,47 +280,51 @@ type AgentTurnContext struct { // AgentTurn is one user request (in-place ⌘L, Agent panel composer, terminal-initiated MCP turn, or background automation run) // and its attached context, streamed steps, follow-ups, pending review, and reply. type AgentTurn struct { - ID string `json:"id"` - Prompt string `json:"prompt"` - Images []AgentReferenceImage `json:"-"` // reference images sent with this turn (one-shot attachments and pinned brief references) - Source string `json:"source,omitempty"` // "in_place", "panel", "external", or "automation" - SkipPlan bool `json:"skipPlan,omitempty"` // true for small in-place ⌘L edits per Plan.dc.html - Status string `json:"status,omitempty"` // "pending", "running", "done", "stopped" - External bool `json:"external,omitempty"` // true for turns started by a terminal MCP client rather than the composer - AgentName string `json:"agentName,omitempty"` - Task AgentTaskKind `json:"task,omitempty"` - Route AgentModelRoute `json:"route,omitempty"` - Model string `json:"model,omitempty"` - Steps []AgentStep `json:"steps,omitempty"` - PlannedSteps []string `json:"plannedSteps,omitempty"` - FollowUps []AgentFollowUp `json:"followUps,omitempty"` - NotChecked []string `json:"notChecked,omitempty"` - StoppedBefore string `json:"stoppedBefore,omitempty"` - PendingReview *AgentPendingReview `json:"pendingReview,omitempty"` - Summary string `json:"summary,omitempty"` - Reply string `json:"reply,omitempty"` - Error string `json:"error,omitempty"` - ModelError *AgentModelErrorState `json:"modelError,omitempty"` - Stopped bool `json:"stopped,omitempty"` - Done bool `json:"done,omitempty"` - Partial *AgentPartialState `json:"partial,omitempty"` - Stuck *AgentStuckState `json:"stuck,omitempty"` - Lost *AgentLostState `json:"lost,omitempty"` - StoppedState *AgentStoppedState `json:"stoppedState,omitempty"` - Mismatch *AgentMismatchReport `json:"mismatch,omitempty"` - Review *AgentTurnReview `json:"review,omitempty"` - InputTokens int `json:"inputTokens,omitempty"` - OutputTokens int `json:"outputTokens,omitempty"` - CreatedAt time.Time `json:"createdAt"` - StartedAt time.Time `json:"startedAt"` - FinishedAt time.Time `json:"finishedAt"` - Context AgentTurnContext `json:"context"` - Automation bool `json:"automation,omitempty"` // true for turns started by an automation trigger - AutomationID string `json:"automationId,omitempty"` // rule ID from automations.yaml when Automation is true - AutomationName string `json:"automationName,omitempty"` // WHEN summary of the triggering automation rule - TriggerSummary string `json:"triggerSummary,omitempty"` // concrete trigger description, e.g. "File changed · scenes/level_01.scene.yaml" - CheckpointID string `json:"checkpointId,omitempty"` // checkpoint captured before the automation started - ReviewState AgentReviewState `json:"reviewState,omitempty"` // lifecycle state for Ready to review / Kept / Dismissed / Failed + ID string `json:"id"` + Prompt string `json:"prompt"` + Images []AgentReferenceImage `json:"-"` // reference images sent with this turn (one-shot attachments and pinned brief references) + Source string `json:"source,omitempty"` // "in_place", "panel", "external", or "automation" + SkipPlan bool `json:"skipPlan,omitempty"` // true for small in-place ⌘L edits per Plan.dc.html + Status string `json:"status,omitempty"` // "pending", "running", "done", "stopped" + External bool `json:"external,omitempty"` // true for turns started by a terminal MCP client rather than the composer + AgentName string `json:"agentName,omitempty"` + Task AgentTaskKind `json:"task,omitempty"` + Route AgentModelRoute `json:"route,omitempty"` + Model string `json:"model,omitempty"` + Steps []AgentStep `json:"steps,omitempty"` + PlannedSteps []string `json:"plannedSteps,omitempty"` + FollowUps []AgentFollowUp `json:"followUps,omitempty"` + NotChecked []string `json:"notChecked,omitempty"` + StoppedBefore string `json:"stoppedBefore,omitempty"` + PendingReview *AgentPendingReview `json:"pendingReview,omitempty"` + Summary string `json:"summary,omitempty"` + Reply string `json:"reply,omitempty"` + Error string `json:"error,omitempty"` + ModelError *AgentModelErrorState `json:"modelError,omitempty"` + Stopped bool `json:"stopped,omitempty"` + Done bool `json:"done,omitempty"` + Partial *AgentPartialState `json:"partial,omitempty"` + Stuck *AgentStuckState `json:"stuck,omitempty"` + Lost *AgentLostState `json:"lost,omitempty"` + StoppedState *AgentStoppedState `json:"stoppedState,omitempty"` + Mismatch *AgentMismatchReport `json:"mismatch,omitempty"` + Review *AgentTurnReview `json:"review,omitempty"` + InputTokens int `json:"inputTokens,omitempty"` + OutputTokens int `json:"outputTokens,omitempty"` + CreatedAt time.Time `json:"createdAt"` + StartedAt time.Time `json:"startedAt"` + FinishedAt time.Time `json:"finishedAt"` + Context AgentTurnContext `json:"context"` + ChangedFiles []string `json:"changedFiles,omitempty"` + ThreadID string `json:"threadId,omitempty"` + SessionIDBefore string `json:"sessionIdBefore,omitempty"` + SessionIDAfter string `json:"sessionIdAfter,omitempty"` + Automation bool `json:"automation,omitempty"` // true for turns started by an automation trigger + AutomationID string `json:"automationId,omitempty"` // rule ID from automations.yaml when Automation is true + AutomationName string `json:"automationName,omitempty"` // WHEN summary of the triggering automation rule + TriggerSummary string `json:"triggerSummary,omitempty"` // concrete trigger description, e.g. "File changed · scenes/level_01.scene.yaml" + CheckpointID string `json:"checkpointId,omitempty"` // checkpoint captured before the automation started + ReviewState AgentReviewState `json:"reviewState,omitempty"` // lifecycle state for Ready to review / Kept / Dismissed / Failed turnStartHistoryIdx int baselineDoc *sceneformat.SceneDoc @@ -358,6 +362,7 @@ type AgentRequest struct { Task AgentTaskKind Route AgentModelRoute Model string + PriorTurns []AgentTurnSummary AutomationID string AutomationName string TriggerKind AutomationTriggerKind @@ -498,7 +503,6 @@ type agentState struct { builtInKeyChecked bool builtInKeyPresent bool notify agentNotifyState - // Failure states, offline queue, viewport pointing, and turn review tracking. offline bool pointingTurnID string @@ -508,7 +512,6 @@ type agentState struct { externalBaselineFile string externalHistoryStart int externalBaselineIDs map[string]struct{} - // Live MCP request streaming, permission card, follow-up, and Stop state (#1012). liveRequestID uint64 liveRequestActive bool @@ -523,6 +526,13 @@ type agentState struct { liveFocusCardSeq uint64 liveFocusReviewSeq uint64 livePermCardFocused bool + + // Per-turn checkpoints and rewind / redo state. + checkpoints map[string]*agentTurnCheckpoint + rewindOpenTurnID string + rewindMode AgentRewindMode + lastRewind *agentRewindRecord + composerHighlighted bool } func (a *agentState) setScope(cx *core.Scope) { @@ -557,6 +567,7 @@ func (a *agentState) initDefaults() { a.threadID = "thread-1" a.reconnectTotal = len(AgentReconnectDelays) a.notify.initDefaults() + a.rewindMode = AgentRewindBoth } func (e *Editor) nowTime() time.Time { @@ -706,6 +717,11 @@ func (e *Editor) resetAgentForProject() { e.agent.liveQueuedFollowUps = nil e.agent.liveActivity = "" e.agent.livePermCardFocused = false + e.agent.checkpoints = nil + e.agent.rewindOpenTurnID = "" + e.agent.rewindMode = AgentRewindBoth + e.agent.lastRewind = nil + e.agent.composerHighlighted = false if e.agent.mode == AgentModeAPIKey && e.HasAgentAPIKey(DefaultAgentAPIKeyAccount) { if e.AgentWeeklyLimitReached() { e.agent.status = AgentStatusLimitReached @@ -750,6 +766,7 @@ func (e *Editor) SetRightRailTab(tab RightRailTab) { e.agentComposer.pickerOpen = false e.agentComposer.breakdownOpen = false e.agentComposer.hoveredChipID = "" + e.agent.rewindOpenTurnID = "" } e.agentThreads.rev++ e.notify() @@ -1128,6 +1145,7 @@ func (e *Editor) CompleteConnectDialog() { e.stopAgentTimers() e.agent.queued = nil e.agent.rightTab = RightTabInspector + e.agent.rewindOpenTurnID = "" e.agent.status = AgentStatusNotConnected e.updateAgentAnnouncement() case AgentModeLocal: @@ -1544,9 +1562,11 @@ func (e *Editor) AgentComposerText() string { // SetAgentComposerText updates the multi-line draft in the Agent composer. func (e *Editor) SetAgentComposerText(text string) { - if e == nil || e.composerDraft == text { + if e == nil || (e.composerDraft == text && !e.agent.composerHighlighted) { return } + e.agent.composerText = text + e.agent.composerHighlighted = false e.updateComposerDraftFromInput(text) } @@ -1555,7 +1575,10 @@ func (e *Editor) InsertAgentComposerNewline() { if e == nil { return } - e.updateComposerDraftFromInput(e.composerDraft + "\n") + next := e.composerDraft + "\n" + e.agent.composerText = next + e.agent.composerHighlighted = false + e.updateComposerDraftFromInput(next) } func cloneAgentTurn(t AgentTurn) AgentTurn { @@ -1583,6 +1606,7 @@ func cloneAgentTurn(t AgentTurn) AgentTurn { cp.NotChecked = slices.Clone(t.PendingReview.NotChecked) t.PendingReview = &cp } + t.ChangedFiles = slices.Clone(t.ChangedFiles) t.Context.SelectionIDs = slices.Clone(t.Context.SelectionIDs) t.Context.SelectionNames = slices.Clone(t.Context.SelectionNames) t.Context.ViewportPNG = slices.Clone(t.Context.ViewportPNG) @@ -2030,6 +2054,7 @@ func (e *Editor) finishAgentRun(runID uint64, turnID string, err error, canceled e.clearWaitingTurnTaskID() } e.agent.turnChangeSeq++ + e.finalizeTurnCheckpoint(turnID) e.restoreIdleAgentStatus() if !e.HasUnkeptAgentTurnReview() && !e.HasPendingAgentTurnReview() { e.scheduleAutoSaveIfNeeded() diff --git a/packages/game/editor/agent_builtin.go b/packages/game/editor/agent_builtin.go index efc8f853..5484226a 100644 --- a/packages/game/editor/agent_builtin.go +++ b/packages/game/editor/agent_builtin.go @@ -582,6 +582,7 @@ func (e *Editor) submitAgentTaskPromptInternal(task AgentTaskKind, prompt string if fromComposer || text == strings.TrimSpace(e.composerDraft) || text == strings.TrimSpace(e.agent.composerText) { e.composerDraft = "" e.agent.composerText = "" + e.agent.composerHighlighted = false e.agentComposer.pickerOpen = false e.agentComposer.pickerOpenedByAt = false e.agentComposer.pickerQuery = "" @@ -630,6 +631,7 @@ func (e *Editor) submitAgentTaskPromptInternal(task AgentTaskKind, prompt string req.Task = task req.Route = route req.Model = model + req.PriorTurns = e.agentPriorTurnSummaries() req.AttachedImages = attachedImgs req.BriefImages = briefImgs req.Images = allImgs @@ -648,11 +650,23 @@ func (e *Editor) submitAgentTaskPromptInternal(task AgentTaskKind, prompt string e.agentComposer.pickerQuery = "" e.agentComposer.pickerActiveIndex = 0 e.agentComposer.hoveredChipID = "" + e.agent.composerHighlighted = false + e.agent.rewindOpenTurnID = "" + e.agent.lastRewind = nil + + sessionBefore := sessionID + cp := e.captureTurnStartCheckpoint() e.agent.turnSeq++ e.agent.turnChangeSeq++ e.agent.liveRequestID++ e.agent.liveStepSeq++ turnID := fmt.Sprintf("turn-%d", e.agent.turnSeq) + if cp != nil { + if e.agent.checkpoints == nil { + e.agent.checkpoints = make(map[string]*agentTurnCheckpoint) + } + e.agent.checkpoints[turnID] = cp + } agentKind := ExternalAgentAuto if !route.IsBuiltIn() { if c, ok := e.AgentPrimaryClient(); ok { @@ -692,6 +706,8 @@ func (e *Editor) submitAgentTaskPromptInternal(task AgentTaskKind, prompt string }}, CreatedAt: now, StartedAt: now, + ThreadID: threadID, + SessionIDBefore: sessionBefore, turnStartHistoryIdx: startHist, }) e.trimAgentTurnAttachments() @@ -817,6 +833,7 @@ func (e *Editor) SwitchAgentTurnToAlternative(turnID string) error { turn.Status = "done" turn.FinishedAt = e.nowTime() e.agent.turnChangeSeq++ + e.finalizeTurnCheckpoint(turnID) if turn.ModelError != nil { turn.ModelError.Retrying = false } diff --git a/packages/game/editor/agent_composer.go b/packages/game/editor/agent_composer.go index 87235528..99cbee3f 100644 --- a/packages/game/editor/agent_composer.go +++ b/packages/game/editor/agent_composer.go @@ -322,6 +322,8 @@ func (e *Editor) resetAgentComposerForProject() { } e.agent.threadID = "thread-1" e.composerDraft = "" + e.agent.composerText = "" + e.agent.composerHighlighted = false } // closeComposerPopovers closes transient composer popovers (mention picker, breakdown, hover preview) @@ -366,6 +368,7 @@ func (e *Editor) composerKeysBlocked() bool { e.RightRailTab() != RightTabAgent || e.AgentMode() == AgentModeNone || e.AgentSwitcherOpen() || + e.AgentRewindOpenTurnID() != "" || e.AskInPlaceOpen() || e.contextMenu.open || e.PermissionsDraftOpen() || e.StartScreenOpen() || e.MergeConflictOpen() || e.PlaytestReportOpen() || @@ -465,6 +468,8 @@ func (e *Editor) updateComposerDraftFromInput(text string) { return } e.composerDraft = text + e.agent.composerText = text + e.agent.composerHighlighted = false if start, query, ok := detectMentionTrigger(text); ok { prevQuery := e.agentComposer.pickerQuery e.agentComposer.pickerOpen = true @@ -679,7 +684,9 @@ func (e *Editor) AcceptMentionItem(id string) (AgentContextChip, bool) { } if start, _, ok := detectMentionTrigger(e.composerDraft); ok { e.composerDraft = e.composerDraft[:start] + e.agent.composerText = e.composerDraft } + e.agent.composerHighlighted = false e.agentComposer.pickerOpen = false e.agentComposer.pickerOpenedByAt = false e.agentComposer.pickerQuery = "" @@ -2294,6 +2301,9 @@ func joinContextBlocksBounded(blocks []string, maxBytes int) string { func cloneAgentRequest(req AgentRequest) AgentRequest { out := req + if len(req.PriorTurns) > 0 { + out.PriorTurns = slices.Clone(req.PriorTurns) + } if len(req.ViewportImage) > 0 { out.ViewportImage = slices.Clone(req.ViewportImage) } @@ -2378,6 +2388,10 @@ func (e *Editor) SendComposerPrompt() (AgentRequest, error) { } e.composerDraft = "" + e.agent.composerText = "" + e.agent.composerHighlighted = false + e.agent.rewindOpenTurnID = "" + e.agent.lastRewind = nil e.agentComposer.pickerOpen = false e.agentComposer.pickerOpenedByAt = false e.agentComposer.pickerQuery = "" @@ -2430,12 +2444,16 @@ func (e *Editor) RecallLastComposerPrompt() bool { } if len(e.agentComposer.turns) > 0 { e.composerDraft = e.agentComposer.turns[len(e.agentComposer.turns)-1].Prompt + e.agent.composerText = e.composerDraft + e.agent.composerHighlighted = false e.notify() return true } for i := len(e.agent.turns) - 1; i >= 0; i-- { if !e.agent.turns[i].External && strings.TrimSpace(e.agent.turns[i].Prompt) != "" { e.composerDraft = e.agent.turns[i].Prompt + e.agent.composerText = e.composerDraft + e.agent.composerHighlighted = false e.notify() return true } @@ -2804,6 +2822,12 @@ func (e *Editor) StartFreshAgentThread() (string, error) { e.agent.threadID = e.agentComposer.threadID e.agent.sessionID = "" e.agent.turns = nil + e.agent.checkpoints = nil + e.agent.rewindOpenTurnID = "" + e.agent.lastRewind = nil + e.agent.composerHighlighted = false + e.agent.pointingTurnID = "" + e.agent.openReviewTurnID = "" e.agent.turnChangeSeq++ e.agentComposer.turns = nil e.agentComposer.compactedSummary = "" diff --git a/packages/game/editor/agent_composer_ui.go b/packages/game/editor/agent_composer_ui.go index e0b9f3f1..d2a83171 100644 --- a/packages/game/editor/agent_composer_ui.go +++ b/packages/game/editor/agent_composer_ui.go @@ -986,11 +986,17 @@ func AgentComposerView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) cor StyleFunc: func() core.Style { _ = rev.Get() p := ed.SpecPalette(cx) + bw := core.Points(1) + bc := p.LineRaised + if ed.AgentComposerRewound() { + bw = 1.5 + bc = p.Accent.Edge + } return core.Style{ CornerRadius: specRadiusCard, Background: p.Raised, - BorderWidth: 1, - BorderColor: p.LineRaised, + BorderWidth: bw, + BorderColor: bc, Padding: core.Symmetric(specSpace8, specSpace12), Gap: specSpace8, FocusWithin: p.FocusRing(2), diff --git a/packages/game/editor/agent_live_steps.go b/packages/game/editor/agent_live_steps.go index 620eb284..e1918fad 100644 --- a/packages/game/editor/agent_live_steps.go +++ b/packages/game/editor/agent_live_steps.go @@ -295,6 +295,9 @@ func (e *Editor) StartAgentRequest(prompt string) uint64 { e.agent.liveDeniedKeys = make(map[string]bool) e.agent.liveQueuedFollowUps = nil e.agent.liveActivity = "Agent is working · manual edits stay available" + e.agent.rewindOpenTurnID = "" + e.agent.lastRewind = nil + e.agent.composerHighlighted = false e.agent.status = AgentStatusWorking e.agent.workingStep = 1 e.agent.workingTotal = 0 @@ -852,6 +855,7 @@ func (e *Editor) CompleteAgentRequest(summary string) { turn.Mismatch = CheckAgentSummaryAgainstDiff(turn.Summary, turn.Review, turn.mutations) } turn.PendingReview = e.buildTurnPendingReviewLocked(turn, summary, false) + e.finalizeTurnCheckpoint(turn.ID) } e.agent.turnChangeSeq++ e.restoreIdleAgentStatus() @@ -905,6 +909,9 @@ func (e *Editor) StopAgent() bool { e.agent.liveActivity = "" if turn := e.latestAgentTurnPtr(); turn != nil && !turn.Done { + if stoppedTurnID == "" { + stoppedTurnID = turn.ID + } dropTurnPlaceholder(turn) if hadActiveRun { for i := range turn.Steps { @@ -977,6 +984,9 @@ func (e *Editor) StopAgent() bool { turn.PendingReview = e.buildTurnPendingReviewLocked(turn, fmt.Sprintf("%s · %s.", stepLabel, keptDetail), true) } } + if stoppedTurnID != "" { + e.finalizeTurnCheckpoint(stoppedTurnID) + } e.ShowToast(Toast{ ID: "agent-stopped", diff --git a/packages/game/editor/agent_rewind.go b/packages/game/editor/agent_rewind.go new file mode 100644 index 00000000..ba2a471c --- /dev/null +++ b/packages/game/editor/agent_rewind.go @@ -0,0 +1,1286 @@ +package editor + +import ( + "bytes" + "crypto/sha256" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "slices" + "strings" + + "github.com/nsgo-dev/game/packages/game/l10n" + "github.com/nsgo-dev/game/packages/game/project" + "github.com/nsgo-dev/game/packages/game/sceneformat" +) + +const ( + maxRewindCheckpointFileBytes = 16 * 1024 * 1024 // 16 MiB per file cap + maxRewindCheckpointTotalBytes = 64 * 1024 * 1024 // 64 MiB per snapshot cap +) + +// AgentRewindMode selects what RewindAgentTurn restores when rewinding to before a message. +type AgentRewindMode string + +const ( + // AgentRewindBoth restores files from the turns' checkpoints and drops the target and later turns from the thread. + AgentRewindBoth AgentRewindMode = "both" + // AgentRewindFilesOnly restores files from the turns' checkpoints while keeping the conversation thread unchanged. + AgentRewindFilesOnly AgentRewindMode = "files" + // AgentRewindConversationOnly drops the target and later turns from the thread while keeping all files as they are. + AgentRewindConversationOnly AgentRewindMode = "conversation" +) + +// AgentTurnSummary carries a concise summary of a prior turn still in the thread when dispatching the next AgentRequest. +type AgentTurnSummary struct { + ID string + Prompt string + Summary string + ChangedFiles []string +} + +// AgentRewindPreview describes the files and replies that rewinding to before a message will affect. +type AgentRewindPreview struct { + TurnID string + TurnIndex int + Prompt string + ChangedFiles []string + DroppedTurns int +} + +// AgentRewindState describes the most recent rewind shown in the post-rewind banner above the composer with Redo. +type AgentRewindState struct { + TurnID string + TurnIndex int + Mode AgentRewindMode + Prompt string + FilesRestored []string + TurnsDropped int +} + +type fileSnapshot struct { + exists bool + data []byte + mode fs.FileMode + hash [sha256.Size]byte +} + +func (s fileSnapshot) equal(other fileSnapshot) bool { + if s.exists != other.exists { + return false + } + if !s.exists { + return true + } + return s.hash == other.hash && bytes.Equal(s.data, other.data) +} + +type agentTurnCheckpoint struct { + root string + + // fullBefore holds the complete directory scan while a turn is running; + // finalizeTurnCheckpoint compacts it into beforeFiles and clears it. + fullBefore map[string]fileSnapshot + + beforeFiles map[string]fileSnapshot + + beforeDoc *sceneformat.SceneDoc + beforeDocYAML []byte + beforeSceneSaved []byte + beforeFilePath string + docChanged bool + beforeProject *project.File + beforeProjectYAML []byte + beforeProjectSaved []byte + projectChanged bool + + finalized bool +} + +type agentRewindRecord struct { + state AgentRewindState + root string + previousComposerText string + previousTurns []AgentTurn + previousSessionID string + previousCheckpoints map[string]*agentTurnCheckpoint + previousLiveStopped bool + threadID string + previousThreadSessionID string + hadThreadSession bool + + redoFiles map[string]fileSnapshot + hadDocRestore bool + redoDoc *sceneformat.SceneDoc + redoSceneSaved []byte + redoFilePath string + hadProjectRestore bool + redoProject *project.File + redoProjectSaved []byte + filesRestoredCount int +} + +func sameCleanPath(a, b string) bool { + if a == "" && b == "" { + return true + } + if a == "" || b == "" { + return false + } + return filepath.Clean(a) == filepath.Clean(b) +} + +func skipCheckpointDir(name string) bool { + switch name { + case ".git", ".nsgo", "node_modules", ".svn", ".hg": + return true + default: + return false + } +} + +func captureProjectFileTree(root string) map[string]fileSnapshot { + if root == "" { + return nil + } + cleanRoot := filepath.Clean(root) + info, err := os.Stat(cleanRoot) + if err != nil || !info.IsDir() { + return nil + } + out := make(map[string]fileSnapshot) + var totalBytes int64 + _ = filepath.WalkDir(cleanRoot, func(p string, d fs.DirEntry, walkErr error) error { + if walkErr != nil { + return nil + } + if p == cleanRoot { + return nil + } + // Never follow symlinks when snapshotting checkpoints. + if d.Type()&os.ModeSymlink != 0 { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + if d.IsDir() { + if skipCheckpointDir(d.Name()) { + return filepath.SkipDir + } + return nil + } + if !d.Type().IsRegular() { + return nil + } + fi, err := d.Info() + if err != nil { + return nil + } + if fi.Size() > maxRewindCheckpointFileBytes || totalBytes+fi.Size() > maxRewindCheckpointTotalBytes { + return nil + } + rel, err := filepath.Rel(cleanRoot, p) + if err != nil { + return nil + } + relSlash := filepath.ToSlash(filepath.Clean(rel)) + if relSlash == "." || relSlash == ".." || strings.HasPrefix(relSlash, "../") || path.IsAbs(relSlash) { + return nil + } + // Never snapshot You-only configuration files (permissions, tools, models, usage). + if _, isYouOnly := MatchYouOnlyPath(relSlash); isYouOnly { + return nil + } + data, err := readCheckpointFileBounded(p, maxRewindCheckpointFileBytes) + if err != nil { + return nil + } + if int64(len(data)) > maxRewindCheckpointFileBytes || totalBytes+int64(len(data)) > maxRewindCheckpointTotalBytes { + return nil + } + totalBytes += int64(len(data)) + mode := fi.Mode().Perm() + if mode == 0 { + mode = 0o644 + } + out[relSlash] = fileSnapshot{ + exists: true, + data: data, + mode: mode, + hash: sha256.Sum256(data), + } + return nil + }) + return out +} + +func (e *Editor) captureTurnStartCheckpoint() *agentTurnCheckpoint { + if e == nil { + return nil + } + root := e.agentProjectRoot() + cp := &agentTurnCheckpoint{ + root: root, + fullBefore: captureProjectFileTree(root), + } + if e.Doc != nil { + cp.beforeDoc = e.Doc.Clone() + cp.beforeFilePath = e.FilePath + cp.beforeSceneSaved = slices.Clone(e.sceneSaved) + if data, err := e.SaveYAML(); err == nil { + cp.beforeDocYAML = data + } + } + if e.Project != nil { + cp.beforeProject = e.Project.Clone() + cp.beforeProjectSaved = slices.Clone(e.projectSaved) + if data, err := project.Encode(e.Project); err == nil { + cp.beforeProjectYAML = data + } + } + return cp +} + +func (e *Editor) finalizeTurnCheckpoint(turnID string) { + if e == nil || turnID == "" { + return + } + turn := e.findAgentTurn(turnID) + if turn != nil { + turn.SessionIDAfter = e.agent.sessionID + } + if e.agent.checkpoints == nil { + return + } + cp := e.agent.checkpoints[turnID] + if cp == nil || cp.finalized { + return + } + cp.finalized = true + + var changed []string + seen := make(map[string]bool) + addChanged := func(p string) { + p = strings.TrimSpace(p) + if p == "" || seen[p] { + return + } + seen[p] = true + changed = append(changed, p) + } + + if cp.root != "" { + curFiles := captureProjectFileTree(cp.root) + cp.beforeFiles = make(map[string]fileSnapshot) + for rel, before := range cp.fullBefore { + after := curFiles[rel] + if !before.equal(after) { + cp.beforeFiles[rel] = before + addChanged(rel) + } + } + for rel := range curFiles { + if _, existed := cp.fullBefore[rel]; !existed { + cp.beforeFiles[rel] = fileSnapshot{exists: false} + addChanged(rel) + } + } + cp.fullBefore = nil + + // If the turn updated the open scene or game.yaml directly on disk while clean in memory, + // sync the in-memory document now so the viewport updates immediately and a delayed disk-watch + // reload cannot bleed into the next turn's checkpoint. + if e.FilePath != "" && e.isPathAffected(cp.root, e.FilePath, cp.beforeFiles) && !e.SceneDirty() { + if data, err := os.ReadFile(e.FilePath); err == nil { + if doc, err := sceneformat.ParseWith(data, sceneformat.ParseOptions{ + File: e.FilePath, + Components: e.components, + PhysicsLayers: e.PhysicsLayers(), + }); err == nil { + e.setDoc(doc) + if enc, err := sceneformat.Encode(doc); err == nil { + e.sceneSaved = enc + } + e.recordSceneDiskSnapshot(e.FilePath, data) + e.Rebuild() + e.pruneSelection() + e.syncActiveTab() + } + } + } + if e.ProjectPath != "" && e.isPathAffected(cp.root, e.ProjectPath, cp.beforeFiles) && !e.ProjectDirty() { + if data, err := os.ReadFile(e.ProjectPath); err == nil { + if f, err := project.Parse(data); err == nil { + e.Project = f + if enc, err := project.Encode(f); err == nil { + e.projectSaved = enc + } + e.syncAudioMixer() + e.recordProjectDiskSnapshot(e.ProjectPath, data) + } + } + } + } + + if cp.beforeDoc != nil && e.Doc != nil && sameCleanPath(e.FilePath, cp.beforeFilePath) { + if curYAML, err := e.SaveYAML(); err == nil && !bytes.Equal(curYAML, cp.beforeDocYAML) { + cp.docChanged = true + sceneRel := e.ScenePath + if sceneRel == "" && e.FilePath != "" && cp.root != "" { + if rel, err := filepath.Rel(cp.root, e.FilePath); err == nil { + relSlash := filepath.ToSlash(filepath.Clean(rel)) + if relSlash != "." && !strings.HasPrefix(relSlash, "../") { + sceneRel = relSlash + } + } + } + if sceneRel == "" { + sceneRel = e.SceneLabel() + } + addChanged(sceneRel) + } + } + cp.beforeDocYAML = nil + + if cp.beforeProject != nil && e.Project != nil { + if curProjYAML, err := project.Encode(e.Project); err == nil && !bytes.Equal(curProjYAML, cp.beforeProjectYAML) { + cp.projectChanged = true + addChanged(project.FileName) + } + } + cp.beforeProjectYAML = nil + + slices.Sort(changed) + if turn != nil { + turn.ChangedFiles = changed + } + if len(changed) > 0 { + e.filesRev++ + } +} + +func (e *Editor) agentPriorTurnSummaries() []AgentTurnSummary { + if e == nil || len(e.agent.turns) == 0 { + return nil + } + out := make([]AgentTurnSummary, 0, len(e.agent.turns)) + for _, t := range e.agent.turns { + out = append(out, AgentTurnSummary{ + ID: t.ID, + Prompt: t.Prompt, + Summary: t.Summary, + ChangedFiles: slices.Clone(t.ChangedFiles), + }) + } + return out +} + +func (e *Editor) findAgentTurnIndex(turnID string) int { + if e == nil || turnID == "" { + return -1 + } + for i := range e.agent.turns { + if e.agent.turns[i].ID == turnID { + return i + } + } + return -1 +} + +// AgentRewindOpenTurnID returns the turn ID whose rewind popover is currently open, or empty. +func (e *Editor) AgentRewindOpenTurnID() string { + if e == nil { + return "" + } + return e.agent.rewindOpenTurnID +} + +// AgentRewindMode returns the currently selected radio option in the rewind popover. +func (e *Editor) AgentRewindMode() AgentRewindMode { + if e == nil || e.agent.rewindMode == "" { + return AgentRewindBoth + } + return e.agent.rewindMode +} + +// SetAgentRewindMode selects one of the three choices in the rewind popover. +func (e *Editor) SetAgentRewindMode(mode AgentRewindMode) { + if e == nil { + return + } + switch mode { + case AgentRewindBoth, AgentRewindFilesOnly, AgentRewindConversationOnly: + default: + return + } + if e.agent.rewindMode == mode { + return + } + e.agent.rewindMode = mode + e.notify() +} + +// OpenAgentRewindPopover opens the "Rewind to before this message" popover for turnID. +func (e *Editor) OpenAgentRewindPopover(turnID string) bool { + if e == nil || e.playing || e.AgentWorking() || e.agent.mode == AgentModeNone { + return false + } + if e.findAgentTurnIndex(turnID) < 0 { + return false + } + if e.agent.rewindOpenTurnID != turnID { + e.agent.rewindMode = AgentRewindBoth + } + if e.agentThreads.switcherOpen { + e.agentThreads.switcherOpen = false + e.agentThreads.switcherQuery = "" + e.agentThreads.rev++ + } + e.agentComposer.pickerOpen = false + e.agentComposer.pickerOpenedByAt = false + e.agentComposer.pickerActiveIndex = 0 + e.agentComposer.breakdownOpen = false + e.agentComposer.hoveredChipID = "" + e.agent.rewindOpenTurnID = turnID + e.notify() + return true +} + +// ToggleAgentRewindPopover opens the rewind popover for turnID, or closes it if already open for turnID. +func (e *Editor) ToggleAgentRewindPopover(turnID string) bool { + if e == nil { + return false + } + if e.agent.rewindOpenTurnID == turnID && turnID != "" { + e.CloseAgentRewindPopover() + return false + } + return e.OpenAgentRewindPopover(turnID) +} + +// CloseAgentRewindPopover closes the rewind popover without rewinding. +func (e *Editor) CloseAgentRewindPopover() { + if e == nil || e.agent.rewindOpenTurnID == "" { + return + } + e.agent.rewindOpenTurnID = "" + e.notify() +} + +// AgentRewindPreview computes the distinct files and dropped turn count for rewinding to before turnID. +func (e *Editor) AgentRewindPreview(turnID string) (AgentRewindPreview, bool) { + if e == nil { + return AgentRewindPreview{}, false + } + idx := e.findAgentTurnIndex(turnID) + if idx < 0 { + return AgentRewindPreview{}, false + } + seen := make(map[string]bool) + var files []string + for j := idx; j < len(e.agent.turns); j++ { + t := e.agent.turns[j] + for _, f := range t.ChangedFiles { + if f != "" && !seen[f] { + seen[f] = true + files = append(files, f) + } + } + if e.agent.checkpoints != nil { + if cp := e.agent.checkpoints[t.ID]; cp != nil { + for rel := range cp.beforeFiles { + if rel != "" && !seen[rel] { + seen[rel] = true + files = append(files, rel) + } + } + } + } + } + slices.Sort(files) + return AgentRewindPreview{ + TurnID: turnID, + TurnIndex: idx, + Prompt: e.agent.turns[idx].Prompt, + ChangedFiles: files, + DroppedTurns: len(e.agent.turns) - idx, + }, true +} + +// AgentRewindBanner returns the active post-rewind banner state (shown above the composer with Redo), if any. +func (e *Editor) AgentRewindBanner() (AgentRewindState, bool) { + if e == nil || e.agent.lastRewind == nil { + return AgentRewindState{}, false + } + cp := e.agent.lastRewind.state + cp.FilesRestored = slices.Clone(cp.FilesRestored) + return cp, true +} + +// CanRedoAgentRewind reports whether a rewound turn can currently be restored with RedoAgentRewind. +func (e *Editor) CanRedoAgentRewind() bool { + return e != nil && e.agent.lastRewind != nil && !e.playing && !e.AgentWorking() && e.agent.mode != AgentModeNone +} + +// DismissAgentRewindBanner hides the post-rewind banner without redoing. +func (e *Editor) DismissAgentRewindBanner() { + if e == nil || e.agent.lastRewind == nil { + return + } + e.agent.lastRewind = nil + e.agent.composerHighlighted = false + e.notify() +} + +// AgentComposerRewound reports whether the composer currently holds a freshly rewound message highlighted with the Spec accent ring. +func (e *Editor) AgentComposerRewound() bool { + return e != nil && e.agent.composerHighlighted +} + +// ConfirmAgentRewind executes the rewind selected in the currently open rewind popover. +func (e *Editor) ConfirmAgentRewind() error { + if e == nil { + return errors.New("editor: nil editor") + } + if e.agent.rewindOpenTurnID == "" { + return errors.New("editor: no rewind popover is open") + } + return e.RewindAgentTurn(e.agent.rewindOpenTurnID, e.AgentRewindMode()) +} + +// RewindAgentTurn rewinds the active agent thread to before turnID using mode: +// - AgentRewindBoth restores files from the turns' checkpoints and drops the target and later turns (restoring the session ID from before turnID). +// - AgentRewindFilesOnly restores files from the turns' checkpoints while keeping the conversation thread and session unchanged. +// - AgentRewindConversationOnly drops the target and later turns (and restores the session ID from before turnID) while keeping all files untouched. +// +// In all modes, the rewound message returns to the composer and a post-rewind banner with Redo is shown. +func (e *Editor) RewindAgentTurn(turnID string, mode AgentRewindMode) error { + if e == nil { + return errors.New("editor: nil editor") + } + if e.playing { + return ErrPlaying + } + if e.agent.mode == AgentModeNone { + return errors.New("editor: agent is disabled") + } + if e.AgentWorking() { + return errors.New("editor: cannot rewind while the agent is working") + } + switch mode { + case AgentRewindBoth, AgentRewindFilesOnly, AgentRewindConversationOnly: + default: + return fmt.Errorf("editor: unknown rewind mode %q", mode) + } + idx := e.findAgentTurnIndex(turnID) + if idx < 0 { + return fmt.Errorf("editor: unknown agent turn %q", turnID) + } + + preview, _ := e.AgentRewindPreview(turnID) + targetTurn := e.agent.turns[idx] + + restoreFiles := mode == AgentRewindBoth || mode == AgentRewindFilesOnly + restoreConv := mode == AgentRewindBoth || mode == AgentRewindConversationOnly + + // Collect the earliest pre-turn file & document snapshots across turns [idx..len-1]. + var root string + targetBeforeFiles := make(map[string]fileSnapshot) + var beforeDoc *sceneformat.SceneDoc + var beforeSceneSaved []byte + var beforeFilePath string + var docChanged bool + var beforeProject *project.File + var beforeProjectSaved []byte + var projectChanged bool + + for j := idx; j < len(e.agent.turns); j++ { + if e.agent.checkpoints == nil { + continue + } + cp := e.agent.checkpoints[e.agent.turns[j].ID] + if cp == nil { + continue + } + if root == "" && cp.root != "" { + root = cp.root + } + for rel, snap := range cp.beforeFiles { + if _, exists := targetBeforeFiles[rel]; !exists { + targetBeforeFiles[rel] = snap + } + } + if cp.docChanged && !docChanged && cp.beforeDoc != nil && sameCleanPath(e.FilePath, cp.beforeFilePath) { + docChanged = true + beforeDoc = cp.beforeDoc.Clone() + beforeSceneSaved = slices.Clone(cp.beforeSceneSaved) + beforeFilePath = cp.beforeFilePath + } + if cp.projectChanged && !projectChanged && cp.beforeProject != nil { + projectChanged = true + beforeProject = cp.beforeProject.Clone() + beforeProjectSaved = slices.Clone(cp.beforeProjectSaved) + } + } + if root == "" { + root = e.agentProjectRoot() + } + + // Clone current thread state for Redo before mutating anything. + prevDraft := e.composerDraft + if prevDraft == "" { + prevDraft = e.agent.composerText + } + rec := &agentRewindRecord{ + state: AgentRewindState{ + TurnID: turnID, + TurnIndex: idx, + Mode: mode, + Prompt: targetTurn.Prompt, + FilesRestored: slices.Clone(preview.ChangedFiles), + TurnsDropped: preview.DroppedTurns, + }, + root: root, + previousComposerText: prevDraft, + previousTurns: e.AgentTurns(), + previousSessionID: e.agent.sessionID, + previousCheckpoints: cloneCheckpointMap(e.agent.checkpoints), + previousLiveStopped: e.agent.liveStopped, + } + + if restoreFiles { + // Snapshot the current disk state of every affected file so Redo can restore it byte for byte. + if root != "" && len(targetBeforeFiles) > 0 { + redoFiles, err := snapshotDiskFiles(root, targetBeforeFiles) + if err != nil { + return err + } + rec.redoFiles = redoFiles + } + if e.Doc != nil && (docChanged || e.isPathAffected(root, e.FilePath, targetBeforeFiles)) { + rec.hadDocRestore = true + rec.redoDoc = e.Doc.Clone() + rec.redoSceneSaved = slices.Clone(e.sceneSaved) + rec.redoFilePath = e.FilePath + } + if e.Project != nil && (projectChanged || e.isPathAffected(root, e.ProjectPath, targetBeforeFiles)) { + rec.hadProjectRestore = true + rec.redoProject = e.Project.Clone() + rec.redoProjectSaved = slices.Clone(e.projectSaved) + } + + // Apply file checkpoint restoration to disk atomically (with rollback on error). + if root != "" && len(targetBeforeFiles) > 0 { + if err := applyFileSnapshots(root, targetBeforeFiles, rec.redoFiles); err != nil { + return err + } + rec.filesRestoredCount = len(targetBeforeFiles) + } + + if e.HistoryPreviewActive() { + e.ExitHistoryPreview() + } + + // Keep open scene, inactive tabs, project, and file browser in sync with the restored files. + e.syncEditorAfterFileRestore(root, targetBeforeFiles, docChanged, beforeFilePath, beforeDoc, beforeSceneSaved, projectChanged, beforeProject, beforeProjectSaved) + } else { + rec.state.FilesRestored = nil + } + + if restoreConv { + for j := idx; j < len(e.agent.turns); j++ { + id := e.agent.turns[j].ID + if e.agent.checkpoints != nil { + delete(e.agent.checkpoints, id) + } + if e.agent.pointingTurnID == id { + e.agent.pointingTurnID = "" + } + if e.agent.openReviewTurnID == id { + e.agent.openReviewTurnID = "" + } + } + e.agent.turns = e.agent.turns[:idx] + e.agent.sessionID = targetTurn.SessionIDBefore + if targetTurn.ThreadID != "" { + if t := e.findPersistedAgentThread(targetTurn.ThreadID); t != nil { + rec.threadID = t.ID + rec.previousThreadSessionID = t.SessionID + rec.hadThreadSession = true + if t.SessionID != targetTurn.SessionIDBefore { + t.SessionID = targetTurn.SessionIDBefore + _ = e.persistAgentThread(t) + e.agentThreads.rev++ + } + } else if e.agentThreads.draftThread != nil && e.agentThreads.draftThread.ID == targetTurn.ThreadID { + rec.threadID = e.agentThreads.draftThread.ID + rec.previousThreadSessionID = e.agentThreads.draftThread.SessionID + rec.hadThreadSession = true + if e.agentThreads.draftThread.SessionID != targetTurn.SessionIDBefore { + e.agentThreads.draftThread.SessionID = targetTurn.SessionIDBefore + e.agentThreads.rev++ + } + } + } + if e.agent.openRequest != nil { + e.agent.openRequest = nil + } + e.agent.liveStopped = false + e.agent.liveDeniedKeys = nil + e.agent.liveQueuedFollowUps = nil + e.agent.liveActivity = "" + e.restoreIdleAgentStatus() + } else { + rec.state.TurnsDropped = 0 + if restoreFiles { + for j := idx; j < len(e.agent.turns); j++ { + if e.agent.turns[j].PendingReview != nil && !e.agent.turns[j].PendingReview.Reverted { + e.agent.turns[j].PendingReview.Kept = false + e.agent.turns[j].PendingReview.Reverted = true + } + if e.agent.turns[j].Review != nil && !e.agent.turns[j].Review.Discarded { + e.agent.turns[j].Review.Kept = false + e.agent.turns[j].Review.Discarded = true + } + } + } + } + + if targetTurn.Prompt != "" { + e.composerDraft = targetTurn.Prompt + e.agent.composerText = targetTurn.Prompt + e.agent.composerHighlighted = true + e.agentComposer.pickerOpen = false + e.agentComposer.pickerOpenedByAt = false + e.agentComposer.pickerQuery = "" + e.agentComposer.pickerActiveIndex = 0 + e.agentComposer.breakdownOpen = false + e.agentComposer.hoveredChipID = "" + } else { + e.agent.composerHighlighted = false + } + e.agent.rewindOpenTurnID = "" + e.agent.lastRewind = rec + e.agent.turnChangeSeq++ + e.agent.liveAnnouncement = e.formatRewindBannerText(rec.state) + e.Status = e.agent.liveAnnouncement + e.scheduleAutoSaveIfNeeded() + e.notify() + return nil +} + +// RedoAgentRewind restores the files, conversation turns, session ID, and composer draft from the last RewindAgentTurn. +func (e *Editor) RedoAgentRewind() error { + if e == nil { + return errors.New("editor: nil editor") + } + if e.playing { + return ErrPlaying + } + if e.agent.mode == AgentModeNone { + return errors.New("editor: agent is disabled") + } + if e.AgentWorking() { + return errors.New("editor: cannot redo rewind while the agent is working") + } + rec := e.agent.lastRewind + if rec == nil { + return errors.New("editor: nothing to redo") + } + + restoreFiles := rec.state.Mode == AgentRewindBoth || rec.state.Mode == AgentRewindFilesOnly + restoreConv := rec.state.Mode == AgentRewindBoth || rec.state.Mode == AgentRewindConversationOnly + + if restoreFiles { + if rec.root != "" && len(rec.redoFiles) > 0 { + rollback, err := snapshotDiskFiles(rec.root, rec.redoFiles) + if err != nil { + return err + } + if err := applyFileSnapshots(rec.root, rec.redoFiles, rollback); err != nil { + return err + } + } + if e.HistoryPreviewActive() { + e.ExitHistoryPreview() + } + e.syncEditorAfterFileRestore( + rec.root, + rec.redoFiles, + rec.hadDocRestore, + rec.redoFilePath, + rec.redoDoc, + rec.redoSceneSaved, + rec.hadProjectRestore, + rec.redoProject, + rec.redoProjectSaved, + ) + } + + if restoreConv { + e.agent.turns = cloneAgentTurns(rec.previousTurns) + e.agent.sessionID = rec.previousSessionID + e.agent.checkpoints = cloneCheckpointMap(rec.previousCheckpoints) + e.agent.liveStopped = rec.previousLiveStopped + if rec.hadThreadSession && rec.threadID != "" { + if t := e.findPersistedAgentThread(rec.threadID); t != nil { + if t.SessionID != rec.previousThreadSessionID { + t.SessionID = rec.previousThreadSessionID + _ = e.persistAgentThread(t) + e.agentThreads.rev++ + } + } else if e.agentThreads.draftThread != nil && e.agentThreads.draftThread.ID == rec.threadID { + if e.agentThreads.draftThread.SessionID != rec.previousThreadSessionID { + e.agentThreads.draftThread.SessionID = rec.previousThreadSessionID + e.agentThreads.rev++ + } + } + } + e.restoreIdleAgentStatus() + } else if restoreFiles { + prevByID := make(map[string]AgentTurn, len(rec.previousTurns)) + for _, pt := range rec.previousTurns { + prevByID[pt.ID] = pt + } + for j := rec.state.TurnIndex; j >= 0 && j < len(e.agent.turns); j++ { + if prev, ok := prevByID[e.agent.turns[j].ID]; ok { + cp := cloneAgentTurn(prev) + e.agent.turns[j].PendingReview = cp.PendingReview + e.agent.turns[j].Review = cp.Review + } + } + } + + e.composerDraft = rec.previousComposerText + e.agent.composerText = rec.previousComposerText + e.agent.composerHighlighted = false + e.agentComposer.pickerOpen = false + e.agentComposer.pickerOpenedByAt = false + e.agentComposer.pickerQuery = "" + e.agentComposer.pickerActiveIndex = 0 + e.agentComposer.breakdownOpen = false + e.agentComposer.hoveredChipID = "" + e.agent.rewindOpenTurnID = "" + e.agent.lastRewind = nil + e.agent.turnChangeSeq++ + e.updateAgentAnnouncement() + e.Status = e.T("agent.rewind.redidStatus") + e.scheduleAutoSaveIfNeeded() + e.notify() + return nil +} + +func cloneAgentTurns(turns []AgentTurn) []AgentTurn { + if len(turns) == 0 { + return nil + } + out := make([]AgentTurn, len(turns)) + for i, t := range turns { + out[i] = cloneAgentTurn(t) + } + return out +} + +func cloneCheckpointMap(m map[string]*agentTurnCheckpoint) map[string]*agentTurnCheckpoint { + if len(m) == 0 { + return nil + } + out := make(map[string]*agentTurnCheckpoint, len(m)) + for k, v := range m { + out[k] = v + } + return out +} + +func readCheckpointFileBounded(abs string, maxBytes int64) ([]byte, error) { + f, err := os.Open(abs) + if err != nil { + return nil, err + } + defer f.Close() + data, err := io.ReadAll(io.LimitReader(f, maxBytes+1)) + if err != nil { + return nil, err + } + if int64(len(data)) > maxBytes { + return nil, fmt.Errorf("editor: checkpoint file %q exceeds %d byte limit", filepath.Base(abs), maxBytes) + } + return data, nil +} + +func resolveSafeCheckpointPath(root, relSlash string) (string, error) { + if root == "" { + return "", errors.New("editor: checkpoint root is empty") + } + if strings.ContainsAny(relSlash, "\\\x00") { + return "", fmt.Errorf("editor: invalid checkpoint path %q", relSlash) + } + cleanRoot := filepath.Clean(root) + cleanRel := path.Clean(relSlash) + if cleanRel == "" || cleanRel == "." || cleanRel == ".." || strings.HasPrefix(cleanRel, "../") || path.IsAbs(cleanRel) { + return "", fmt.Errorf("editor: invalid checkpoint path %q", relSlash) + } + parts := strings.Split(cleanRel, "/") + for _, seg := range parts { + if skipCheckpointDir(seg) { + return "", fmt.Errorf("editor: refusing to touch protected path %q", relSlash) + } + } + if _, isYouOnly := MatchYouOnlyPath(cleanRel); isYouOnly { + return "", fmt.Errorf("editor: refusing to touch You-only file %q", relSlash) + } + // Verify no existing ancestor component or target inside root is a symlink. + cur := cleanRoot + for _, seg := range parts { + cur = filepath.Join(cur, seg) + fi, err := os.Lstat(cur) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + break + } + return "", err + } + if fi.Mode()&os.ModeSymlink != 0 { + return "", fmt.Errorf("editor: refusing to follow symlink at %q", relSlash) + } + } + abs := filepath.Join(cleanRoot, filepath.FromSlash(cleanRel)) + relCheck, err := filepath.Rel(cleanRoot, abs) + if err != nil || relCheck == ".." || strings.HasPrefix(relCheck, ".."+string(os.PathSeparator)) { + return "", fmt.Errorf("editor: checkpoint path %q escapes project root", relSlash) + } + if resolvedRoot, ok := resolvePathThroughExistingAncestors(cleanRoot); ok { + resolvedAbs, okAbs := resolvePathThroughExistingAncestors(abs) + if !okAbs { + return "", fmt.Errorf("editor: cannot resolve checkpoint path %q", relSlash) + } + realRel, relErr := filepath.Rel(resolvedRoot, resolvedAbs) + if relErr != nil || realRel == "." || realRel == ".." || strings.HasPrefix(realRel, ".."+string(os.PathSeparator)) { + return "", fmt.Errorf("editor: checkpoint path %q escapes project root", relSlash) + } + } + return abs, nil +} + +func snapshotDiskFiles(root string, keys map[string]fileSnapshot) (map[string]fileSnapshot, error) { + out := make(map[string]fileSnapshot, len(keys)) + var totalBytes int64 + for rel := range keys { + abs, err := resolveSafeCheckpointPath(root, rel) + if err != nil { + return nil, err + } + fi, err := os.Lstat(abs) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + out[rel] = fileSnapshot{exists: false} + continue + } + return nil, err + } + if fi.Mode()&os.ModeSymlink != 0 { + return nil, fmt.Errorf("editor: refusing to snapshot symlink %q", rel) + } + if !fi.Mode().IsRegular() { + return nil, fmt.Errorf("editor: refusing to snapshot non-regular file %q", rel) + } + if fi.Size() > maxRewindCheckpointFileBytes || totalBytes+fi.Size() > maxRewindCheckpointTotalBytes { + return nil, fmt.Errorf("editor: file %q exceeds checkpoint size limit", rel) + } + data, err := readCheckpointFileBounded(abs, maxRewindCheckpointFileBytes) + if err != nil { + return nil, err + } + if totalBytes+int64(len(data)) > maxRewindCheckpointTotalBytes { + return nil, fmt.Errorf("editor: rewind snapshot exceeds %d byte total limit", maxRewindCheckpointTotalBytes) + } + totalBytes += int64(len(data)) + mode := fi.Mode().Perm() + if mode == 0 { + mode = 0o644 + } + out[rel] = fileSnapshot{ + exists: true, + data: data, + mode: mode, + hash: sha256.Sum256(data), + } + } + return out, nil +} + +func applyFileSnapshots(root string, target, rollback map[string]fileSnapshot) error { + cleanRoot := filepath.Clean(root) + rels := make([]string, 0, len(target)) + for rel := range target { + rels = append(rels, rel) + } + slices.Sort(rels) + + applied := make([]string, 0, len(rels)) + rollbackApplied := func() { + for i := len(applied) - 1; i >= 0; i-- { + rel := applied[i] + orig, ok := rollback[rel] + if !ok { + continue + } + abs, err := resolveSafeCheckpointPath(cleanRoot, rel) + if err != nil { + continue + } + if orig.exists { + _ = os.MkdirAll(filepath.Dir(abs), 0o755) + _ = writeFileAtomic(abs, orig.data) + if orig.mode != 0 { + _ = os.Chmod(abs, orig.mode) + } + } else { + if fi, lerr := os.Lstat(abs); lerr == nil && !fi.IsDir() && fi.Mode()&os.ModeSymlink == 0 { + _ = os.Remove(abs) + pruneEmptyParents(cleanRoot, filepath.Dir(abs)) + } + } + } + } + + for _, rel := range rels { + snap := target[rel] + abs, err := resolveSafeCheckpointPath(cleanRoot, rel) + if err != nil { + rollbackApplied() + return err + } + if snap.exists { + if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil { + rollbackApplied() + return err + } + if err := writeFileAtomic(abs, snap.data); err != nil { + rollbackApplied() + return err + } + if snap.mode != 0 { + _ = os.Chmod(abs, snap.mode) + } + } else { + if fi, lerr := os.Lstat(abs); lerr == nil { + if fi.IsDir() { + rollbackApplied() + return fmt.Errorf("editor: refusing to remove directory at checkpoint file path %q", rel) + } + if fi.Mode()&os.ModeSymlink != 0 { + rollbackApplied() + return fmt.Errorf("editor: refusing to remove symlink at checkpoint file path %q", rel) + } + } else if !errors.Is(lerr, os.ErrNotExist) { + rollbackApplied() + return lerr + } + if err := os.Remove(abs); err != nil && !errors.Is(err, os.ErrNotExist) { + rollbackApplied() + return err + } + pruneEmptyParents(cleanRoot, filepath.Dir(abs)) + } + applied = append(applied, rel) + } + return nil +} + +func pruneEmptyParents(root, dir string) { + cleanRoot := filepath.Clean(root) + cur := filepath.Clean(dir) + for cur != cleanRoot && strings.HasPrefix(cur, cleanRoot+string(os.PathSeparator)) { + fi, err := os.Lstat(cur) + if err != nil || !fi.IsDir() || fi.Mode()&os.ModeSymlink != 0 { + return + } + entries, err := os.ReadDir(cur) + if err != nil || len(entries) > 0 { + return + } + if err := os.Remove(cur); err != nil { + return + } + cur = filepath.Dir(cur) + } +} + +func (e *Editor) isPathAffected(root, absPath string, files map[string]fileSnapshot) bool { + if root == "" || absPath == "" || len(files) == 0 { + return false + } + rel, err := filepath.Rel(filepath.Clean(root), filepath.Clean(absPath)) + if err != nil { + return false + } + relSlash := filepath.ToSlash(filepath.Clean(rel)) + _, ok := files[relSlash] + return ok +} + +func (e *Editor) syncEditorAfterFileRestore( + root string, + restoredFiles map[string]fileSnapshot, + docChanged bool, + expectedFilePath string, + fallbackDoc *sceneformat.SceneDoc, + fallbackSceneSaved []byte, + projectChanged bool, + fallbackProject *project.File, + fallbackProjectSaved []byte, +) { + if e == nil { + return + } + // Reload open project file if it changed on disk or in memory. + if e.ProjectPath != "" && e.isPathAffected(root, e.ProjectPath, restoredFiles) { + if data, err := os.ReadFile(e.ProjectPath); err == nil { + if f, err := project.Parse(data); err == nil { + e.Project = f + if enc, err := project.Encode(f); err == nil { + e.projectSaved = enc + } + e.syncAudioMixer() + e.recordProjectDiskSnapshot(e.ProjectPath, data) + } + } + } else if projectChanged && fallbackProject != nil { + e.Project = fallbackProject.Clone() + e.projectSaved = slices.Clone(fallbackProjectSaved) + e.syncAudioMixer() + } + + // Reload active open scene if its file was restored on disk, or restore in-memory doc snapshot + // when the same scene is still open. + sceneReloaded := false + if e.FilePath != "" && e.isPathAffected(root, e.FilePath, restoredFiles) { + if data, err := os.ReadFile(e.FilePath); err == nil { + if doc, err := sceneformat.ParseWith(data, sceneformat.ParseOptions{ + File: e.FilePath, + Components: e.components, + PhysicsLayers: e.PhysicsLayers(), + }); err == nil { + e.setDoc(doc) + if enc, err := sceneformat.Encode(doc); err == nil { + e.sceneSaved = enc + } + e.recordSceneDiskSnapshot(e.FilePath, data) + sceneReloaded = true + } + } + } + if !sceneReloaded && docChanged && fallbackDoc != nil && sameCleanPath(e.FilePath, expectedFilePath) { + e.setDoc(fallbackDoc.Clone()) + e.sceneSaved = slices.Clone(fallbackSceneSaved) + sceneReloaded = true + } + if sceneReloaded && e.Doc != nil { + e.Rebuild() + e.pruneSelection() + e.syncActiveTab() + } + + // Also refresh any inactive open scene tabs whose backing file was restored. + for i, tab := range e.tabs { + if i == e.activeTab || tab == nil || tab.filePath == "" { + continue + } + if !e.isPathAffected(root, tab.filePath, restoredFiles) { + continue + } + data, err := os.ReadFile(tab.filePath) + if err != nil { + continue + } + doc, err := sceneformat.ParseWith(data, sceneformat.ParseOptions{ + File: tab.filePath, + Components: e.components, + PhysicsLayers: e.PhysicsLayers(), + }) + if err != nil { + continue + } + tab.doc = doc + if enc, err := sceneformat.Encode(doc); err == nil { + tab.sceneSaved = enc + } + tab.sceneDisk = makeDiskSnapshot(tab.filePath, data) + built, buildErr := sceneformat.Build(doc, e.Resolver) + tab.built = built + tab.buildErr = buildErr + } + + e.filesRev++ + e.snapshotProjectTree() + e.invalidateProjectIndex() + e.RefreshChangesCount() + if e.Project != nil { + e.CheckProblems() + } +} + +func truncateRewindPrompt(prompt string, maxRunes int) string { + s := strings.Join(strings.Fields(strings.TrimSpace(prompt)), " ") + runes := []rune(s) + if len(runes) <= maxRunes || maxRunes <= 1 { + return s + } + prefix := string(runes[:maxRunes]) + // Prefer a word boundary when spaces exist (avoid cutting Latin words mid-word). + if runes[maxRunes] != ' ' { + if idx := strings.LastIndex(prefix, " "); idx >= len(prefix)/2 { + prefix = prefix[:idx] + } + } + cut := strings.TrimRight(prefix, " ,.;:!?") + if cut == "" { + cut = string(runes[:maxRunes]) + } + return cut + "…" +} + +func (e *Editor) formatRewindModeLabel(mode AgentRewindMode) string { + switch mode { + case AgentRewindFilesOnly: + return e.T("agent.rewind.modeFiles") + case AgentRewindConversationOnly: + return e.T("agent.rewind.modeConv") + default: + return e.T("agent.rewind.modeBoth") + } +} + +func (e *Editor) formatRewindBannerText(st AgentRewindState) string { + mode := e.formatRewindModeLabel(st.Mode) + prompt := truncateRewindPrompt(st.Prompt, 23) + if prompt == "" { + return e.T("agent.rewind.bannerNoPrompt", l10n.Param("mode", mode)) + } + return e.T("agent.rewind.banner", l10n.Param("mode", mode), l10n.Param("prompt", prompt)) +} + +func (e *Editor) formatRewindBothDetail(preview AgentRewindPreview) string { + files := len(preview.ChangedFiles) + replies := max(1, preview.DroppedTurns) + switch { + case files == 0 && replies == 1: + return e.T("agent.rewind.bothDetailNoFilesOneReply") + case files == 0: + return e.T("agent.rewind.bothDetailNoFilesManyReplies", l10n.Param("replies", replies)) + case files == 1 && replies == 1: + return e.T("agent.rewind.bothDetailOneFileOneReply") + case files == 1: + return e.T("agent.rewind.bothDetailOneFileManyReplies", l10n.Param("replies", replies)) + case replies == 1: + return e.T("agent.rewind.bothDetailManyFilesOneReply", l10n.Param("files", files)) + default: + return e.T("agent.rewind.bothDetailManyFilesManyReplies", l10n.Param("files", files), l10n.Param("replies", replies)) + } +} diff --git a/packages/game/editor/agent_rewind_test.go b/packages/game/editor/agent_rewind_test.go new file mode 100644 index 00000000..dcb54abf --- /dev/null +++ b/packages/game/editor/agent_rewind_test.go @@ -0,0 +1,1229 @@ +package editor_test + +import ( + "context" + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/project" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func setupRewindProject(t *testing.T) (dir string, ed *editor.Editor, sceneFile, coinFile, sparkleFile string) { + t.Helper() + dir = t.TempDir() + proj := &project.File{ + Version: project.CurrentVersion, + Name: "dungeon-run", + ID: "dev.nsgo.dungeon-run", + AppVersion: "0.1.0", + Window: project.Window{Width: 1280, Height: 720}, + } + projData, err := project.Encode(proj) + if err != nil { + t.Fatalf("encode game.yaml: %v", err) + } + if err := os.WriteFile(filepath.Join(dir, "game.yaml"), projData, 0o644); err != nil { + t.Fatal(err) + } + + sceneDoc := &sceneformat.SceneDoc{ + Version: sceneformat.CurrentVersion, + Name: "level_01", + VirtualWidth: 640, + VirtualHeight: 360, + Layers: []sceneformat.LayerDoc{{ + Name: "main", + Objects: []sceneformat.ObjectDoc{ + {ID: "knight", Name: "Knight", X: 96, Y: 182}, + }, + }}, + } + sceneBytes, err := sceneformat.Encode(sceneDoc) + if err != nil { + t.Fatalf("encode scene: %v", err) + } + sceneFile = filepath.Join(dir, "scenes", "level_01.scene.yaml") + if err := os.MkdirAll(filepath.Dir(sceneFile), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(sceneFile, sceneBytes, 0o644); err != nil { + t.Fatal(err) + } + + coinFile = filepath.Join(dir, "prefabs", "coin.prefab.yaml") + if err := os.MkdirAll(filepath.Dir(coinFile), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(coinFile, []byte("version: 1\nname: coin\nspin: false\nbob: false\n"), 0o644); err != nil { + t.Fatal(err) + } + sparkleFile = filepath.Join(dir, "fx", "sparkle.particles.yaml") + + ed, err = editor.New(nil, nil) + if err != nil { + t.Fatalf("editor.New: %v", err) + } + if err := ed.OpenProjectScene(dir, sceneFile); err != nil { + t.Fatalf("OpenProjectScene: %v", err) + } + ed.SetRightRailTab(editor.RightTabAgent) + ed.NotifyAgentMCPConnected(editor.AgentClientInfo{ + ID: "c1", + Name: "claude-code", + Transport: "stdio", + }) + return dir, ed, sceneFile, coinFile, sparkleFile +} + +func waitAgentIdleWithTurns(t *testing.T, app *nsgotest.App, ed *editor.Editor, wantTurns int) { + t.Helper() + app.WaitUntil(5*time.Second, func() bool { + return !ed.AgentWorking() && ed.AgentStatus() == editor.AgentStatusConnected && len(ed.AgentTurns()) == wantTurns + }) + app.Settle() +} + +func TestAgentRewindFilesAndConversationAndRedo(t *testing.T) { + _, ed, sceneFile, coinFile, sparkleFile := setupRewindProject(t) + defer ed.Close() + + prompt1 := "Put three slimes patrolling the lower floor and a short coin trail toward the door." + prompt2 := "Make the coins spin and bob, and give each one a sparkle." + + sceneAfterTurn1 := "" + coinBeforeTurn2 := "version: 1\nname: coin\nspin: false\nbob: false\n" + coinAfterTurn2 := "version: 1\nname: coin\nspin: true\nbob: true\n" + sparkleAfterTurn2 := "version: 1\nname: sparkle\nrate: 24\n" + + ed.AgentRunner = editor.AgentRunnerFunc(func(_ context.Context, req editor.AgentRequest, emit func(editor.AgentEvent)) error { + switch req.Prompt { + case prompt1: + emit(editor.AgentEvent{Kind: editor.AgentEventSession, SessionID: "sess-turn-1"}) + doc := &sceneformat.SceneDoc{ + Version: sceneformat.CurrentVersion, + Name: "level_01", + VirtualWidth: 640, + VirtualHeight: 360, + Layers: []sceneformat.LayerDoc{{ + Name: "main", + Objects: []sceneformat.ObjectDoc{ + {ID: "knight", Name: "Knight", X: 96, Y: 182}, + {ID: "slime_01", Name: "Slime 1", X: 200, Y: 200}, + {ID: "coin_01", Name: "Coin 1", X: 260, Y: 180}, + }, + }}, + } + b, err := sceneformat.Encode(doc) + if err != nil { + return err + } + sceneAfterTurn1 = string(b) + if err := os.WriteFile(sceneFile, b, 0o644); err != nil { + return err + } + emit(editor.AgentEvent{Kind: editor.AgentEventMessage, Text: "Done: 3 slimes and 3 coins, kept."}) + emit(editor.AgentEvent{Kind: editor.AgentEventDone}) + return nil + + case prompt2: + emit(editor.AgentEvent{Kind: editor.AgentEventSession, SessionID: "sess-turn-2"}) + if err := os.WriteFile(coinFile, []byte(coinAfterTurn2), 0o644); err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(sparkleFile), 0o755); err != nil { + return err + } + if err := os.WriteFile(sparkleFile, []byte(sparkleAfterTurn2), 0o644); err != nil { + return err + } + emit(editor.AgentEvent{Kind: editor.AgentEventStep, StepID: "s1", StepTitle: "Added spin and bob to prefabs/coin.prefab.yaml", StepStatus: editor.AgentStepDone}) + emit(editor.AgentEvent{Kind: editor.AgentEventStep, StepID: "s2", StepTitle: "Wrote fx/sparkle.particles.yaml", StepStatus: editor.AgentStepDone}) + emit(editor.AgentEvent{Kind: editor.AgentEventMessage, Text: "Kept · 2 files. The sparkle is louder than you probably want."}) + emit(editor.AgentEvent{Kind: editor.AgentEventDone}) + return nil + default: + return errors.New("unexpected prompt") + } + }) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1280, 860)) + + // Send first request that edits the scene file. + if err := ed.SubmitAgentPrompt(prompt1); err != nil { + t.Fatalf("submit 1: %v", err) + } + waitAgentIdleWithTurns(t, app, ed, 1) + + // Send second request that edits coin.prefab.yaml and creates fx/sparkle.particles.yaml. + if err := ed.SubmitAgentPrompt(prompt2); err != nil { + t.Fatalf("submit 2: %v", err) + } + waitAgentIdleWithTurns(t, app, ed, 2) + + if ed.AgentSessionID() != "sess-turn-2" { + t.Fatalf("session after turn 2 = %q, want sess-turn-2", ed.AgentSessionID()) + } + // Before hovering, Rewind to here trigger should not be shown. + if app.Exists("id:agent-rewind-trigger-1") { + t.Fatal("rewind trigger should stay hidden until hovered or focused") + } + + // Hover message 2 -> "Rewind to here" appears. + app.Hover("id:agent-turn-prompt-1") + app.Settle() + if !app.Exists("id:agent-rewind-trigger-1") { + t.Fatal("hovering sent message did not reveal Rewind to here") + } + if got := agentViewText(t, app, "id:agent-rewind-trigger-1"); got != "Rewind to here" { + t.Fatalf("trigger text = %q, want Rewind to here", got) + } + + // Open rewind popover and inspect its choices. + app.Press("id:agent-rewind-trigger-1") + app.Settle() + if !app.Exists("id:agent-rewind-popover") { + t.Fatal("rewind popover did not open") + } + if got := agentViewText(t, app, "id:agent-rewind-title"); got != "Rewind to before this message" { + t.Fatalf("popover title = %q", got) + } + if got := agentViewText(t, app, "id:agent-rewind-opt-both-detail"); got != "Undo 2 files, drop the reply" { + t.Fatalf("both detail = %q, want Undo 2 files, drop the reply", got) + } + + // Confirm Rewind (default: Files and conversation). + app.Press("id:agent-rewind-confirm") + app.Settle() + + // Files are back to exact post-turn-1 state. + gotScene, err := os.ReadFile(sceneFile) + if err != nil { + t.Fatal(err) + } + if string(gotScene) != sceneAfterTurn1 { + t.Fatalf("scene file after rewind changed unexpectedly:\ngot:\n%s\nwant:\n%s", gotScene, sceneAfterTurn1) + } + gotCoin, err := os.ReadFile(coinFile) + if err != nil { + t.Fatal(err) + } + if string(gotCoin) != coinBeforeTurn2 { + t.Fatalf("coin.prefab.yaml after rewind = %q, want %q", gotCoin, coinBeforeTurn2) + } + if _, err := os.Stat(sparkleFile); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("sparkle.particles.yaml should be removed by rewind, stat err = %v", err) + } + + // Conversation dropped turn 2 and rolled session back to after turn 1. + turns := ed.AgentTurns() + if len(turns) != 1 || turns[0].Prompt != prompt1 { + t.Fatalf("turns after rewind = %+v, want only first turn", turns) + } + if ed.AgentSessionID() != "sess-turn-1" { + t.Fatalf("session after rewind = %q, want sess-turn-1", ed.AgentSessionID()) + } + + // Post-rewind banner with Redo is visible, and composer holds turn 2's prompt. + if !app.Exists("id:agent-rewind-banner") { + t.Fatal("post-rewind banner missing") + } + bannerText := agentViewText(t, app, "id:agent-rewind-banner-text") + if !strings.Contains(bannerText, "Rewound files and conversation to before") { + t.Fatalf("banner text = %q", bannerText) + } + if ed.AgentComposerText() != prompt2 { + t.Fatalf("composer text after rewind = %q, want %q", ed.AgentComposerText(), prompt2) + } + if !ed.AgentComposerRewound() { + t.Fatal("expected composer rewound ring to be active") + } + + // Press Redo -> brings both files and conversation back. + app.Press("id:agent-rewind-redo") + app.Settle() + + gotCoin, err = os.ReadFile(coinFile) + if err != nil { + t.Fatal(err) + } + if string(gotCoin) != coinAfterTurn2 { + t.Fatalf("coin.prefab.yaml after redo = %q, want %q", gotCoin, coinAfterTurn2) + } + gotSparkle, err := os.ReadFile(sparkleFile) + if err != nil { + t.Fatalf("sparkle.particles.yaml missing after redo: %v", err) + } + if string(gotSparkle) != sparkleAfterTurn2 { + t.Fatalf("sparkle.particles.yaml after redo = %q, want %q", gotSparkle, sparkleAfterTurn2) + } + turns = ed.AgentTurns() + if len(turns) != 2 || turns[1].Prompt != prompt2 { + t.Fatalf("turns after redo = %+v, want both turns back", turns) + } + if ed.AgentSessionID() != "sess-turn-2" { + t.Fatalf("session after redo = %q, want sess-turn-2", ed.AgentSessionID()) + } + if app.Exists("id:agent-rewind-banner") { + t.Fatal("rewind banner should clear after Redo") + } + if ed.AgentComposerText() != "" { + t.Fatalf("composer text after redo = %q, want empty", ed.AgentComposerText()) + } +} + +func TestAgentRewindFilesOnlyAndConversationOnlyModes(t *testing.T) { + _, ed, _, coinFile, sparkleFile := setupRewindProject(t) + defer ed.Close() + + coinOrig := "version: 1\nname: coin\nspin: false\nbob: false\n" + coinV1 := "version: 1\nname: coin\nspin: true\nbob: false\n" + coinV2 := "version: 1\nname: coin\nspin: true\nbob: true\n" + sparkleV2 := "version: 1\nname: sparkle\nrate: 24\n" + + ed.AgentRunner = editor.AgentRunnerFunc(func(_ context.Context, req editor.AgentRequest, emit func(editor.AgentEvent)) error { + switch req.Prompt { + case "First tweak": + emit(editor.AgentEvent{Kind: editor.AgentEventSession, SessionID: "s1"}) + if err := os.WriteFile(coinFile, []byte(coinV1), 0o644); err != nil { + return err + } + emit(editor.AgentEvent{Kind: editor.AgentEventMessage, Text: "Enabled spin."}) + emit(editor.AgentEvent{Kind: editor.AgentEventDone}) + case "Second tweak": + emit(editor.AgentEvent{Kind: editor.AgentEventSession, SessionID: "s2"}) + if err := os.WriteFile(coinFile, []byte(coinV2), 0o644); err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(sparkleFile), 0o755); err != nil { + return err + } + if err := os.WriteFile(sparkleFile, []byte(sparkleV2), 0o644); err != nil { + return err + } + emit(editor.AgentEvent{Kind: editor.AgentEventMessage, Text: "Enabled bob and sparkle."}) + emit(editor.AgentEvent{Kind: editor.AgentEventDone}) + } + return nil + }) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1280, 860)) + + if err := ed.SubmitAgentPrompt("First tweak"); err != nil { + t.Fatal(err) + } + waitAgentIdleWithTurns(t, app, ed, 1) + if err := ed.SubmitAgentPrompt("Second tweak"); err != nil { + t.Fatal(err) + } + waitAgentIdleWithTurns(t, app, ed, 2) + + // 1. Files only: restores files to after turn 1, keeps BOTH turns in thread. + app.Hover("id:agent-turn-prompt-1") + app.Settle() + app.Press("id:agent-rewind-trigger-1") + app.Settle() + app.Press("id:agent-rewind-opt-files") + app.Settle() + app.Press("id:agent-rewind-confirm") + app.Settle() + + gotCoin, err := os.ReadFile(coinFile) + if err != nil { + t.Fatal(err) + } + if string(gotCoin) != coinV1 { + t.Fatalf("Files only: coin = %q, want %q", gotCoin, coinV1) + } + if _, err := os.Stat(sparkleFile); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("Files only: sparkle should be removed, err = %v", err) + } + if len(ed.AgentTurns()) != 2 { + t.Fatalf("Files only: thread len = %d, want 2 (conversation kept)", len(ed.AgentTurns())) + } + if ed.AgentSessionID() != "s2" { + t.Fatalf("Files only: session = %q, want s2", ed.AgentSessionID()) + } + if !strings.Contains(agentViewText(t, app, "id:agent-rewind-banner-text"), "files only") { + t.Fatalf("Files only banner = %q", agentViewText(t, app, "id:agent-rewind-banner-text")) + } + + // Redo brings files back. + app.Press("id:agent-rewind-redo") + app.Settle() + gotCoin, _ = os.ReadFile(coinFile) + if string(gotCoin) != coinV2 { + t.Fatalf("Redo after Files only: coin = %q, want %q", gotCoin, coinV2) + } + if _, err := os.Stat(sparkleFile); err != nil { + t.Fatalf("Redo after Files only: sparkle missing: %v", err) + } + + // 2. Conversation only: drops turn 2 from thread, keeps files at v2. + app.Hover("id:agent-turn-prompt-1") + app.Settle() + app.Press("id:agent-rewind-trigger-1") + app.Settle() + app.Press("id:agent-rewind-opt-conv") + app.Settle() + app.Press("id:agent-rewind-confirm") + app.Settle() + + if len(ed.AgentTurns()) != 1 || ed.AgentTurns()[0].Prompt != "First tweak" { + t.Fatalf("Conversation only: turns = %+v, want only first turn", ed.AgentTurns()) + } + if ed.AgentSessionID() != "s1" { + t.Fatalf("Conversation only: session = %q, want s1", ed.AgentSessionID()) + } + gotCoin, _ = os.ReadFile(coinFile) + if string(gotCoin) != coinV2 { + t.Fatalf("Conversation only: coin changed to %q, want untouched %q", gotCoin, coinV2) + } + if _, err := os.Stat(sparkleFile); err != nil { + t.Fatalf("Conversation only: sparkle should remain, err = %v", err) + } + if !strings.Contains(agentViewText(t, app, "id:agent-rewind-banner-text"), "conversation only") { + t.Fatalf("Conversation only banner = %q", agentViewText(t, app, "id:agent-rewind-banner-text")) + } + + // Redo brings conversation back. + app.Press("id:agent-rewind-redo") + app.Settle() + if len(ed.AgentTurns()) != 2 || ed.AgentSessionID() != "s2" { + t.Fatalf("Redo after Conversation only: turns=%d session=%q, want 2 / s2", len(ed.AgentTurns()), ed.AgentSessionID()) + } + + // 3. Rewind to before the very first message (turn 0) with Files and conversation restores initial state. + turn0ID := ed.AgentTurns()[0].ID + if err := ed.RewindAgentTurn(turn0ID, editor.AgentRewindBoth); err != nil { + t.Fatalf("RewindAgentTurn(turn0): %v", err) + } + gotCoin, _ = os.ReadFile(coinFile) + if string(gotCoin) != coinOrig { + t.Fatalf("rewind to before turn 0: coin = %q, want %q", gotCoin, coinOrig) + } + if len(ed.AgentTurns()) != 0 || ed.AgentSessionID() != "" { + t.Fatalf("rewind to before turn 0: turns=%d session=%q, want 0 / empty", len(ed.AgentTurns()), ed.AgentSessionID()) + } + if err := ed.RedoAgentRewind(); err != nil { + t.Fatalf("RedoAgentRewind from turn 0: %v", err) + } + if len(ed.AgentTurns()) != 2 || ed.AgentSessionID() != "s2" { + t.Fatalf("redo from turn 0: turns=%d session=%q, want 2 / s2", len(ed.AgentTurns()), ed.AgentSessionID()) + } +} + +func TestAgentRewindContinuesSessionRebuildsOpenSceneAndGuards(t *testing.T) { + _, ed, sceneFile, _, _ := setupRewindProject(t) + defer ed.Close() + + var mu sync.Mutex + var received []editor.AgentRequest + ed.AgentRunner = editor.AgentRunnerFunc(func(_ context.Context, req editor.AgentRequest, emit func(editor.AgentEvent)) error { + mu.Lock() + received = append(received, req) + mu.Unlock() + switch req.Prompt { + case "Add slime": + emit(editor.AgentEvent{Kind: editor.AgentEventSession, SessionID: "sess-1"}) + raw, err := os.ReadFile(sceneFile) + if err != nil { + return err + } + doc, err := sceneformat.Parse(raw) + if err != nil { + return err + } + doc.Layers[0].Objects = append(doc.Layers[0].Objects, sceneformat.ObjectDoc{ID: "slime_1", Name: "Slime", X: 120, Y: 180}) + b, err := sceneformat.Encode(doc) + if err != nil { + return err + } + if err := os.WriteFile(sceneFile, b, 0o644); err != nil { + return err + } + emit(editor.AgentEvent{Kind: editor.AgentEventDone, Text: "Added slime_1."}) + case "Add boss": + emit(editor.AgentEvent{Kind: editor.AgentEventSession, SessionID: "sess-2"}) + raw, err := os.ReadFile(sceneFile) + if err != nil { + return err + } + doc, err := sceneformat.Parse(raw) + if err != nil { + return err + } + doc.Layers[0].Objects = append(doc.Layers[0].Objects, sceneformat.ObjectDoc{ID: "boss_1", Name: "Boss", X: 300, Y: 180}) + b, err := sceneformat.Encode(doc) + if err != nil { + return err + } + if err := os.WriteFile(sceneFile, b, 0o644); err != nil { + return err + } + emit(editor.AgentEvent{Kind: editor.AgentEventDone, Text: "Added boss_1."}) + case "Add gentle slime instead": + emit(editor.AgentEvent{Kind: editor.AgentEventSession, SessionID: "sess-3"}) + emit(editor.AgentEvent{Kind: editor.AgentEventDone, Text: "Added gentle slime."}) + } + return nil + }) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1280, 820)) + + if err := ed.SubmitAgentPrompt("Add slime"); err != nil { + t.Fatal(err) + } + waitAgentIdleWithTurns(t, app, ed, 1) + if err := ed.SubmitAgentPrompt("Add boss"); err != nil { + t.Fatal(err) + } + waitAgentIdleWithTurns(t, app, ed, 2) + + if obj, _, _ := ed.FindObject("boss_1"); obj == nil { + t.Fatal("boss_1 not present in open scene before rewind") + } + + // Cancel closes popover without rewinding. + turn1ID := ed.AgentTurns()[1].ID + if !ed.OpenAgentRewindPopover(turn1ID) { + t.Fatal("OpenAgentRewindPopover failed") + } + app.Settle() + app.Press("id:agent-rewind-cancel") + app.Settle() + if ed.AgentRewindOpenTurnID() != "" || len(ed.AgentTurns()) != 2 { + t.Fatal("Cancel did not close popover cleanly") + } + + // Play mode refuses rewind. + if err := ed.Play(); err != nil { + t.Fatalf("Play: %v", err) + } + if err := ed.RewindAgentTurn(turn1ID, editor.AgentRewindBoth); !errors.Is(err, editor.ErrPlaying) { + t.Fatalf("RewindAgentTurn during Play = %v, want ErrPlaying", err) + } + if err := ed.Stop(); err != nil { + t.Fatalf("Stop: %v", err) + } + + // Rewind to before "Add boss" -> boss_1 disappears from open scene in memory too, slime_1 remains. + if err := ed.RewindAgentTurn(turn1ID, editor.AgentRewindBoth); err != nil { + t.Fatalf("RewindAgentTurn: %v", err) + } + app.Settle() + if obj, _, _ := ed.FindObject("boss_1"); obj != nil { + t.Fatal("boss_1 still in open scene after rewind") + } + if obj, _, _ := ed.FindObject("slime_1"); obj == nil { + t.Fatal("slime_1 lost from open scene after rewind") + } + + // Edit composer and send a replacement prompt -> continues from session "sess-1" and 1 prior turn! + ed.SetAgentComposerText("Add gentle slime instead") + if ed.AgentComposerRewound() { + t.Fatal("editing composer text should clear rewound highlight ring") + } + if err := ed.SubmitAgentPrompt(""); err != nil { + t.Fatalf("submit replacement: %v", err) + } + waitAgentIdleWithTurns(t, app, ed, 2) + + mu.Lock() + gotReceived := append([]editor.AgentRequest(nil), received...) + mu.Unlock() + if len(gotReceived) != 3 { + t.Fatalf("received %d requests, want 3", len(gotReceived)) + } + if gotReceived[2].SessionID != "sess-1" { + t.Fatalf("continued SessionID = %q, want sess-1", gotReceived[2].SessionID) + } + if len(gotReceived[2].PriorTurns) != 1 || gotReceived[2].PriorTurns[0].Prompt != "Add slime" { + t.Fatalf("continued PriorTurns = %+v, want [Add slime]", gotReceived[2].PriorTurns) + } + if ed.CanRedoAgentRewind() { + t.Fatal("sending a new prompt should clear previous rewind Redo state") + } +} + +// TestAgentRewindScreenshots captures real macOS screenshots of the Rewind popover and post-rewind state +// in both Dark and Light Spec appearances for visual inspection beside docs/design/editor/Checkpoints.dc.html. +func TestAgentRewindScreenshots(t *testing.T) { + _, ed, sceneFile, coinFile, sparkleFile := setupRewindProject(t) + defer ed.Close() + + prompt1 := "Put three slimes patrolling the lower floor and a short coin trail toward the door." + prompt2 := "Make the coins spin and bob, and give each one a sparkle." + + ed.AgentRunner = editor.AgentRunnerFunc(func(_ context.Context, req editor.AgentRequest, emit func(editor.AgentEvent)) error { + switch req.Prompt { + case prompt1: + emit(editor.AgentEvent{Kind: editor.AgentEventSession, SessionID: "s1"}) + b, _ := os.ReadFile(sceneFile) + _ = os.WriteFile(sceneFile, append(b, []byte("\n")...), 0o644) + emit(editor.AgentEvent{Kind: editor.AgentEventMessage, Text: "Done: 3 slimes and 3 coins, kept."}) + emit(editor.AgentEvent{Kind: editor.AgentEventDone}) + case prompt2: + emit(editor.AgentEvent{Kind: editor.AgentEventSession, SessionID: "s2"}) + _ = os.WriteFile(coinFile, []byte("version: 1\nname: coin\nspin: true\nbob: true\n"), 0o644) + _ = os.MkdirAll(filepath.Dir(sparkleFile), 0o755) + _ = os.WriteFile(sparkleFile, []byte("version: 1\nname: sparkle\nrate: 24\n"), 0o644) + emit(editor.AgentEvent{Kind: editor.AgentEventStep, StepID: "1", StepTitle: "Added spin and bob to prefabs/coin.prefab.yaml", StepStatus: editor.AgentStepDone}) + emit(editor.AgentEvent{Kind: editor.AgentEventStep, StepID: "2", StepTitle: "Wrote fx/sparkle.particles.yaml", StepStatus: editor.AgentStepDone}) + emit(editor.AgentEvent{Kind: editor.AgentEventMessage, Text: "Kept · 2 files. The sparkle is louder than you probably want."}) + emit(editor.AgentEvent{Kind: editor.AgentEventDone}) + } + return nil + }) + + ed.SetAppearance(editor.AppearanceDark) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900)) + + if err := ed.SubmitAgentPrompt(prompt1); err != nil { + t.Fatal(err) + } + waitAgentIdleWithTurns(t, app, ed, 1) + if err := ed.SubmitAgentPrompt(prompt2); err != nil { + t.Fatal(err) + } + waitAgentIdleWithTurns(t, app, ed, 2) + + // 1. Dark theme: hover second message + open Rewind popover. + app.Hover("id:agent-turn-prompt-1") + app.Settle() + app.Press("id:agent-rewind-trigger-1") + app.Settle() + + dark := editor.DarkSpecPalette() + if got := app.Find("id:agent-rewind-popover").Style.Background; got != dark.Raised { + t.Fatalf("dark rewind popover bg = %#x, want %#x", uint32(got), uint32(dark.Raised)) + } + if got := app.Find("id:agent-rewind-confirm").Style.Background; got != dark.Accent.Fg { + t.Fatalf("dark rewind confirm bg = %#x, want %#x", uint32(got), uint32(dark.Accent.Fg)) + } + app.Screenshot("agent/rewind-popover-dark") + + // 2. Dark theme: after pressing Rewind -> post-rewind banner with Redo + composer holding prompt2. + app.Press("id:agent-rewind-confirm") + app.Settle() + if got := app.Find("id:agent-rewind-banner").Style.Background; got != dark.Raised { + t.Fatalf("dark rewind banner bg = %#x, want %#x", uint32(got), uint32(dark.Raised)) + } + if got := app.Find("id:agent-composer-card").Style.BorderColor; got != dark.Accent.Edge { + t.Fatalf("dark composer rewound ring = %#x, want %#x", uint32(got), uint32(dark.Accent.Edge)) + } + app.Screenshot("agent/rewind-after-dark") + + // 3. Light theme parity: Redo, switch to Light, verify popover + post-rewind banner tokens and screenshots. + app.Press("id:agent-rewind-redo") + app.Settle() + ed.SetAppearance(editor.AppearanceLight) + app.SetEnvironment(core.Environment{ + OS: core.OSMacOS, + Idiom: core.IdiomDesktop, + Dark: false, + Locale: "en-US", + }) + app.Hover("id:agent-turn-prompt-1") + app.Settle() + app.Press("id:agent-rewind-trigger-1") + app.Settle() + + light := editor.LightSpecPalette() + if got := app.Find("id:agent-rewind-popover").Style.Background; got != light.Raised { + t.Fatalf("light rewind popover bg = %#x, want %#x", uint32(got), uint32(light.Raised)) + } + app.Screenshot("agent/rewind-popover-light") + + app.Press("id:agent-rewind-confirm") + app.Settle() + if got := app.Find("id:agent-rewind-banner").Style.Background; got != light.Raised { + t.Fatalf("light rewind banner bg = %#x, want %#x", uint32(got), uint32(light.Raised)) + } + app.Screenshot("agent/rewind-after-light") +} + +func TestAgentRewindRespectsYouOnlyFilesAndSymlinkGuards(t *testing.T) { + dir, ed, _, coinFile, sparkleFile := setupRewindProject(t) + defer ed.Close() + + permsFile := filepath.Join(dir, "permissions.yaml") + initialPerms := "version: 1\nprofile: balanced\n" + tightenedPerms := "version: 1\nprofile: cautious\n" + if err := os.WriteFile(permsFile, []byte(initialPerms), 0o644); err != nil { + t.Fatal(err) + } + toolsFile := filepath.Join(dir, "tools.yaml") + if err := os.WriteFile(toolsFile, []byte("version: 1\n"), 0o644); err != nil { + t.Fatal(err) + } + + ed.AgentRunner = editor.AgentRunnerFunc(func(_ context.Context, req editor.AgentRequest, emit func(editor.AgentEvent)) error { + switch req.Prompt { + case "Touch coin and permissions": + if err := os.WriteFile(coinFile, []byte("version: 1\nname: coin\nspin: true\nbob: false\n"), 0o644); err != nil { + return err + } + // Simulate user/external tightening permissions.yaml & tools.yaml during the turn: + // checkpoints must ignore You-only files so rewind/redo can never silently loosen them. + if err := os.WriteFile(permsFile, []byte(tightenedPerms), 0o644); err != nil { + return err + } + if err := os.WriteFile(toolsFile, []byte("version: 1\ndisabled: [game_delete_file]\n"), 0o644); err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(sparkleFile), 0o755); err != nil { + return err + } + if err := os.WriteFile(sparkleFile, []byte("version: 1\nname: sparkle\n"), 0o644); err != nil { + return err + } + emit(editor.AgentEvent{Kind: editor.AgentEventDone, Text: "Updated coin."}) + } + return nil + }) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1280, 820)) + + if err := ed.SubmitAgentPrompt("Touch coin and permissions"); err != nil { + t.Fatal(err) + } + waitAgentIdleWithTurns(t, app, ed, 1) + + turn := ed.AgentTurns()[0] + for _, f := range turn.ChangedFiles { + if strings.Contains(f, "permissions.yaml") || strings.Contains(f, "tools.yaml") { + t.Fatalf("You-only file %q leaked into turn ChangedFiles: %v", f, turn.ChangedFiles) + } + } + + // Rewind must restore coin.prefab.yaml and remove sparkle.particles.yaml, + // while leaving tightened permissions.yaml and tools.yaml completely untouched. + if err := ed.RewindAgentTurn(turn.ID, editor.AgentRewindBoth); err != nil { + t.Fatalf("RewindAgentTurn: %v", err) + } + gotPerms, err := os.ReadFile(permsFile) + if err != nil { + t.Fatal(err) + } + if string(gotPerms) != tightenedPerms { + t.Fatalf("permissions.yaml was altered by rewind: got %q, want %q", gotPerms, tightenedPerms) + } + gotTools, err := os.ReadFile(toolsFile) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(gotTools), "game_delete_file") { + t.Fatalf("tools.yaml was altered by rewind: got %q", gotTools) + } + + // Redo restores coin & sparkle, still without touching permissions.yaml. + if err := ed.RedoAgentRewind(); err != nil { + t.Fatalf("RedoAgentRewind: %v", err) + } + + // Replace sparkle.particles.yaml with a directory -> rewind must refuse without deleting the directory or truncating turns. + if err := os.Remove(sparkleFile); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(sparkleFile, 0o755); err != nil { + t.Fatal(err) + } + if err := ed.RewindAgentTurn(turn.ID, editor.AgentRewindBoth); err == nil { + t.Fatal("expected RewindAgentTurn to refuse when checkpoint file path is now a directory") + } + if fi, err := os.Lstat(sparkleFile); err != nil || !fi.IsDir() { + t.Fatalf("directory at sparkle path should still exist: fi=%v err=%v", fi, err) + } + if len(ed.AgentTurns()) != 1 { + t.Fatalf("failed rewind should not truncate turns, got %d", len(ed.AgentTurns())) + } + + // Replace coin.prefab.yaml with a symlink -> rewind must refuse without mutating symlink target or turns. + if runtime.GOOS != "windows" { + if err := os.RemoveAll(sparkleFile); err != nil { + t.Fatal(err) + } + outside := filepath.Join(t.TempDir(), "outside.yaml") + if err := os.WriteFile(outside, []byte("secret"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Remove(coinFile); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, coinFile); err != nil { + t.Fatal(err) + } + if err := ed.RewindAgentTurn(turn.ID, editor.AgentRewindBoth); err == nil { + t.Fatal("expected RewindAgentTurn to refuse symlink at checkpoint path") + } + gotOutside, err := os.ReadFile(outside) + if err != nil || string(gotOutside) != "secret" { + t.Fatalf("outside symlink target altered: %q err=%v", gotOutside, err) + } + if len(ed.AgentTurns()) != 1 { + t.Fatalf("symlink-rejected rewind should not truncate turns, got %d", len(ed.AgentTurns())) + } + } +} + +func TestAgentRewindSceneSwitchStopAndLifecycleGuards(t *testing.T) { + dir, ed, _, coinFile, _ := setupRewindProject(t) + defer ed.Close() + + // Create a second scene so we can test switching scenes between turns and rewind. + scene2Doc := &sceneformat.SceneDoc{ + Version: sceneformat.CurrentVersion, + Name: "level_02", + VirtualWidth: 640, + VirtualHeight: 360, + Layers: []sceneformat.LayerDoc{{ + Name: "main", + Objects: []sceneformat.ObjectDoc{ + {ID: "boss_door", Name: "Boss Door", X: 400, Y: 180}, + }, + }}, + } + scene2Bytes, err := sceneformat.Encode(scene2Doc) + if err != nil { + t.Fatal(err) + } + scene2File := filepath.Join(dir, "scenes", "level_02.scene.yaml") + if err := os.WriteFile(scene2File, scene2Bytes, 0o644); err != nil { + t.Fatal(err) + } + + turnStarted := make(chan struct{}) + turnDone := make(chan struct{}) + ed.AgentRunner = editor.AgentRunnerFunc(func(ctx context.Context, req editor.AgentRequest, emit func(editor.AgentEvent)) error { + switch req.Prompt { + case "Edit open scene in memory": + ed.Post(func() { + _, _ = ed.PlaceObject("main", sceneformat.ObjectDoc{ID: "temp_slime", Name: "Temp Slime", X: 140, Y: 180}) + }) + emit(editor.AgentEvent{Kind: editor.AgentEventDone, Text: "Placed temp_slime."}) + case "Long running turn": + _ = os.WriteFile(coinFile, []byte("version: 1\nname: coin\nspin: true\nbob: true\n"), 0o644) + emit(editor.AgentEvent{Kind: editor.AgentEventStep, StepID: "s1", StepTitle: "Editing coin", StepStatus: editor.AgentStepRunning}) + close(turnStarted) + <-ctx.Done() + // Late event emitted after StopAgentRun must be ignored. + emit(editor.AgentEvent{Kind: editor.AgentEventMessage, Text: "Late stray message"}) + close(turnDone) + return ctx.Err() + } + return nil + }) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1280, 820)) + + // 1. Turn 1 modifies level_01 in memory (unsaved). Then switch to level_02 and rewind Turn 1: + // level_02 must NOT be overwritten with level_01's document! + if err := ed.SubmitAgentPrompt("Edit open scene in memory"); err != nil { + t.Fatal(err) + } + waitAgentIdleWithTurns(t, app, ed, 1) + if err := ed.OpenScene("scenes/level_02.scene.yaml"); err != nil { + t.Fatalf("OpenScene level_02: %v", err) + } + turn0ID := ed.AgentTurns()[0].ID + if err := ed.RewindAgentTurn(turn0ID, editor.AgentRewindBoth); err != nil { + t.Fatalf("RewindAgentTurn after scene switch: %v", err) + } + if ed.Doc.Name != "level_02" { + t.Fatalf("open scene was corrupted by rewind from another scene: got %q, want level_02", ed.Doc.Name) + } + if obj, _, _ := ed.FindObject("boss_door"); obj == nil { + t.Fatal("boss_door missing from level_02 after rewinding level_01 turn") + } + + // 2. Stopping an in-flight turn finalizes its checkpoint, marks Status="stopped", ignores late events, + // and allows rewinding the partial file write. + if err := ed.SubmitAgentPrompt("Long running turn"); err != nil { + t.Fatal(err) + } + <-turnStarted + app.Settle() + if err := ed.RewindAgentTurn(ed.AgentTurns()[0].ID, editor.AgentRewindBoth); err == nil { + t.Fatal("expected rewind to fail while agent is working") + } + ed.StopAgentRun() + <-turnDone + app.Settle() + + turns := ed.AgentTurns() + if len(turns) != 1 || turns[0].Status != "stopped" || !turns[0].Stopped { + t.Fatalf("stopped turn state = %+v, want Status=stopped", turns) + } + if strings.Contains(turns[0].Summary, "Late stray message") { + t.Fatalf("late event leaked into stopped turn: %q", turns[0].Summary) + } + if err := ed.RewindAgentTurn(turns[0].ID, editor.AgentRewindBoth); err != nil { + t.Fatalf("RewindAgentTurn(stopped turn): %v", err) + } + gotCoin, err := os.ReadFile(coinFile) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(gotCoin), "spin: false") { + t.Fatalf("rewinding stopped turn did not restore coin.prefab.yaml: %q", gotCoin) + } + + // 3. Lifecycle guards: switching away from Agent tab or entering Play closes the rewind popover. + if err := ed.RedoAgentRewind(); err != nil { + t.Fatalf("RedoAgentRewind: %v", err) + } + stoppedID := ed.AgentTurns()[0].ID + if !ed.OpenAgentRewindPopover(stoppedID) { + t.Fatal("OpenAgentRewindPopover failed") + } + ed.SetRightRailTab(editor.RightTabInspector) + if ed.AgentRewindOpenTurnID() != "" { + t.Fatal("switching away from Agent tab should close rewind popover") + } + ed.SetRightRailTab(editor.RightTabAgent) + if !ed.OpenAgentRewindPopover(stoppedID) { + t.Fatal("reopening rewind popover failed") + } + if err := ed.Play(); err != nil { + t.Fatalf("Play: %v", err) + } + if ed.AgentRewindOpenTurnID() != "" { + t.Fatal("entering Play should close rewind popover") + } + if err := ed.Stop(); err != nil { + t.Fatalf("Stop: %v", err) + } + + // 4. Rewinding files while HistoryPreview is active exits HistoryPreview cleanly. + if _, err := ed.PlaceObject("main", sceneformat.ObjectDoc{ID: "hist_obj", Name: "HistObj", X: 20, Y: 20}); err != nil { + t.Fatal(err) + } + entries := ed.HistoryEntries() + if len(entries) > 0 { + if err := ed.PreviewHistoryEntry(entries[len(entries)-1].ID); err != nil { + t.Fatalf("PreviewHistoryEntry: %v", err) + } + if !ed.HistoryPreviewActive() { + t.Fatal("expected HistoryPreviewActive == true") + } + if err := ed.RewindAgentTurn(stoppedID, editor.AgentRewindFilesOnly); err != nil { + t.Fatalf("RewindAgentTurn during HistoryPreview: %v", err) + } + if ed.HistoryPreviewActive() { + t.Fatal("rewinding files should exit HistoryPreview") + } + } + + // 5. Radio option switching inside popover updates Checked & Expanded in-place without losing popover mount. + app.Settle() + app.Hover("id:agent-turn-prompt-0") + app.Settle() + if app.Find("id:agent-rewind-trigger-0").Props.Expanded { + t.Fatal("expected rewind trigger Expanded=false before opening popover") + } + app.Press("id:agent-rewind-trigger-0") + app.Settle() + if !app.Find("id:agent-rewind-trigger-0").Props.Expanded { + t.Fatal("expected rewind trigger Expanded=true while popover is open") + } + if !app.Find("id:agent-rewind-opt-both").Props.Checked { + t.Fatal("expected Files and conversation radio option Checked=true initially") + } + app.Press("id:agent-rewind-opt-files") + app.Settle() + if !app.Find("id:agent-rewind-opt-files").Props.Checked || app.Find("id:agent-rewind-opt-both").Props.Checked { + t.Fatal("expected Files only radio option Checked=true after press") + } + app.Press("id:agent-rewind-cancel") + app.Settle() + if app.Exists("id:agent-rewind-popover") { + t.Fatal("expected popover to close on Cancel") + } +} + +func TestAgentRewindWithSceneGroupedThreads(t *testing.T) { + _, ed, _, coinFile, _ := setupRewindProject(t) + defer ed.Close() + + // Seed an active #1019 persisted thread for level_01 with an earlier kept request and session ID. + if _, err := ed.SendAgentRequestWith(editor.AgentSendRequest{ + Title: "Earlier kept request", + Prompt: "Seed level_01 thread", + SessionID: "sess-persisted-0", + Outcome: editor.AgentThreadOutcomeKept, + ChangesTotal: 1, + ChangesKept: 1, + }); err != nil { + t.Fatalf("SendAgentRequestWith: %v", err) + } + activeThreadID := ed.ActiveAgentThread().ID + + var seenSessions []string + ed.AgentRunner = editor.AgentRunnerFunc(func(_ context.Context, req editor.AgentRequest, emit func(editor.AgentEvent)) error { + seenSessions = append(seenSessions, req.SessionID) + switch req.Prompt { + case "Spin coins": + emit(editor.AgentEvent{Kind: editor.AgentEventSession, SessionID: "sess-turn-1"}) + _ = os.WriteFile(coinFile, []byte("version: 1\nname: coin\nspin: true\nbob: false\n"), 0o644) + emit(editor.AgentEvent{Kind: editor.AgentEventDone, Text: "Updated coin spin."}) + case "Bob coins instead": + emit(editor.AgentEvent{Kind: editor.AgentEventSession, SessionID: "sess-turn-2"}) + emit(editor.AgentEvent{Kind: editor.AgentEventDone, Text: "Updated coin bob."}) + } + return nil + }) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1280, 820)) + + if err := ed.SubmitAgentPrompt("Spin coins"); err != nil { + t.Fatalf("SubmitAgentPrompt: %v", err) + } + waitAgentIdleWithTurns(t, app, ed, 1) + + // Simulate the persisted thread also tracking the newer session ID. + if err := ed.SetAgentThreadSessionID(activeThreadID, "sess-turn-1"); err != nil { + t.Fatalf("SetAgentThreadSessionID: %v", err) + } + + // Verify mutual exclusion between thread switcher and rewind popover inside agentThreadConversationBody. + ed.SetAgentSwitcherOpen(true) + if !ed.AgentSwitcherOpen() { + t.Fatal("expected thread switcher open") + } + turnID := ed.AgentTurns()[0].ID + if !ed.OpenAgentRewindPopover(turnID) { + t.Fatal("OpenAgentRewindPopover failed") + } + if ed.AgentSwitcherOpen() { + t.Fatal("opening rewind popover should close thread switcher") + } + ed.SetAgentSwitcherOpen(true) + if ed.AgentRewindOpenTurnID() != "" { + t.Fatal("opening thread switcher should close rewind popover") + } + ed.SetAgentSwitcherOpen(false) + app.Settle() + + // Hovering the live turn inside a persisted #1019 thread renders the rewind trigger and popover. + app.Hover("id:agent-turn-prompt-0") + app.Settle() + app.Press("id:agent-rewind-trigger-0") + app.Settle() + if !app.Exists("id:agent-rewind-popover") { + t.Fatal("expected rewind popover inside persisted thread conversation body") + } + app.Press("id:agent-rewind-confirm") + app.Settle() + + // Both AgentSessionID and the persisted thread's SessionID must rewind to sess-persisted-0. + if got := ed.AgentSessionID(); got != "sess-persisted-0" { + t.Fatalf("AgentSessionID after rewind = %q, want sess-persisted-0", got) + } + if got := ed.AgentThread(activeThreadID).SessionID; got != "sess-persisted-0" { + t.Fatalf("persisted thread SessionID after rewind = %q, want sess-persisted-0", got) + } + if gotCoin, err := os.ReadFile(coinFile); err != nil || !strings.Contains(string(gotCoin), "spin: false") { + t.Fatalf("coin.prefab.yaml after rewind = %q err=%v, want spin: false", gotCoin, err) + } + + // Redo restores both AgentSessionID and persisted thread SessionID, then rewind again and submit a new prompt. + if err := ed.RedoAgentRewind(); err != nil { + t.Fatalf("RedoAgentRewind: %v", err) + } + if got := ed.AgentThread(activeThreadID).SessionID; got != "sess-turn-1" { + t.Fatalf("persisted thread SessionID after redo = %q, want sess-turn-1", got) + } + if err := ed.RewindAgentTurn(turnID, editor.AgentRewindBoth); err != nil { + t.Fatalf("second RewindAgentTurn: %v", err) + } + if err := ed.SubmitAgentPrompt("Bob coins instead"); err != nil { + t.Fatalf("SubmitAgentPrompt after rewind: %v", err) + } + waitAgentIdleWithTurns(t, app, ed, 1) + if len(seenSessions) != 2 || seenSessions[0] != "sess-persisted-0" || seenSessions[1] != "sess-persisted-0" { + t.Fatalf("runner saw sessions %v, want [sess-persisted-0 sess-persisted-0]", seenSessions) + } +} + +func TestAgentRewindIntegratesWithAgentComposerDraftAndPopovers(t *testing.T) { + _, ed, _, coinFile, _ := setupRewindProject(t) + defer ed.Close() + + ed.AgentRunner = editor.AgentRunnerFunc(func(_ context.Context, req editor.AgentRequest, emit func(editor.AgentEvent)) error { + _ = os.WriteFile(coinFile, []byte("version: 1\nname: coin\nspin: true\nbob: false\n"), 0o644) + emit(editor.AgentEvent{Kind: editor.AgentEventSession, SessionID: "sess-1"}) + emit(editor.AgentEvent{Kind: editor.AgentEventDone, Text: "Updated coin."}) + return nil + }) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1280, 820)) + + if err := ed.SubmitAgentPrompt("Make coins spin"); err != nil { + t.Fatalf("SubmitAgentPrompt: %v", err) + } + waitAgentIdleWithTurns(t, app, ed, 1) + + // Stage a composer draft with an open @-mention trigger before opening Rewind. + ed.SetComposerDraft("check @coin") + if !ed.MentionPickerOpen() { + t.Fatal("expected mention picker open for @coin draft") + } + turnID := ed.AgentTurns()[0].ID + if !ed.OpenAgentRewindPopover(turnID) { + t.Fatal("OpenAgentRewindPopover failed") + } + if ed.MentionPickerOpen() { + t.Fatal("opening rewind popover should close mention picker") + } + app.Settle() + + if err := ed.ConfirmAgentRewind(); err != nil { + t.Fatalf("ConfirmAgentRewind: %v", err) + } + app.Settle() + + if got := ed.ComposerDraft(); got != "Make coins spin" { + t.Fatalf("ComposerDraft after rewind = %q, want %q", got, "Make coins spin") + } + if got := ed.AgentComposerText(); got != "Make coins spin" { + t.Fatalf("AgentComposerText after rewind = %q, want %q", got, "Make coins spin") + } + if !ed.AgentComposerRewound() { + t.Fatal("expected AgentComposerRewound true after rewind") + } + if !app.Exists("id:agent-rewind-banner") || !app.Exists("id:agent-composer-card") { + t.Fatal("expected rewind banner and composer card rendered") + } + + // Typing into the composer clears the rewound highlight. + ed.SetComposerDraft("Make coins spin slowly") + if ed.AgentComposerRewound() { + t.Fatal("expected SetComposerDraft to clear AgentComposerRewound") + } + + // Redo restores the prior composer draft ("check @coin") and clears banner/highlight. + if err := ed.RedoAgentRewind(); err != nil { + t.Fatalf("RedoAgentRewind: %v", err) + } + if got := ed.ComposerDraft(); got != "check @coin" { + t.Fatalf("ComposerDraft after redo = %q, want %q", got, "check @coin") + } + if ed.AgentComposerRewound() { + t.Fatal("expected AgentComposerRewound false after redo") + } + + // Rewind again, then StartFreshAgentThread must clear stale rewind/redo state. + if err := ed.RewindAgentTurn(turnID, editor.AgentRewindBoth); err != nil { + t.Fatalf("second RewindAgentTurn: %v", err) + } + if !ed.CanRedoAgentRewind() { + t.Fatal("expected CanRedoAgentRewind true before StartFreshAgentThread") + } + if _, err := ed.StartFreshAgentThread(); err != nil { + t.Fatalf("StartFreshAgentThread: %v", err) + } + if ed.CanRedoAgentRewind() || ed.AgentComposerRewound() || ed.AgentRewindOpenTurnID() != "" { + t.Fatal("expected StartFreshAgentThread to clear rewind redo, highlight, and open popover state") + } +} + +func TestAgentRewindClearsPendingReviewAndStoppedState(t *testing.T) { + _, ed, _, _, _ := setupRewindProject(t) + + // Run a live request that edits the scene and then gets stopped, leaving PendingReview + liveStopped. + ed.StartAgentRequest("Move the knight right") + s1 := ed.BeginAgentToolStep("scene_edit", "Move knight", "", []string{"knight"}) + if err := ed.MoveObject("knight", 250, 120); err != nil { + t.Fatalf("MoveObject: %v", err) + } + ed.FinishAgentToolStep(s1, "Move knight", "", []string{"knight"}, false) + if !ed.StopAgent() { + t.Fatal("expected StopAgent to return true") + } + if !ed.AgentStopped() { + t.Fatal("expected AgentStopped true after StopAgent") + } + if !ed.HasPendingAgentTurnReview() { + t.Fatal("expected HasPendingAgentTurnReview true after stopped turn with edits") + } + + turns := ed.AgentTurns() + if len(turns) != 1 { + t.Fatalf("len(turns) = %d, want 1", len(turns)) + } + turnID := turns[0].ID + + // Verify Esc in AgentPanelView closes AgentRewindPopover cleanly. + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1280, 820)) + app.Settle() + + if !ed.OpenAgentRewindPopover(turnID) { + t.Fatal("OpenAgentRewindPopover failed") + } + app.Settle() + app.Key("escape") + app.Settle() + if ed.AgentRewindOpenTurnID() != "" { + t.Fatalf("expected Esc to close AgentRewindPopover, still open for %q", ed.AgentRewindOpenTurnID()) + } + + // Files-only rewind should mark the turn's PendingReview reverted so autosave is not stuck paused. + if err := ed.RewindAgentTurn(turnID, editor.AgentRewindFilesOnly); err != nil { + t.Fatalf("RewindAgentTurn(FilesOnly): %v", err) + } + if ed.HasPendingAgentTurnReview() { + t.Fatal("expected HasPendingAgentTurnReview false after FilesOnly rewind") + } + if err := ed.RedoAgentRewind(); err != nil { + t.Fatalf("RedoAgentRewind(FilesOnly): %v", err) + } + if !ed.HasPendingAgentTurnReview() { + t.Fatal("expected HasPendingAgentTurnReview restored after RedoAgentRewind(FilesOnly)") + } + + // Both rewind drops the stopped turn and clears both PendingReview and AgentStopped. + if err := ed.RewindAgentTurn(turnID, editor.AgentRewindBoth); err != nil { + t.Fatalf("RewindAgentTurn(Both): %v", err) + } + if ed.HasPendingAgentTurnReview() { + t.Fatal("expected HasPendingAgentTurnReview false after Both rewind") + } + if ed.AgentStopped() { + t.Fatal("expected AgentStopped false after Both rewind drops the stopped turn") + } + if err := ed.RedoAgentRewind(); err != nil { + t.Fatalf("RedoAgentRewind(Both): %v", err) + } + if !ed.HasPendingAgentTurnReview() || !ed.AgentStopped() { + t.Fatalf("expected PendingReview=%v and AgentStopped=%v restored after RedoAgentRewind(Both)", + ed.HasPendingAgentTurnReview(), ed.AgentStopped()) + } +} diff --git a/packages/game/editor/agent_states.go b/packages/game/editor/agent_states.go index e66727c5..527bd9d5 100644 --- a/packages/game/editor/agent_states.go +++ b/packages/game/editor/agent_states.go @@ -2019,6 +2019,7 @@ func (e *Editor) queueAgentTaskRequest(task AgentTaskKind, prompt string, offlin if fromComposer || text == strings.TrimSpace(e.composerDraft) || text == strings.TrimSpace(e.agent.composerText) { e.composerDraft = "" e.agent.composerText = "" + e.agent.composerHighlighted = false e.agentComposer.pickerOpen = false e.agentComposer.pickerOpenedByAt = false e.agentComposer.pickerQuery = "" diff --git a/packages/game/editor/agent_threads.go b/packages/game/editor/agent_threads.go index 079bf808..40ec16b9 100644 --- a/packages/game/editor/agent_threads.go +++ b/packages/game/editor/agent_threads.go @@ -639,6 +639,7 @@ func (e *Editor) loadAgentThreadsForProject() { e.agentThreads.switcherQuery = "" e.agentThreads.expandedRequestID = "" e.agentThreads.selectedHistoryStep = AgentHistorySelection{} + e.agent.rewindOpenTurnID = "" e.agentThreads.rev++ root, ok := e.agentThreadsRoot() @@ -697,6 +698,7 @@ func (e *Editor) resetAgentThreadsForDemo() { e.agentThreads.switcherQuery = "" e.agentThreads.expandedRequestID = "" e.agentThreads.selectedHistoryStep = AgentHistorySelection{} + e.agent.rewindOpenTurnID = "" e.agentThreads.rev++ e.syncAgentThreadForOpenScene() } @@ -721,6 +723,7 @@ func (e *Editor) syncAgentThreadForOpenScene() { scenePath := e.currentThreadScenePath() e.agentThreads.switcherOpen = false e.agentThreads.expandedRequestID = "" + e.agent.rewindOpenTurnID = "" // Keep the currently active persisted thread only if it already belongs to this scene. if cur := e.findPersistedAgentThread(e.agentThreads.activeThreadID); cur != nil && cur.ScenePath == scenePath { @@ -942,6 +945,7 @@ func (e *Editor) newAgentThreadForScene(scenePath string) *AgentThread { e.agentThreads.switcherOpen = false e.agentThreads.switcherQuery = "" e.agentThreads.expandedRequestID = "" + e.agent.rewindOpenTurnID = "" e.agentThreads.rev++ e.notify() return draft.Clone() @@ -959,6 +963,7 @@ func (e *Editor) SelectAgentThread(id string) error { e.agentThreads.activeThreadID = id e.agentThreads.switcherOpen = false e.agentThreads.expandedRequestID = "" + e.agent.rewindOpenTurnID = "" e.agentThreads.rev++ e.notify() return nil @@ -974,6 +979,7 @@ func (e *Editor) SelectAgentThread(id string) error { e.agentThreads.draftThread = nil e.agentThreads.switcherOpen = false e.agentThreads.expandedRequestID = "" + e.agent.rewindOpenTurnID = "" e.agentThreads.rev++ e.notify() return nil @@ -990,7 +996,9 @@ func (e *Editor) SetAgentSwitcherOpen(open bool) { return } e.agentThreads.switcherOpen = open - if !open { + if open { + e.agent.rewindOpenTurnID = "" + } else { e.agentThreads.switcherQuery = "" } e.agentThreads.rev++ @@ -1610,6 +1618,7 @@ func (e *Editor) OpenHistoryStep(threadID, requestID, stepID string) error { e.agentThreads.selectedHistoryStep = sel e.agent.rightTab = RightTabHistory e.agentThreads.switcherOpen = false + e.agent.rewindOpenTurnID = "" e.agentThreads.rev++ e.Status = e.T("threads.history.openedStatus") e.notify() diff --git a/packages/game/editor/agent_threads_ui.go b/packages/game/editor/agent_threads_ui.go index 5df2b6d9..85bd7d58 100644 --- a/packages/game/editor/agent_threads_ui.go +++ b/packages/game/editor/agent_threads_ui.go @@ -504,6 +504,7 @@ func agentThreadConversationBody( pendingAsk *AgentPermissionPrompt, openReq *AgentOpenRequest, openReqRef, cardRef, allowOnceRef, allowAlwaysRef, denyRef *core.Ref, + hoveredTurnID, focusedTurnID *core.Signal[string], ) core.Node { expandedID := ed.ExpandedAgentRequestID() var nodes []core.Node @@ -931,7 +932,7 @@ func agentThreadConversationBody( Children: latestNodes, }) for ti, turn := range turns { - nodes = append(nodes, agentTurnView(ed, rev, ti, turn, p, osKind)) + nodes = append(nodes, agentTurnView(ed, rev, ti, turn, p, osKind, hoveredTurnID, focusedTurnID)) } if ed.HasAgentPanelCard() { nodes = append(nodes, agentReviewPanelCards(ed, p, turns)...) diff --git a/packages/game/editor/agent_ui.go b/packages/game/editor/agent_ui.go index 56182e38..504c969f 100644 --- a/packages/game/editor/agent_ui.go +++ b/packages/game/editor/agent_ui.go @@ -997,6 +997,8 @@ func AgentStatusChipView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) c // working "Add to this request" + Stop footer. func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { addDraft := core.NewSignal(cx, "") + hoveredTurnID := core.NewSignal(cx, "") + focusedTurnID := core.NewSignal(cx, "") openReqRef := new(core.Ref) panelRef := new(core.Ref) switcherBtnRef := new(core.Ref) @@ -1093,6 +1095,10 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N ed.SetAgentSwitcherOpen(false) return } + if ed.AgentRewindOpenTurnID() != "" { + ed.CloseAgentRewindPopover() + return + } if ed.CommandPaletteOpen() || ed.ConnectDialogOpen() || ed.SettingsOpen() || ed.AskInPlaceOpen() || ed.PermissionsDraftOpen() || ed.HistoryPreviewActive() || ed.MentionPickerOpen() || ed.ContextBreakdownOpen() { return } @@ -1162,7 +1168,7 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N if t.PendingReview != nil { kept, revd, notChk = t.PendingReview.Kept, t.PendingReview.Reverted, len(t.PendingReview.NotChecked) } - fmt.Fprintf(&b, "%s:%s:%d:%d:%d:%v:%v:%v:%s:%s:%v:%v:%d:%d:%d:%d", t.ID, t.Status, len(t.Steps), len(t.Images), len(t.FollowUps), t.Done, t.Stopped, t.SkipPlan, t.ReviewState, t.CheckpointID, kept, revd, notChk, len(t.Summary), len(t.Reply), len(t.Error)) + fmt.Fprintf(&b, "%s:%s:%d:%d:%d:%d:%v:%v:%v:%s:%s:%v:%v:%d:%d:%d:%d", t.ID, t.Status, len(t.Steps), len(t.Images), len(t.FollowUps), len(t.ChangedFiles), t.Done, t.Stopped, t.SkipPlan, t.ReviewState, t.CheckpointID, kept, revd, notChk, len(t.Summary), len(t.Reply), len(t.Error)) if t.Partial != nil { fmt.Fprintf(&b, ":P(%v,%v,%v,%v)", t.Partial.Pointing, t.Partial.Kept, t.Partial.TryingAnother, t.Partial.HasPoint) } @@ -1215,6 +1221,10 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N }) osKind := cx.Env().OS() + bannerThemeKey := core.NewMemo(cx, func() string { + _ = rev.Get() + return fmt.Sprintf("%v|%s", ed.SpecPalette(cx).Dark, ed.ResolvedLanguage()) + }) tabBar := core.Dynamic(func(cx *core.Scope) core.Node { p := SpecPaletteFor(darkMemo.Get()) return rightRailTabBar(cx, ed, rev, p, true) @@ -1245,7 +1255,7 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N waitingCard := agentCodeReviewWaitingCard(ed, p) if active != nil && len(active.Requests) > 0 { - return agentThreadConversationBody(cx, ed, rev, p, osKind, active, turns, pendingAsk, openReq, openReqRef, cardRef, allowOnceRef, allowAlwaysRef, denyRef) + return agentThreadConversationBody(cx, ed, rev, p, osKind, active, turns, pendingAsk, openReq, openReqRef, cardRef, allowOnceRef, allowAlwaysRef, denyRef, hoveredTurnID, focusedTurnID) } ready := ed.ReadyToReviewTurns() if summary != "" || len(turns) > 0 || len(composerTurns) > 0 || pendingAsk != nil || openReq != nil || len(ready) > 0 || hasReviewCard || dtPending || len(queued) > 0 || limitReached || hasPendingTurn || len(offlineNodes) > 0 || activeRev != nil || waitingCard != nil { @@ -1263,7 +1273,7 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N items = append(items, agentComposerSummaryCard(ed, p, summary)) } for ti, turn := range turns { - items = append(items, agentTurnView(ed, rev, ti, turn, p, osKind)) + items = append(items, agentTurnView(ed, rev, ti, turn, p, osKind, hoveredTurnID, focusedTurnID)) } if len(composerTurns) > 0 { items = append(items, agentComposerThreadNodes(ed, p, composerTurns)...) @@ -1369,6 +1379,11 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N }, }, }, + core.Dynamic(func(cx *core.Scope) core.Node { + _ = bannerThemeKey.Get() + p := SpecPaletteFor(darkMemo.Get()) + return agentRewindBannerView(ed, rev, p) + }), footer, }, } @@ -1479,7 +1494,7 @@ func agentEmptyStateCard(ed *Editor, p SpecPalette) core.Node { } } -func agentTurnView(ed *Editor, rev *core.Signal[uint64], turnIdx int, turn AgentTurn, p SpecPalette, osKind core.OS) core.Node { +func agentTurnView(ed *Editor, rev *core.Signal[uint64], turnIdx int, turn AgentTurn, p SpecPalette, osKind core.OS, hoveredTurnID, focusedTurnID *core.Signal[string]) core.Node { var children []core.Node if turn.Automation { stateLabel, stateFg, stateBg, stateEdge := automationReviewBadgeStyle(ed, turn.ReviewState, p) @@ -1558,6 +1573,7 @@ func agentTurnView(ed *Editor, rev *core.Signal[uint64], turnIdx int, turn Agent }, }) } else if turn.Prompt != "" || len(turn.Images) > 0 { + turnID := turn.ID var bubbleChildren []core.Node if imgRow := agentTurnImagesRowView(turnIdx, turn.Images, p); imgRow != nil { bubbleChildren = append(bubbleChildren, imgRow) @@ -1567,7 +1583,7 @@ func agentTurnView(ed *Editor, rev *core.Signal[uint64], turnIdx int, turn Agent Content: turn.Prompt, Style: core.Style{ FontSize: 12.5, - Color: p.TextSecondary, + Color: p.TextPrimary, }, }) } @@ -1583,18 +1599,107 @@ func agentTurnView(ed *Editor, rev *core.Signal[uint64], turnIdx int, turn Agent }) } children = append(children, core.View{ - TestID: fmt.Sprintf("agent-turn-prompt-%d", turnIdx), + TestID: fmt.Sprintf("agent-turn-user-%d", turnIdx), Style: core.Style{ - AlignSelf: core.AlignEnd, - MaxWidth: core.Pt(296), - Padding: core.Symmetric(8, 12), - Gap: 8, - CornerRadius: 12, - Background: p.Raised, - BorderWidth: 1, - BorderColor: p.LineRaised, + AlignItems: core.AlignEnd, + Gap: 4, + }, + OnMouseEnter: func(core.MouseEvent) { + hoveredTurnID.Set(turnID) + }, + OnMouseLeave: func(core.MouseEvent) { + if hoveredTurnID.Get() == turnID { + hoveredTurnID.Set("") + } + }, + OnFocusIn: func() { + focusedTurnID.Set(turnID) + }, + OnFocusOut: func() { + if focusedTurnID.Get() == turnID { + focusedTurnID.Set("") + } + }, + Children: []core.Node{ + core.View{ + TestID: fmt.Sprintf("agent-turn-prompt-%d", turnIdx), + Focusable: func() bool { + _ = rev.Get() + return !ed.AgentWorking() + }, + Style: core.Style{ + MaxWidth: core.Pt(312), + Padding: core.Symmetric(8, 12), + CornerRadius: 12, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + Gap: 8, + FocusVisible: p.FocusRing(2), + }, + Children: bubbleChildren, + }, + core.Show{ + When: func() bool { + _ = rev.Get() + if ed.AgentWorking() { + return false + } + return hoveredTurnID.Get() == turnID || focusedTurnID.Get() == turnID || ed.AgentRewindOpenTurnID() == turnID + }, + Then: func(cx *core.Scope) core.Node { + return core.View{ + TestID: fmt.Sprintf("agent-rewind-trigger-%d", turnIdx), + Role: core.RoleButton, + Label: ed.T("agent.rewind.trigger"), + Expanded: func() bool { + _ = rev.Get() + return ed.AgentRewindOpenTurnID() == turnID + }, + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Height: core.Pt(24), + Gap: 6, + Padding: core.Symmetric(0, 8), + CornerRadius: 6, + Hover: &core.Style{Background: p.Raised}, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.ToggleAgentRewindPopover(turnID) + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.Undo2(), + Style: core.Style{ + Width: core.Pt(13), + Height: core.Pt(13), + Color: p.TextMuted, + FlexShrink: 0, + }, + }, + core.Text{ + Content: ed.T("agent.rewind.trigger"), + Style: core.Style{ + FontSize: 12, + Color: p.TextMuted, + }, + }, + }, + } + }, + }, + }, + }) + children = append(children, core.Show{ + When: func() bool { + _ = rev.Get() + return ed.AgentRewindOpenTurnID() == turnID + }, + Then: func(cx *core.Scope) core.Node { + return agentRewindPopoverView(ed, rev, turnID, p) }, - Children: bubbleChildren, }) } @@ -1789,7 +1894,7 @@ func agentTurnView(ed *Editor, rev *core.Signal[uint64], turnIdx int, turn Agent return core.View{ TestID: fmt.Sprintf("agent-turn-%d", turnIdx), Style: core.Style{ - Gap: 10, + Gap: 8, }, Children: children, } @@ -2386,6 +2491,312 @@ func agentOpenRequestCard(ed *Editor, req *AgentOpenRequest, ref *core.Ref, p Sp } } +func agentRewindPopoverView(ed *Editor, rev *core.Signal[uint64], turnID string, p SpecPalette) core.Node { + preview, ok := ed.AgentRewindPreview(turnID) + if !ok { + return core.View{} + } + shadowAlpha := float32(0.5) + if !p.Dark { + shadowAlpha = 0.16 + } + optionRow := func(testID string, mode AgentRewindMode, label, detail string) core.Node { + return core.View{ + TestID: testID, + Role: core.RoleRadio, + Label: label, + Checked: func() bool { + _ = rev.Get() + return ed.AgentRewindMode() == mode + }, + Focusable: func() bool { return true }, + StyleFunc: func() core.Style { + _ = rev.Get() + selected := ed.AgentRewindMode() == mode + st := core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 10, + Padding: core.Symmetric(6, 8), + CornerRadius: 8, + BorderWidth: 1.5, + BorderColor: core.Transparent, + FocusVisible: p.FocusRing(2), + } + if selected { + st.Background = p.Accent.Fill + st.BorderColor = p.Accent.Edge + } else { + st.Hover = &core.Style{Background: p.Inset} + } + return st + }, + OnPress: func(core.PressEvent) { + ed.SetAgentRewindMode(mode) + }, + Children: []core.Node{ + core.View{ + StyleFunc: func() core.Style { + _ = rev.Get() + if ed.AgentRewindMode() == mode { + return core.Style{ + Width: core.Pt(14), + Height: core.Pt(14), + CornerRadius: 7, + BorderWidth: 4, + BorderColor: p.Accent.Fg, + Background: p.Raised, + FlexShrink: 0, + } + } + return core.Style{ + Width: core.Pt(14), + Height: core.Pt(14), + CornerRadius: 7, + BorderWidth: 1.5, + BorderColor: p.TextFaint, + FlexShrink: 0, + } + }, + }, + core.View{ + Style: core.Style{ + FlexGrow: 1, + FlexShrink: 1, + MinWidth: core.Pt(0), + Gap: 2, + }, + Children: []core.Node{ + core.Text{ + Content: label, + Style: core.Style{ + FontSize: 12.5, + Color: p.TextPrimary, + }, + }, + core.Text{ + TestID: testID + "-detail", + Content: detail, + Style: core.Style{ + FontSize: 11.5, + Color: p.TextFaint, + }, + }, + }, + }, + }, + } + } + + return core.View{ + TestID: "agent-rewind-popover", + Role: core.RoleDialog, + Label: ed.T("agent.rewind.title"), + Style: core.Style{ + AlignSelf: core.AlignEnd, + Width: core.Pt(320), + MaxWidth: core.Pct(100), + CornerRadius: 12, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + Padding: core.All(10), + Gap: 8, + Shadows: []core.BoxShadow{ + ui.Shadow(0, 16, 40, 0, ui.Black(shadowAlpha)), + }, + }, + Children: []core.Node{ + core.Text{ + TestID: "agent-rewind-title", + Content: ed.T("agent.rewind.title"), + Style: core.Style{ + FontSize: 12.5, + FontWeight: 600, + Color: p.TextPrimary, + }, + }, + core.View{ + TestID: "agent-rewind-options", + Role: core.RoleRadioGroup, + Label: ed.T("agent.rewind.title"), + Style: core.Style{Gap: 4}, + Children: []core.Node{ + optionRow("agent-rewind-opt-both", AgentRewindBoth, ed.T("agent.rewind.both"), ed.formatRewindBothDetail(preview)), + optionRow("agent-rewind-opt-files", AgentRewindFilesOnly, ed.T("agent.rewind.filesOnly"), ed.T("agent.rewind.filesOnlyDetail")), + optionRow("agent-rewind-opt-conv", AgentRewindConversationOnly, ed.T("agent.rewind.convOnly"), ed.T("agent.rewind.convOnlyDetail")), + }, + }, + core.View{ + Style: core.Style{ + Direction: core.Row, + Gap: 8, + JustifyContent: core.JustifyEnd, + }, + Children: []core.Node{ + core.View{ + TestID: "agent-rewind-cancel", + Role: core.RoleButton, + Label: ed.T("agent.rewind.cancel"), + Style: core.Style{ + Height: core.Pt(30), + Padding: core.Symmetric(0, 12), + CornerRadius: 8, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Background: p.LineRaised, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.CloseAgentRewindPopover() + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("agent.rewind.cancel"), + Style: core.Style{ + FontSize: 12.5, + Color: p.TextPrimary, + }, + }, + }, + }, + core.View{ + TestID: "agent-rewind-confirm", + Role: core.RoleButton, + Label: ed.T("agent.rewind.action"), + Style: core.Style{ + Height: core.Pt(30), + Padding: core.Symmetric(0, 12), + CornerRadius: 8, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Background: p.Accent.Fg, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.report(ed.ConfirmAgentRewind()) + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("agent.rewind.action"), + Style: core.Style{ + FontSize: 12.5, + FontWeight: 600, + Color: p.Accent.OnFill, + }, + }, + }, + }, + }, + }, + }, + } +} + +func agentRewindBannerView(ed *Editor, rev *core.Signal[uint64], p SpecPalette) core.Node { + shadowAlpha := float32(0.45) + if !p.Dark { + shadowAlpha = 0.14 + } + return core.Show{ + When: func() bool { + _ = rev.Get() + _, ok := ed.AgentRewindBanner() + return ok + }, + Then: func(cx *core.Scope) core.Node { + return core.View{ + Style: core.Style{ + Padding: core.Edges{Left: 12, Right: 12, Top: 8}, + Background: p.Panel, + FlexShrink: 0, + }, + Children: []core.Node{ + core.View{ + TestID: "agent-rewind-banner", + Role: core.RoleStatus, + LiveRegion: core.LiveRegionPolite, + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + Padding: core.Edges{Top: 6, Right: 6, Bottom: 6, Left: 12}, + CornerRadius: 12, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + Shadows: []core.BoxShadow{ + ui.Shadow(0, 12, 32, 0, ui.Black(shadowAlpha)), + }, + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.Undo2(), + Style: core.Style{ + Width: core.Pt(15), + Height: core.Pt(15), + Color: p.TextMuted, + FlexShrink: 0, + }, + }, + core.Text{ + TestID: "agent-rewind-banner-text", + ContentFunc: func() string { + _ = rev.Get() + st, ok := ed.AgentRewindBanner() + if !ok { + return "" + } + return ed.formatRewindBannerText(st) + }, + Style: core.Style{ + FlexGrow: 1, + FlexShrink: 1, + MinWidth: core.Pt(0), + FontSize: 12, + Color: p.TextPrimary, + }, + }, + core.View{ + TestID: "agent-rewind-redo", + Role: core.RoleButton, + Label: ed.T("agent.rewind.redo"), + Disabled: func() bool { + _ = rev.Get() + return !ed.CanRedoAgentRewind() + }, + Style: core.Style{ + Height: core.Pt(30), + Padding: core.Symmetric(0, 12), + CornerRadius: 8, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Background: p.LineRaised, + FlexShrink: 0, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.report(ed.RedoAgentRewind()) + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("agent.rewind.redo"), + Style: core.Style{ + FontSize: 12.5, + FontWeight: 500, + Color: p.TextPrimary, + }, + }, + }, + }, + }, + }, + }, + } + }, + } +} + // ConnectAgentDialogView renders the "Connect an agent" modal dialog matching docs/design/editor/Connect.dc.html // using exclusively Spec.dc.html tokens: three choices, the one-time `go tool game mcp install` command with Copy, // a live waiting state that turns to connected when the first MCP client attaches, four starting permission checkboxes, diff --git a/packages/game/editor/editorcmd/agent_rewind_screenshot_test.go b/packages/game/editor/editorcmd/agent_rewind_screenshot_test.go new file mode 100644 index 00000000..c86a75c8 --- /dev/null +++ b/packages/game/editor/editorcmd/agent_rewind_screenshot_test.go @@ -0,0 +1,153 @@ +package editorcmd_test + +import ( + "context" + "os" + "path/filepath" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/project" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +// TestAgentRewindMacOSScreenshots renders the Agent panel's Rewind popover ("Rewind to before this message") +// and post-rewind state (banner with Redo + rewound prompt returned to composer) on native macOS +// in both Dark and Light Spec themes for visual inspection beside docs/design/editor/Checkpoints.dc.html. +func TestAgentRewindMacOSScreenshots(t *testing.T) { + dir := t.TempDir() + proj := &project.File{ + Version: project.CurrentVersion, + Name: "dungeon-run", + ID: "dev.nsgo.dungeon-run", + AppVersion: "0.1.0", + Window: project.Window{Width: 1280, Height: 720}, + } + projData, err := project.Encode(proj) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "game.yaml"), projData, 0o644); err != nil { + t.Fatal(err) + } + + doc, err := sceneformat.Parse([]byte(macosThemePreviewScene)) + if err != nil { + t.Fatal(err) + } + sceneBytes, err := sceneformat.Encode(doc) + if err != nil { + t.Fatal(err) + } + sceneFile := filepath.Join(dir, "scenes", "level_01.scene.yaml") + if err := os.MkdirAll(filepath.Dir(sceneFile), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(sceneFile, sceneBytes, 0o644); err != nil { + t.Fatal(err) + } + coinFile := filepath.Join(dir, "prefabs", "coin.prefab.yaml") + if err := os.MkdirAll(filepath.Dir(coinFile), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(coinFile, []byte("version: 1\nname: coin\nspin: false\nbob: false\n"), 0o644); err != nil { + t.Fatal(err) + } + sparkleFile := filepath.Join(dir, "fx", "sparkle.particles.yaml") + + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + defer ed.Close() + if err := ed.OpenProjectScene(dir, sceneFile); err != nil { + t.Fatal(err) + } + ed.SetRightRailTab(editor.RightTabAgent) + ed.NotifyAgentMCPConnected(editor.AgentClientInfo{ + ID: "c1", + Name: "claude-code", + Transport: "stdio", + }) + + prompt1 := "Put three slimes patrolling the lower floor and a short coin trail toward the door." + prompt2 := "Make the coins spin and bob, and give each one a sparkle." + + ed.AgentRunner = editor.AgentRunnerFunc(func(_ context.Context, req editor.AgentRequest, emit func(editor.AgentEvent)) error { + switch req.Prompt { + case prompt1: + emit(editor.AgentEvent{Kind: editor.AgentEventSession, SessionID: "s1"}) + emit(editor.AgentEvent{Kind: editor.AgentEventMessage, Text: "Done: 3 slimes and 3 coins, kept."}) + emit(editor.AgentEvent{Kind: editor.AgentEventDone}) + case prompt2: + emit(editor.AgentEvent{Kind: editor.AgentEventSession, SessionID: "s2"}) + _ = os.WriteFile(coinFile, []byte("version: 1\nname: coin\nspin: true\nbob: true\n"), 0o644) + _ = os.MkdirAll(filepath.Dir(sparkleFile), 0o755) + _ = os.WriteFile(sparkleFile, []byte("version: 1\nname: sparkle\nrate: 24\n"), 0o644) + emit(editor.AgentEvent{Kind: editor.AgentEventStep, StepID: "1", StepTitle: "Added spin and bob to prefabs/coin.prefab.yaml", StepStatus: editor.AgentStepDone}) + emit(editor.AgentEvent{Kind: editor.AgentEventStep, StepID: "2", StepTitle: "Wrote fx/sparkle.particles.yaml", StepStatus: editor.AgentStepDone}) + emit(editor.AgentEvent{Kind: editor.AgentEventMessage, Text: "Kept · 2 files. The sparkle is louder than you probably want."}) + emit(editor.AgentEvent{Kind: editor.AgentEventDone}) + } + return nil + }) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), nsgotest.Environment(core.Environment{ + OS: core.OSMacOS, + Idiom: core.IdiomDesktop, + Dark: true, + Locale: "en-US", + })) + app.Settle() + + if err := ed.SubmitAgentPrompt(prompt1); err != nil { + t.Fatal(err) + } + app.WaitUntil(5*time.Second, func() bool { + return !ed.AgentWorking() && len(ed.AgentTurns()) == 1 + }) + app.Settle() + if err := ed.SubmitAgentPrompt(prompt2); err != nil { + t.Fatal(err) + } + app.WaitUntil(5*time.Second, func() bool { + return !ed.AgentWorking() && len(ed.AgentTurns()) == 2 + }) + app.Settle() + + // 1. Dark: hover message 2 + open Rewind popover. + app.Hover("id:agent-turn-prompt-1") + app.Settle() + app.Press("id:agent-rewind-trigger-1") + app.Settle() + app.Screenshot("agent-rewind-popover-dark") + + // 2. Dark: after Rewind (Files and conversation) -> banner with Redo + composer holds prompt 2. + app.Press("id:agent-rewind-confirm") + app.Settle() + app.Screenshot("agent-rewind-after-dark") + + // 3. Light: Redo, switch appearance to Light via live environment, open Rewind popover & confirm. + app.Press("id:agent-rewind-redo") + app.Settle() + app.SetEnvironment(core.Environment{ + OS: core.OSMacOS, + Idiom: core.IdiomDesktop, + Dark: false, + Locale: "en-US", + }) + app.Hover("id:agent-turn-prompt-1") + app.Settle() + app.Press("id:agent-rewind-trigger-1") + app.Settle() + app.Screenshot("agent-rewind-popover-light") + + app.Press("id:agent-rewind-confirm") + app.Settle() + app.Screenshot("agent-rewind-after-light") +} diff --git a/packages/game/editor/inspector_sections.go b/packages/game/editor/inspector_sections.go index b848f112..a9cb7229 100644 --- a/packages/game/editor/inspector_sections.go +++ b/packages/game/editor/inspector_sections.go @@ -170,7 +170,7 @@ func (e *Editor) ComposerDraft() string { // SetComposerDraft updates the agent composer draft text, refreshes @-mention trigger detection, and notifies listeners. func (e *Editor) SetComposerDraft(text string) { - if e == nil || e.composerDraft == text { + if e == nil || (e.composerDraft == text && !e.agent.composerHighlighted) { return } e.updateComposerDraftFromInput(text) @@ -196,6 +196,8 @@ func (e *Editor) AskToAddComponent(objectID string) string { } prompt := fmt.Sprintf("Add a component to %s that ", target) e.composerDraft = prompt + e.agent.composerText = prompt + e.agent.composerHighlighted = false e.Status = prompt if e.OnComposerPrompt != nil { e.OnComposerPrompt(prompt) diff --git a/packages/game/editor/locales/en.yaml b/packages/game/editor/locales/en.yaml index 2bfdae8d..4a7d2b77 100644 --- a/packages/game/editor/locales/en.yaml +++ b/packages/game/editor/locales/en.yaml @@ -68,6 +68,28 @@ strings: agent.ref.undo: Undo agent.revert: Revert agent.review: Review + agent.rewind.action: Rewind + agent.rewind.banner: Rewound {mode} to before “{prompt}” + agent.rewind.bannerNoPrompt: Rewound {mode} + agent.rewind.both: Files and conversation + agent.rewind.bothDetailManyFilesManyReplies: Undo {files} files, drop {replies} replies + agent.rewind.bothDetailManyFilesOneReply: Undo {files} files, drop the reply + agent.rewind.bothDetailNoFilesManyReplies: Drop {replies} replies + agent.rewind.bothDetailNoFilesOneReply: Drop the reply + agent.rewind.bothDetailOneFileManyReplies: Undo 1 file, drop {replies} replies + agent.rewind.bothDetailOneFileOneReply: Undo 1 file, drop the reply + agent.rewind.cancel: Cancel + agent.rewind.convOnly: Conversation only + agent.rewind.convOnlyDetail: Keep the files as they are + agent.rewind.filesOnly: Files only + agent.rewind.filesOnlyDetail: Keep the conversation as it is + agent.rewind.modeBoth: files and conversation + agent.rewind.modeConv: conversation only + agent.rewind.modeFiles: files only + agent.rewind.redidStatus: Redid rewind + agent.rewind.redo: Redo + agent.rewind.title: Rewind to before this message + agent.rewind.trigger: Rewind to here agent.status.disconnected: Disconnected agent.status.limitShort: Limit agent.status.offline: Offline diff --git a/packages/game/editor/locales/zh.yaml b/packages/game/editor/locales/zh.yaml index d329cc38..1f00cd07 100644 --- a/packages/game/editor/locales/zh.yaml +++ b/packages/game/editor/locales/zh.yaml @@ -68,6 +68,28 @@ strings: agent.ref.undo: 撤销 agent.revert: 还原 agent.review: 审查 + agent.rewind.action: 回退 + agent.rewind.banner: 已将{mode}回退到“{prompt}”之前 + agent.rewind.bannerNoPrompt: 已回退{mode} + agent.rewind.both: 文件与对话 + agent.rewind.bothDetailManyFilesManyReplies: 撤销 {files} 个文件,移除 {replies} 条回复 + agent.rewind.bothDetailManyFilesOneReply: 撤销 {files} 个文件,移除该回复 + agent.rewind.bothDetailNoFilesManyReplies: 移除 {replies} 条回复 + agent.rewind.bothDetailNoFilesOneReply: 移除该回复 + agent.rewind.bothDetailOneFileManyReplies: 撤销 1 个文件,移除 {replies} 条回复 + agent.rewind.bothDetailOneFileOneReply: 撤销 1 个文件,移除该回复 + agent.rewind.cancel: 取消 + agent.rewind.convOnly: 仅对话 + agent.rewind.convOnlyDetail: 保持文件现状不变 + agent.rewind.filesOnly: 仅文件 + agent.rewind.filesOnlyDetail: 保持对话现状不变 + agent.rewind.modeBoth: 文件与对话 + agent.rewind.modeConv: 仅对话 + agent.rewind.modeFiles: 仅文件 + agent.rewind.redidStatus: 已重做回退 + agent.rewind.redo: 重做 + agent.rewind.title: 回退到此消息之前 + agent.rewind.trigger: 回退到此处 agent.status.disconnected: 已断开 agent.status.limitShort: 已达上限 agent.status.offline: 离线 diff --git a/packages/game/editor/play.go b/packages/game/editor/play.go index a824a28b..1954ee71 100644 --- a/packages/game/editor/play.go +++ b/packages/game/editor/play.go @@ -270,6 +270,7 @@ func (e *Editor) startPlaySession(cx *core.Scope, playback *replay.Recording, st // Pause the review screen so Play runs in the viewport on the untouched old code on disk. e.CloseCodeReview() } + e.CloseAgentRewindPopover() e.endTileStrokeForChange() e.endGridMapStrokeForChange() e.endTerrainStrokeForChange()