Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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`.
3 changes: 3 additions & 0 deletions changelog.d/editor-agent-rewind-1021.md
Original file line number Diff line number Diff line change
@@ -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.
13 changes: 11 additions & 2 deletions docs/en/editor.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`):
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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 <file>:<line>"` 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 `<file>`** (`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.
Loading
Loading