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,52 @@
# Agent Note: Reference images in the Agent composer and atomic Pin to brief

Status: implemented

## Problem

Issue #1027 implements the *Paste or drop an image* and *Pin to brief* workflows from `docs/design/editor/Sketch.dc.html` on top of the [Agent panel and composer contract](../../implemented/architecture/2026-11-26-editor-agent-connect.md). Authors need two distinct lifetimes for reference art without hidden state:

1. **One-shot attachments**: dropping, pasting, or picking a PNG, JPEG, or WebP image attaches it to the next request only, shows a chip with a hover preview, and refuses unsupported formats with a clear reason.
2. **Project-wide pinned references**: clicking **Pin to brief** copies the image into `art/reference/<name>` and adds one entry to `brief.yaml` under `art.references` as a single undoable `Editor.History` step that shows in Review/Changes, joins every subsequent request through the `brief.yaml` Always chip, and disappears completely (both file and YAML line) on Undo.

## Decision

### Strict in-memory decoding for PNG, JPEG, and WebP

- `DecodeAgentReferenceImage` validates magic bytes (`\x89PNG\r\n\x1a\n`, `\xff\xd8\xff`, and `RIFF....WEBP`) and decodes the image in memory (`image/png`, `image/jpeg`, `golang.org/x/image/webp`) under strict size, dimension, and count caps (`16 MiB`, `4096×4096`, `16M` pixels, max `8` one-shot attachments per request and `16` pinned brief references).
- Non-matching formats (GIF, SVG, BMP, PDF, text, non-regular files, remote non-`file://` URIs, or malformed image files) are refused before creating a chip, surfacing an explicit reason in `AgentAttachError` and the composer's accessible `RoleAlert` banner.
- Decoded `*image.RGBA` pixels are attached to `AgentReferenceImage` so thumbnails, turn bubbles, and hover preview cards render consistently across all three formats—including WebP—via `core.Image{Source: core.ImageSource{Pixels: ..., Version: ...}}`. Historical `AgentTurn.Images` retain thumbnail pixels without retaining raw encoded byte buffers in RAM.

### Composer drop, paste, hover preview, and one-shot clearing

- `agent-composer` wires `core.View.OnFileDragEnter`, `OnFileDragLeave`, and `OnFileDrop` to show the Spec-styled **"Drop to attach"** overlay and call `DropAgentReferenceFiles`.
- `agent-composer-input` wires `core.Input.OnPaste` (`HandleAgentComposerPaste`), which handles pasted image bytes (`PasteEvent.Files`) and copied file URLs (`PasteEvent.URIs`) without interfering with normal plain-text pastes (`PasteInsert`). Injectable `Editor.ReadClipboardImage`, `Editor.ReadClipboardFiles`, and `Editor.PickAgentReferenceFiles` hooks keep clipboard and picker flows deterministic in tests, and async picker/clipboard callbacks verify editor lifecycle and project identity before mutating state.
- `SubmitAgentPrompt` snapshots one-shot attachments (`AgentRequest.AttachedImages`) and pinned brief references (`AgentRequest.BriefImages`) into a deduplicated `AgentRequest.Images` slice and `AgentTurn.Images`, then clears `attachedImages` immediately so the next request never carries one-shot attachments.

### Schema-compatible YAML AST pinning and atomic `fallibleCommand` Undo

- `project.Brief` (`packages/game/project/brief.go` and `apps/website/public/schemas/brief.v1.json`) declares `Art *BriefArt` (`art.direction` and `art.references: [{path, note}]`) with strict validation (clean slash-separated project-relative paths, no duplicates, no control characters) so `brief.yaml` round-trips cleanly between **Pin to brief** and **Settings › Game brief** (#1026).
- `PinAgentReferenceImage` executes a `pinReferenceImageCmd` (`fallibleCommand`) on `Editor.History`, guarded against Play mode, merge conflicts, and read-only History preview.
- `appendBriefReferenceYAML` edits existing `brief.yaml` files through `yaml.Node` to preserve existing keys, comments, and formatting while adding a single `- path: art/reference/<name>` line (plus `note:` when supplied), and creates fresh `brief.yaml` files with `project.BriefSchemaComment` and `version: 1`.
- Every read, write, and Undo/Redo step enforces component-by-component `os.Lstat` symlink containment under the project root (protecting against TOCTOU symlink swaps), avoids unbounded `os.ReadFile` calls during filename disambiguation (`resolvePinImageTarget`), synchronizes `Editor.Brief()` (`reloadBriefFromDisk`), and keeps the pin card's **Undo** button (`CanUndoLastBriefPin` / `UndoLastBriefPin`) bound strictly to the top of `Editor.History` so it never undoes unrelated subsequent edits.
- `BriefFileExists`, `BriefReferences`, and `BriefReferenceImages` cache parsed metadata and decoded pinned images by `(path, modTime, size)` (pruning stale keys) so composer keystrokes and UI redraws avoid redundant disk reads and YAML parsing while staying synchronized with disk edits and Undo/Redo.

## Alternatives considered

### Copy dropped or pasted images into a temporary project folder immediately on attach

Writing one-shot attachments to `.nsgo/tmp/` or `art/reference/` on drop would let CLI runners reference a file path immediately. This was rejected because an unpinned image is explicitly ephemeral ("sent with this request only" and never dirties the project or git working tree); keeping one-shot bytes strictly in memory until the user clicks **Pin to brief** (and materializing ephemeral files only in a private OS temp directory cleaned up on exit inside `CLIAgentRunner.Run`) ensures nothing touches the project directory unless explicitly pinned.

### Re-marshal `brief.yaml` through `project.EncodeBrief` on every Pin to brief

Always re-encoding through `project.Brief` would strip author comments and rewrite unrelated sections of `brief.yaml`, producing noisy diffs on the Pin to brief confirmation card. Supporting `Art *BriefArt` in `project.Brief` for schema/Settings interop while using `yaml.Node` AST updates in `PinAgentReferenceImage` gives both strict schema compatibility and minimal single-line diffs.

## Consequences

- **Benefits**: One-shot image attachments never leak across requests or dirty the working tree; PNG, JPEG, and WebP work identically across drop, paste, and picker; Pin to brief produces clean, reviewable, schema-valid diffs in Changes/Git, stays in sync with Settings › Game brief, and reverts atomically with one Undo; all UI surfaces use `SpecPalette` tokens in both Dark and Light appearances and full EN/ZH localization.
- **Costs**: `CLIAgentRunner` writes temporary OS files for ephemeral one-shot images during subprocess execution (cleaned up immediately on exit) and validates every project-backed reference path against root containment before passing `-i` (Codex) or prompt references (Claude / resumed Codex).

## Testing

- `packages/game/editor/agent_references_test.go`: tests dropping a PNG (drag overlay, chip, hover preview, received once by scripted `AgentRunner`, absent on next request), pasting/dropping PNG/JPEG/WebP, refusing GIF/SVG/TXT/corrupt PNG with visible reasons, Pin to brief writing `art/reference/<name>` and one YAML line in `brief.yaml`, Changes/Review visibility, next request carrying the pinned image through the Always chip, Undo removing both files/lines (both with existing and absent `brief.yaml`), Redo restoring them, and Dark/Light `SpecPalette` token switching.
- `packages/game/editor/editorcmd/agent_references_screenshot_test.go`: captures real macOS `-target macos` screenshots of attached preview, Drop to attach overlay, Pin to brief YAML diff card, and unsupported-format refusal banner.
45 changes: 45 additions & 0 deletions apps/website/public/schemas/brief.v1.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@
"description": "ArtDirection describes visual style, resolution, palette, and silhouette rules.",
"type": "string"
},
"art": {
"description": "Art holds structured visual direction notes and pinned reference images read by the agent before every request.",
"allOf": [
{
"$ref": "#/definitions/BriefArt"
}
]
},
"toneAndAudio": {
"description": "ToneAndAudio describes mood, music, and sound direction.",
"type": "string"
Expand All @@ -57,6 +65,43 @@
],
"additionalProperties": false,
"definitions": {
"BriefArt": {
"description": "BriefArt holds structured art direction notes and pinned project-relative reference images.",
"type": "object",
"properties": {
"direction": {
"description": "Direction optionally describes visual direction inline under art.direction.",
"type": "string"
},
"references": {
"description": "References lists pinned project-relative reference images included with every agent request.",
"type": "array",
"items": {
"$ref": "#/definitions/BriefArtReference"
}
}
},
"additionalProperties": false
},
"BriefArtReference": {
"description": "BriefArtReference names one pinned reference image listed under art.references in brief.yaml.",
"type": "object",
"properties": {
"path": {
"description": "Path is the project-relative slash path to the reference image (for example \"art/reference/spikes_ref.png\").",
"type": "string",
"minLength": 1
},
"note": {
"description": "Note is an optional short description of what the reference illustrates.",
"type": "string"
}
},
"required": [
"path"
],
"additionalProperties": false
},
"BriefFeel": {
"description": "BriefFeel describes game feel, difficulty expectations, and machine-readable playtest targets.",
"type": "object",
Expand Down
3 changes: 3 additions & 0 deletions changelog.d/editor-reference-images-1027.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Added

- `game/editor`: support dropping, pasting, or picking PNG, JPEG, and WebP reference images onto the Agent composer with format validation, refusal reasons, hover previews, one-shot request delivery, atomic undoable **Pin to brief** (`art/reference/<name>` + `brief.yaml` YAML diff card), and automatic inclusion of pinned references on every request via the `brief.yaml` Always chip (#1027).
10 changes: 10 additions & 0 deletions docs/en/editor.md
Original file line number Diff line number Diff line change
Expand Up @@ -1339,6 +1339,7 @@ Connect an external coding agent (Claude Code, Codex, or any MCP client on your
- `Waiting for you · m:ss` (clicking focuses the open request card)
- `Reconnecting · try n of 5` (retries after `1, 2, 4, 8, 16 s` using injectable `Editor.AgentScheduleAfter`)
- `Disconnected` with **Reconnect** and **Troubleshoot** (reopens Connect directly at the failed step rather than the start).

## Play mode marks, rolling replay, and frozen-frame agent questions (#1042)

While playing a scene in Play mode (`Play`, `PlayIn`, `StepPlay`, `PlayTick`) or connected to a running game, the editor keeps a rolling 60-second input recording, supports marking moments without stopping, lets you freeze any frame to ask the agent what looks wrong, and adds panic triage with one-click replay up to the panic frame (`docs/design/editor/PlayMode.dc.html`, styled strictly with `Spec.dc.html` tokens):
Expand Down Expand Up @@ -1532,3 +1533,12 @@ Draw session-only numbered annotations directly over the 2D viewport to point at
- **Sending a sketch to the agent (`SendSketch` / `Editor.OnSendSketch`)**: the composer attaches a `"Sketch · N marks"` context chip (clicking toggles a `"Sent with this request"` scene-coordinate preview). Sending delivers `SketchAgentRequest` with structured marks (`number`, `kind`, geometry in scene coordinates, `label`) and a rendered PNG of the viewport with numbered marks overlaid (`RenderSketchViewportPNG`).
- **Agent reading card & `scene_edit` confirmation hold**: sending a sketch arms a hold gate (`SketchHoldActive() == true`) that causes `scene_edit` and other mutating scene MCP tools to refuse edits until the person confirms. The agent reads marks via `sketch_read` and posts its restatement (`"I read your sketch as: …"` with numbered items and assumptions) via `sketch_reading` (`PostSketchReading`). Clicking **Go ahead** (`ApproveSketchReading`, `⌘↵`) releases the hold; clicking **Correct a mark** (`CorrectSketchMark`, `⇧M`, or clicking any numbered item) reopens sketch mode with that exact mark selected while keeping the hold active; replying in words (`ReplyToSketchReading`) works too.
- **Review overlay & Keep / Revert**: after approval, agent edits open a review card (`SketchReviewOpen`) with a **Sketch overlay** toggle (`O`, `ToggleSketchReviewOverlay`, also available in `TileReview`) that lays the faint dotted sketch over the result. **Keep** (`KeepSketchReview` / `KeepTileReview`) keeps the edits and clears the sketch layer; **Revert** (`RevertSketchReview` / `RevertAllTileReview`) undoes the edits while keeping the sketch marks intact to send again.

## Reference images in the agent composer and pinning to the brief (#1027)

Attach PNG, JPEG, or WebP reference images to a single agent request or pin them to the project's game brief, matching `docs/design/editor/Sketch.dc.html` (*Paste or drop an image*, *Pin to brief*) using exclusively `docs/design/editor/Spec.dc.html` tokens:

- **Drop, paste, or pick PNG, JPEG, and WebP**: dragging files over the Agent composer shows the Spec-styled **"Drop to attach"** overlay (`SetAgentComposerDragOver`, `DropAgentReferenceFiles`); pasting an image or image files into the composer (`HandleAgentComposerPaste` via `core.Input.OnPaste`, or `PasteAgentReferenceImage`) or clicking the **Attach an image** button (`PickAndAttachAgentReferenceImages` / `CmdAttachReferenceImage`) validates actual PNG, JPEG, or WebP headers and pixels in memory (`DecodeAgentReferenceImage`). Unsupported file types (such as GIF, SVG, BMP, text, or corrupted images) are refused with the exact reason in an accessible error banner (`AgentAttachError`).
- **One-shot chips with hover preview**: each attached image appears as a chip with a thumbnail, filename, **Pin to brief** button, and **×** remove button (`RemoveAgentReferenceImage`). Hovering or focusing a chip displays a floating preview card above the composer with the decoded image, format, dimensions, and scope (`Sent with this request only`). Submitting a request (`SubmitAgentPrompt`) delivers attached images in `AgentRequest.AttachedImages` and `AgentRequest.Images` (and records thumbnails on `AgentTurn.Images`), then clears the one-shot chips so the next request does not carry them.
- **Pin to brief (`PinAgentReferenceImage`)**: clicking **Pin to brief** copies the image to `art/reference/<name>` (disambiguating collisions without overwriting different files) and adds an entry under `art.references` in `brief.yaml` via YAML AST editing (preserving existing keys and comments) as **one atomic, undoable `Editor.History` step**. Both files immediately appear in Review / Changes (`RefreshChanges`), a confirmation card displays the `+` YAML diff with an **Undo** button (`UndoLastBriefPin`), and a single Undo removes both the copied file and the YAML line (or deletes a freshly created `brief.yaml` and empty `art/reference/` folder).
- **Always chip (`brief.yaml`)**: whenever `brief.yaml` exists, the composer shows the **Always** row with a locked `brief.yaml` chip (showing the pinned reference count when non-zero). Hovering or pressing the chip previews every pinned reference image, and every subsequent agent request automatically includes those images via `AgentRequest.BriefImages` and `AgentRequest.Images`.
Loading
Loading