diff --git a/.agents/notes/implemented/feature/2026-11-26-editor-agent-reference-images.md b/.agents/notes/implemented/feature/2026-11-26-editor-agent-reference-images.md new file mode 100644 index 000000000..c2203f595 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-26-editor-agent-reference-images.md @@ -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/` 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/` 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/` 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. diff --git a/apps/website/public/schemas/brief.v1.json b/apps/website/public/schemas/brief.v1.json index 49065b749..7bc9095f7 100644 --- a/apps/website/public/schemas/brief.v1.json +++ b/apps/website/public/schemas/brief.v1.json @@ -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" @@ -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", diff --git a/changelog.d/editor-reference-images-1027.md b/changelog.d/editor-reference-images-1027.md new file mode 100644 index 000000000..ccdc0345d --- /dev/null +++ b/changelog.d/editor-reference-images-1027.md @@ -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/` + `brief.yaml` YAML diff card), and automatic inclusion of pinned references on every request via the `brief.yaml` Always chip (#1027). diff --git a/docs/en/editor.md b/docs/en/editor.md index ce664b537..cb7ab08aa 100644 --- a/docs/en/editor.md +++ b/docs/en/editor.md @@ -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): @@ -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/` (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`. diff --git a/docs/zh/editor.md b/docs/zh/editor.md index e5ca3351a..2631792a8 100644 --- a/docs/zh/editor.md +++ b/docs/zh/editor.md @@ -1339,6 +1339,7 @@ func main() { - `Waiting for you · m:ss`(点击聚焦当前待处理请求卡片) - `Reconnecting · try n of 5`(按 `1、2、4、8、16 s` 指数退避重试,可通过 `Editor.AgentScheduleAfter` 注入调度器以确定性测试) - `Disconnected` 及 **Reconnect** 与 **Troubleshoot** 按钮(点击 **Troubleshoot** 直接在失败的步骤重新打开连接对话框,而非回到起始步)。 + ## 运行模式标记、滚动回放与冻结帧智能体提问(#1042) 在运行模式(`Play`、`PlayIn`、`StepPlay`、`PlayTick`)或连接运行中游戏期间,编辑器会持续保留最近 60 秒的滚动输入回放,支持在不中断运行的情况下打标记、冻结任意帧向智能体提问,并在输出面板提供崩溃堆栈卡片与一键回放到崩溃前一帧(对应 `docs/design/editor/PlayMode.dc.html`,严格采用 `Spec.dc.html` 设计令牌): @@ -1532,3 +1533,12 @@ func main() { - **将草图发送给智能体(`SendSketch` / `Editor.OnSendSketch`)**:输入框附带 `"Sketch · N marks"` 上下文芯片(点击可展开 `"Sent with this request"` 场景坐标预览)。发送时通过 `SketchAgentRequest` 传递结构化标记(编号、类型、场景坐标几何、标签)以及叠加了编号标记的视口渲染 PNG(`RenderSketchViewportPNG`)。 - **智能体解读卡片与 `scene_edit` 确认闸门**:发送草图后立即启用确认闸门(`SketchHoldActive() == true`),在用户确认前 `scene_edit` 等变更场景的 MCP 工具会被拒绝。智能体通过 `sketch_read` 读取草图,并通过 `sketch_reading`(`PostSketchReading`)提交复述卡片(`"I read your sketch as: …"` 与待确认假设)。点击 **Go ahead**(`ApproveSketchReading`、`⌘↵`)放行修改;点击 **Correct a mark**(`CorrectSketchMark`、`⇧M` 或点击任意编号条目)会重新进入草图模式并精确选中该标记,同时保持确认闸门生效;直接输入文字回复(`ReplyToSketchReading`)同样有效。 - **审查叠加层与保留 / 撤销行为**:确认后智能体的场景修改会打开审查卡片(`SketchReviewOpen`),内置 **Sketch overlay** 开关(`O`、`ToggleSketchReviewOverlay`,瓦片审查 `TileReview` 中同样支持)将草图以半透明点线叠加在结果之上。**Keep**(`KeepSketchReview` / `KeepTileReview`)保留修改并清空草图层;**Revert**(`RevertSketchReview` / `RevertAllTileReview`)撤销修改但保留草图标记以便再次发送。 + +## 智能体输入框中的参考图与固定到简报(#1027) + +在智能体输入框中为单次请求附加 PNG、JPEG 或 WebP 参考图,或将其固定到项目的游戏简报,界面严格遵循 `docs/design/editor/Spec.dc.html` 设计令牌并对应 `docs/design/editor/Sketch.dc.html`(*Paste or drop an image*、*Pin to brief*): + +- **拖放、粘贴或选取 PNG、JPEG 与 WebP**:将文件拖到智能体输入框上方时会显示符合 Spec 规范的 **“Drop to attach”** 拖放层(`SetAgentComposerDragOver`、`DropAgentReferenceFiles`);向输入框粘贴图片或图片文件(通过 `core.Input.OnPaste` 调用 `HandleAgentComposerPaste`,或调用 `PasteAgentReferenceImage`),或点击 **附加参考图** 按钮(`PickAndAttachAgentReferenceImages` / `CmdAttachReferenceImage`)会在内存中校验真实的 PNG、JPEG 或 WebP 文件头与像素(`DecodeAgentReferenceImage`)。不支持的文件类型(如 GIF、SVG、BMP、文本或损坏的图片)会被拒绝并在无障碍提示横幅中说明具体原因(`AgentAttachError`)。 +- **带悬停预览的单次请求标签**:每张附加的图片都会显示为包含缩略图、文件名、**Pin to brief** 按钮与 **×** 移除按钮的标签(`RemoveAgentReferenceImage`)。悬停或聚焦标签会在输入框上方弹出预览卡片,展示解码后的图片、格式、尺寸及作用范围(仅随本次请求发送)。发送请求(`SubmitAgentPrompt`)会将附加图片随 `AgentRequest.AttachedImages` 与 `AgentRequest.Images` 传入(并在 `AgentTurn.Images` 中记录缩略图),随后立即清空单次附加标签,确保下一次请求不再携带。 +- **固定到简报(`PinAgentReferenceImage`)**:点击 **Pin to brief** 会将图片复制到 `art/reference/`(存在不同内容同名文件时自动去重而不覆盖),并通过 YAML AST 编辑在 `brief.yaml` 的 `art.references` 下新增一条记录(完整保留原有字段与注释),整个操作作为 `Editor.History` 中的**单个原子可撤销步骤**执行。两个文件会立即出现在审查/变更列表(`RefreshChanges`)中,确认卡片会展示带 `+` 高亮的 YAML 差异及 **Undo** 按钮(`UndoLastBriefPin`);执行一次撤销即可同时移除复制的图片文件与新增的 YAML 行(若 `brief.yaml` 与空 `art/reference/` 目录是本次创建的也会一并清理)。 +- **始终附带标签(`brief.yaml`)**:只要项目存在 `brief.yaml`,输入框中就会显示 **Always** 行及带锁图标的 `brief.yaml` 标签(有固定参考图时显示数量)。悬停或点击该标签可预览全部已固定参考图,后续每次智能体请求都会通过 `AgentRequest.BriefImages` 与 `AgentRequest.Images` 自动携带这些图片。 diff --git a/packages/game/editor/agent.go b/packages/game/editor/agent.go index 29dc75350..e4cac2b00 100644 --- a/packages/game/editor/agent.go +++ b/packages/game/editor/agent.go @@ -261,6 +261,7 @@ type AgentTurnContext struct { 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" @@ -316,6 +317,9 @@ type AgentRequest struct { TriggerKind AutomationTriggerKind TriggerDetail string CheckpointID string + AttachedImages []AgentReferenceImage // one-shot reference images dropped or pasted for this request only + BriefImages []AgentReferenceImage // project-wide reference images joined through brief.yaml's Always chip + Images []AgentReferenceImage // deduplicated union of AttachedImages and BriefImages sent with this request } // AgentEventKind classifies one streamed event from an AgentRunner. @@ -400,6 +404,16 @@ type agentState struct { sessionID string turns []AgentTurn composerText string + attachedImages []AgentReferenceImage + attachSeq uint64 + attachImgVer uint64 + attachErr string + composerDragOver bool + previewImageID string + lastPinNotice *BriefPinNotice + lastPinCmd *pinReferenceImageCmd + briefRefCache map[string]cachedBriefRefImage + briefMeta cachedBriefMeta workingStep int workingTotal int activeRunCancel context.CancelFunc @@ -565,6 +579,14 @@ func (e *Editor) resetAgentForProject() { e.agent.turns = nil e.agent.queued = nil e.agent.composerText = "" + e.agent.attachedImages = nil + e.agent.attachErr = "" + e.agent.composerDragOver = false + e.agent.previewImageID = "" + e.agent.lastPinNotice = nil + e.agent.lastPinCmd = nil + e.agent.briefRefCache = nil + e.agent.briefMeta = cachedBriefMeta{} e.agent.workingStep = 0 e.agent.workingTotal = 0 e.agent.openRequest = nil @@ -1407,6 +1429,13 @@ func (e *Editor) InsertAgentComposerNewline() { func cloneAgentTurn(t AgentTurn) AgentTurn { t.Steps = slices.Clone(t.Steps) + if len(t.Images) > 0 { + imgs := make([]AgentReferenceImage, len(t.Images)) + for i, img := range t.Images { + imgs[i] = img.clone() + } + t.Images = imgs + } t.Context.SelectionIDs = slices.Clone(t.Context.SelectionIDs) t.Context.SelectionNames = slices.Clone(t.Context.SelectionNames) t.Context.ViewportPNG = slices.Clone(t.Context.ViewportPNG) diff --git a/packages/game/editor/agent_builtin.go b/packages/game/editor/agent_builtin.go index 84defeb6c..61eced79c 100644 --- a/packages/game/editor/agent_builtin.go +++ b/packages/game/editor/agent_builtin.go @@ -584,7 +584,11 @@ func (e *Editor) submitAgentTaskPromptInternal(task AgentTaskKind, prompt string return err } + attachedImgs, briefImgs, allImgs := e.collectRequestReferenceImages() e.agent.composerText = "" + e.agent.attachedImages = nil + e.agent.attachErr = "" + e.agent.previewImageID = "" e.agent.turnSeq++ e.agent.turnChangeSeq++ turnID := fmt.Sprintf("turn-%d", e.agent.turnSeq) @@ -595,9 +599,17 @@ func (e *Editor) submitAgentTaskPromptInternal(task AgentTaskKind, prompt string } } now := e.nowTime() + turnImages := make([]AgentReferenceImage, len(allImgs)) + for i, img := range allImgs { + cp := img.clone() + // Historical turns only render thumbnails from Pixels; avoid retaining multi-MiB raw encoded bytes in RAM. + cp.Data = nil + turnImages[i] = cp + } e.agent.turns = append(e.agent.turns, AgentTurn{ ID: turnID, Prompt: text, + Images: turnImages, Source: "panel", Status: "running", AgentName: clientName, @@ -643,17 +655,20 @@ func (e *Editor) submitAgentTaskPromptInternal(task AgentTaskKind, prompt string } } req := AgentRequest{ - ThreadID: threadID, - SessionID: sessionID, - Prompt: text, - ProjectRoot: e.agentProjectRoot(), - ScenePath: e.ScenePath, - SelectedID: e.SelectedID, - AgentKind: agentKind, - Permissions: e.agent.permissions, - Task: task, - Route: route, - Model: model, + ThreadID: threadID, + SessionID: sessionID, + Prompt: text, + ProjectRoot: e.agentProjectRoot(), + ScenePath: e.ScenePath, + SelectedID: e.SelectedID, + AgentKind: agentKind, + Permissions: e.agent.permissions, + Task: task, + Route: route, + Model: model, + AttachedImages: attachedImgs, + BriefImages: briefImgs, + Images: allImgs, } if builtIn, ok := runner.(*builtInAgentRunner); ok { @@ -1045,7 +1060,7 @@ func (r *builtInAgentRunner) Run(ctx context.Context, req AgentRequest, emit fun systemPrompt := buildBuiltInSystemPrompt(req) messages := []anthropicMessage{ - {Role: "user", Content: req.Prompt}, + {Role: "user", Content: buildBuiltInUserContent(req)}, } for iter := 0; iter < builtInMaxToolIterations; iter++ { @@ -1428,3 +1443,35 @@ func buildBuiltInSystemPrompt(req AgentRequest) string { } return b.String() } + +func buildBuiltInUserContent(req AgentRequest) any { + if len(req.Images) == 0 { + return req.Prompt + } + var blocks []map[string]any + for _, img := range req.Images { + mimeType := strings.TrimSpace(img.MIMEType) + if mimeType == "" { + mimeType = img.Format.MIMEType() + } + if len(img.Data) == 0 || len(img.Data) > builtInMaxToolImageBytes || mimeType == "" { + continue + } + blocks = append(blocks, map[string]any{ + "type": "image", + "source": map[string]any{ + "type": "base64", + "media_type": mimeType, + "data": base64.StdEncoding.EncodeToString(img.Data), + }, + }) + } + if len(blocks) == 0 { + return req.Prompt + } + blocks = append(blocks, map[string]any{ + "type": "text", + "text": req.Prompt, + }) + return blocks +} diff --git a/packages/game/editor/agent_references.go b/packages/game/editor/agent_references.go new file mode 100644 index 000000000..5ad95a02e --- /dev/null +++ b/packages/game/editor/agent_references.go @@ -0,0 +1,1516 @@ +package editor + +import ( + "bytes" + "errors" + "fmt" + "image" + "image/draw" + "image/jpeg" + "image/png" + "io/fs" + "os" + "path" + "path/filepath" + "slices" + "strings" + "time" + "unicode" + + "go.yaml.in/yaml/v3" + "golang.org/x/image/webp" + + "github.com/nsgo-dev/game/packages/game/project" + "github.com/nsgo-dev/nsgo/core" +) + +const ( + // AgentBriefPreviewID is the preview target ID used when hovering or focusing the brief.yaml Always chip. + AgentBriefPreviewID = "brief" + + maxAgentRefImageBytes = 16 << 20 // 16 MiB per attached or pinned reference image + maxAgentRefImageDim = 4096 // max width or height in pixels + maxAgentRefImagePixels = 16 << 20 // 16M pixels cap + maxAgentAttachedImages = 8 // max one-shot reference images attached to a single request + maxAgentBriefRefImages = 16 // max pinned reference images loaded from brief.yaml + maxAgentBriefYAMLBytes = 1 << 20 // 1 MiB cap for brief.yaml + agentRefFolderRel = "art/reference" +) + +// AgentImageFormat identifies one of the three supported reference image formats for agent requests. +type AgentImageFormat string + +const ( + AgentImagePNG AgentImageFormat = "png" + AgentImageJPEG AgentImageFormat = "jpeg" + AgentImageWebP AgentImageFormat = "webp" +) + +// MIMEType returns the standard MIME type for f. +func (f AgentImageFormat) MIMEType() string { + switch f { + case AgentImagePNG: + return "image/png" + case AgentImageJPEG: + return "image/jpeg" + case AgentImageWebP: + return "image/webp" + default: + return "" + } +} + +// Extension returns the canonical lowercase file extension (including the leading dot) for f. +func (f AgentImageFormat) Extension() string { + switch f { + case AgentImagePNG: + return ".png" + case AgentImageJPEG: + return ".jpg" + case AgentImageWebP: + return ".webp" + default: + return "" + } +} + +// Label returns the human-readable format name shown in previews and errors. +func (f AgentImageFormat) Label() string { + switch f { + case AgentImagePNG: + return "PNG" + case AgentImageJPEG: + return "JPEG" + case AgentImageWebP: + return "WebP" + default: + return strings.ToUpper(string(f)) + } +} + +// AgentReferenceImage is a validated PNG, JPEG, or WebP reference image attached to a single composer +// request or pinned to brief.yaml for every request in the project. +type AgentReferenceImage struct { + // ID uniquely identifies this image within the current composer draft (or "brief:" for pinned brief references). + ID string + // Name is the display file name (for example "spikes_ref.png"). + Name string + // Path is the project-relative slash path when pinned or read from brief.yaml (for example "art/reference/spikes_ref.png"), + // or empty for a one-shot ephemeral composer attachment. + Path string + // Format is AgentImagePNG, AgentImageJPEG, or AgentImageWebP. + Format AgentImageFormat + // MIMEType is "image/png", "image/jpeg", or "image/webp". + MIMEType string + // Data holds the raw encoded image bytes sent to the agent. + Data []byte + // Width and Height are the decoded pixel dimensions. + Width int + Height int + // Pinned reports whether this image has been copied to art/reference/ and added to brief.yaml. + Pinned bool + // FromBrief reports whether this image joined the request through brief.yaml (the Always chip). + FromBrief bool + // Note is an optional short description recorded alongside path in brief.yaml. + Note string + // Pixels holds the decoded RGBA image for in-memory thumbnail and hover preview rendering. + Pixels *image.RGBA + // ImageVersion uniquely keys core.ImageSource pixel uploads. + ImageVersion uint64 +} + +func (img AgentReferenceImage) clone() AgentReferenceImage { + cp := img + cp.Data = slices.Clone(img.Data) + return cp +} + +// BriefReference is one entry listed under art.references in brief.yaml. +type BriefReference struct { + // Path is the project-relative slash path to the reference image (for example "art/reference/spikes_ref.png"). + Path string + // Note is an optional short description for the agent. + Note string +} + +// BriefPinDiffLine is one formatted line in the Pin to brief confirmation card's YAML diff. +type BriefPinDiffLine struct { + Sign string + Text string + Added bool + Removed bool +} + +// BriefPinNotice describes the most recent Pin to brief action shown in the composer confirmation card with Undo. +type BriefPinNotice struct { + ImageID string + Name string + RelPath string + Note string + Diff []BriefPinDiffLine +} + +type cachedBriefRefImage struct { + modTime time.Time + size int64 + img AgentReferenceImage +} + +type cachedBriefMeta struct { + valid bool + path string + exists bool + modTime time.Time + size int64 + refs []BriefReference +} + +func (e *Editor) invalidateBriefReferenceCaches() { + if e == nil { + return + } + e.agent.briefMeta = cachedBriefMeta{} + clear(e.agent.briefRefCache) +} + +// DecodeAgentReferenceImage validates that data is a well-formed PNG, JPEG, or WebP image within safe bounds +// and decodes its pixels into an RGBA image for thumbnails and hover previews. +// Unsupported file types (such as GIF, SVG, BMP, text, or YAML) are refused with a clear reason. +func DecodeAgentReferenceImage(name string, data []byte) (AgentReferenceImage, error) { + displayName := strings.TrimSpace(filepath.Base(strings.ReplaceAll(strings.TrimSpace(name), "\\", "/"))) + if displayName == "." || displayName == "/" { + displayName = "" + } + if len(data) == 0 { + return AgentReferenceImage{}, formatRefAttachError(displayName, "empty file", "file is empty") + } + if len(data) > maxAgentRefImageBytes { + return AgentReferenceImage{}, fmt.Errorf("cannot attach %s: file is larger than %d MiB", quoteDisplayName(displayName), maxAgentRefImageBytes>>20) + } + + format, detectedOther := sniffAgentImageFormat(displayName, data) + if format == "" { + reason := detectedOther + if reason == "" { + if ext := strings.ToLower(path.Ext(displayName)); ext != "" { + reason = ext + } else { + reason = "unsupported format" + } + } + return AgentReferenceImage{}, formatRefAttachError(displayName, reason, "only PNG, JPEG, or WebP images are supported") + } + + var ( + cfg image.Config + img image.Image + err error + ) + switch format { + case AgentImagePNG: + cfg, err = png.DecodeConfig(bytes.NewReader(data)) + if err != nil { + return AgentReferenceImage{}, fmt.Errorf("cannot attach %s: invalid PNG image (%v)", quoteDisplayName(displayName), err) + } + if err := validateRefImageDimensions(displayName, cfg.Width, cfg.Height); err != nil { + return AgentReferenceImage{}, err + } + img, err = png.Decode(bytes.NewReader(data)) + case AgentImageJPEG: + cfg, err = jpeg.DecodeConfig(bytes.NewReader(data)) + if err != nil { + return AgentReferenceImage{}, fmt.Errorf("cannot attach %s: invalid JPEG image (%v)", quoteDisplayName(displayName), err) + } + if err := validateRefImageDimensions(displayName, cfg.Width, cfg.Height); err != nil { + return AgentReferenceImage{}, err + } + img, err = jpeg.Decode(bytes.NewReader(data)) + case AgentImageWebP: + cfg, err = webp.DecodeConfig(bytes.NewReader(data)) + if err != nil { + return AgentReferenceImage{}, fmt.Errorf("cannot attach %s: invalid WebP image (%v)", quoteDisplayName(displayName), err) + } + if err := validateRefImageDimensions(displayName, cfg.Width, cfg.Height); err != nil { + return AgentReferenceImage{}, err + } + img, err = webp.Decode(bytes.NewReader(data)) + } + if err != nil { + return AgentReferenceImage{}, fmt.Errorf("cannot attach %s: invalid %s image (%v)", quoteDisplayName(displayName), format.Label(), err) + } + + b := img.Bounds() + w, h := b.Dx(), b.Dy() + if err := validateRefImageDimensions(displayName, w, h); err != nil { + return AgentReferenceImage{}, err + } + rgba := image.NewRGBA(image.Rect(0, 0, w, h)) + draw.Draw(rgba, rgba.Bounds(), img, b.Min, draw.Src) + + cleanName := sanitizeReferenceFileName(displayName, format) + return AgentReferenceImage{ + Name: cleanName, + Format: format, + MIMEType: format.MIMEType(), + Data: slices.Clone(data), + Width: w, + Height: h, + Pixels: rgba, + }, nil +} + +func validateRefImageDimensions(displayName string, w, h int) error { + if w <= 0 || h <= 0 { + return fmt.Errorf("cannot attach %s: image dimensions are invalid (%dx%d)", quoteDisplayName(displayName), w, h) + } + if w > maxAgentRefImageDim || h > maxAgentRefImageDim { + return fmt.Errorf("cannot attach %s: image is too large (%dx%d, max %dx%d)", quoteDisplayName(displayName), w, h, maxAgentRefImageDim, maxAgentRefImageDim) + } + if int64(w)*int64(h) > maxAgentRefImagePixels { + return fmt.Errorf("cannot attach %s: image has too many pixels (%dx%d)", quoteDisplayName(displayName), w, h) + } + return nil +} + +func sniffAgentImageFormat(name string, data []byte) (AgentImageFormat, string) { + // PNG magic: 89 50 4E 47 0D 0A 1A 0A + if len(data) >= 8 && bytes.Equal(data[:8], []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}) { + return AgentImagePNG, "" + } + // JPEG magic: FF D8 FF + if len(data) >= 3 && data[0] == 0xff && data[1] == 0xd8 && data[2] == 0xff { + return AgentImageJPEG, "" + } + // WebP magic: RIFF <4 bytes> WEBP + if len(data) >= 12 && bytes.Equal(data[:4], []byte("RIFF")) && bytes.Equal(data[8:12], []byte("WEBP")) { + return AgentImageWebP, "" + } + // Identify common unsupported types so the refusal explains what was dropped/pasted. + if len(data) >= 6 && (bytes.HasPrefix(data, []byte("GIF87a")) || bytes.HasPrefix(data, []byte("GIF89a"))) { + return "", "GIF" + } + if len(data) >= 2 && data[0] == 'B' && data[1] == 'M' { + return "", "BMP" + } + if len(data) >= 4 && bytes.HasPrefix(data, []byte("%PDF")) { + return "", "PDF" + } + trimmed := bytes.TrimSpace(data) + if bytes.HasPrefix(trimmed, []byte("= maxAgentAttachedImages { + err := fmt.Errorf("cannot attach more than %d reference images to one request", maxAgentAttachedImages) + e.agent.attachErr = err.Error() + e.Status = err.Error() + e.notify() + return AgentReferenceImage{}, err + } + img, err := DecodeAgentReferenceImage(name, data) + if err != nil { + e.agent.attachErr = err.Error() + e.Status = err.Error() + e.notify() + return AgentReferenceImage{}, err + } + e.agent.attachSeq++ + e.agent.attachImgVer++ + img.ID = fmt.Sprintf("img-%d", e.agent.attachSeq) + img.ImageVersion = e.agent.attachImgVer + // If no name was provided (for example pasted from clipboard), give each paste a distinct filename. + if strings.TrimSpace(name) == "" && e.agent.attachSeq > 1 { + img.Name = fmt.Sprintf("pasted_%d%s", e.agent.attachSeq, img.Format.Extension()) + } + e.agent.attachedImages = append(e.agent.attachedImages, img) + e.agent.attachErr = "" + e.Status = fmt.Sprintf("Attached %s for this request", img.Name) + e.notify() + return img.clone(), nil +} + +// AttachAgentReferenceFile reads a local file path or file:// URL, validates it as PNG, JPEG, or WebP, +// and attaches it to the current composer request only. +func (e *Editor) AttachAgentReferenceFile(pathOrURI string) (AgentReferenceImage, error) { + if e == nil { + return AgentReferenceImage{}, errors.New("editor: nil editor") + } + if e.playing { + return AgentReferenceImage{}, ErrPlaying + } + if e.agent.mode == AgentModeNone { + return AgentReferenceImage{}, errors.New("editor: agent is disabled") + } + raw := strings.TrimSpace(pathOrURI) + if raw == "" { + err := errors.New("cannot attach empty file path: only PNG, JPEG, or WebP images are supported") + e.agent.attachErr = err.Error() + e.notify() + return AgentReferenceImage{}, err + } + localPath, err := resolveReferenceFileInput(raw) + if err != nil { + e.agent.attachErr = err.Error() + e.Status = err.Error() + e.notify() + return AgentReferenceImage{}, err + } + base := filepath.Base(localPath) + // Fast-fail clearly on obviously unsupported extensions before reading huge files, while still validating magic bytes for image extensions. + if ext := strings.ToLower(path.Ext(base)); ext != "" && ext != ".png" && ext != ".jpg" && ext != ".jpeg" && ext != ".webp" { + err := formatRefAttachError(base, ext, "only PNG, JPEG, or WebP images are supported") + e.agent.attachErr = err.Error() + e.Status = err.Error() + e.notify() + return AgentReferenceImage{}, err + } + // Refuse directories and special files (FIFOs, sockets, device nodes) before opening so a pipe cannot block the UI thread. + info, statErr := os.Stat(localPath) + if statErr != nil { + refErr := fmt.Errorf("cannot attach %q: %w", base, statErr) + e.agent.attachErr = refErr.Error() + e.Status = refErr.Error() + e.notify() + return AgentReferenceImage{}, refErr + } + if !info.Mode().IsRegular() { + refErr := formatRefAttachError(base, "not a regular file", "only PNG, JPEG, or WebP images are supported") + e.agent.attachErr = refErr.Error() + e.Status = refErr.Error() + e.notify() + return AgentReferenceImage{}, refErr + } + data, err := readFileLimited(localPath, maxAgentRefImageBytes) + if err != nil { + refErr := fmt.Errorf("cannot attach %q: %w", base, err) + e.agent.attachErr = refErr.Error() + e.Status = refErr.Error() + e.notify() + return AgentReferenceImage{}, refErr + } + return e.AttachAgentReferenceBytes(base, data) +} + +func resolveReferenceFileInput(raw string) (string, error) { + trimmed := strings.TrimSpace(raw) + if idx := strings.Index(trimmed, "://"); idx > 0 { + scheme := strings.ToLower(trimmed[:idx]) + if scheme != "file" { + return "", fmt.Errorf("cannot attach %q: unsupported URI scheme %q (only local PNG, JPEG, or WebP files are supported)", trimmed, scheme) + } + // Always validate host (reject non-localhost remote hosts) and normalize Windows drive paths first. + p, err := parseLocalFileInput(trimmed) + if err != nil { + return "", fmt.Errorf("cannot attach %q: %w", trimmed, err) + } + if f, ferr := core.FileFromURL(trimmed); ferr == nil && f.Path != "" { + return f.Path, nil + } + return p, nil + } + return parseLocalFileInput(trimmed) +} + +// DropAgentReferenceFiles attaches one or more dropped file paths or file:// URLs onto the Agent composer. +// Valid PNG/JPEG/WebP files are attached as chips; unsupported files are refused with a clear reason. +func (e *Editor) DropAgentReferenceFiles(uris []string) ([]AgentReferenceImage, error) { + if e == nil { + return nil, errors.New("editor: nil editor") + } + e.agent.composerDragOver = false + if e.playing { + e.notify() + return nil, ErrPlaying + } + if e.agent.mode == AgentModeNone { + e.notify() + return nil, errors.New("editor: agent is disabled") + } + var attached []AgentReferenceImage + var errs []string + for _, raw := range uris { + if strings.TrimSpace(raw) == "" { + continue + } + img, err := e.AttachAgentReferenceFile(raw) + if err != nil { + errs = append(errs, err.Error()) + continue + } + attached = append(attached, img) + } + if len(errs) > 0 { + msg := strings.Join(errs, "; ") + e.agent.attachErr = msg + e.Status = msg + e.notify() + return attached, errors.New(msg) + } + e.notify() + return attached, nil +} + +// HandleAgentComposerPaste processes a core.PasteEvent from the Agent composer input. +// Returns (attached, handled, err). Plain text pastes return (nil, false, nil) so the input inserts text normally. +func (e *Editor) HandleAgentComposerPaste(ev core.PasteEvent) ([]AgentReferenceImage, bool, error) { + if e == nil { + return nil, false, errors.New("editor: nil editor") + } + if len(ev.Files) == 0 && len(ev.URIs) == 0 { + return nil, false, nil + } + if e.playing { + return nil, true, ErrPlaying + } + if e.agent.mode == AgentModeNone { + return nil, false, errors.New("editor: agent is disabled") + } + var attached []AgentReferenceImage + var errs []string + for _, f := range ev.Files { + name := strings.TrimSpace(f.Name) + if name == "" && f.MIME != "" { + switch strings.ToLower(strings.TrimSpace(f.MIME)) { + case "image/png": + name = "pasted.png" + case "image/jpeg", "image/jpg": + name = "pasted.jpg" + case "image/webp": + name = "pasted.webp" + } + } + img, err := e.AttachAgentReferenceBytes(name, f.Data) + if err != nil { + errs = append(errs, err.Error()) + continue + } + attached = append(attached, img) + } + for _, uri := range ev.URIs { + if strings.TrimSpace(uri) == "" { + continue + } + img, err := e.AttachAgentReferenceFile(uri) + if err != nil { + errs = append(errs, err.Error()) + continue + } + attached = append(attached, img) + } + if len(errs) > 0 { + msg := strings.Join(errs, "; ") + e.agent.attachErr = msg + e.Status = msg + e.notify() + return attached, true, errors.New(msg) + } + return attached, true, nil +} + +// PasteAgentReferenceImage reads an image or copied file(s) from the clipboard (via Editor.ReadClipboardImage / +// Editor.ReadClipboardFiles when set, or the attached UI scope) and attaches them to the composer. +func (e *Editor) PasteAgentReferenceImage() ([]AgentReferenceImage, bool, error) { + if e == nil { + return nil, false, errors.New("editor: nil editor") + } + if e.playing { + return nil, false, ErrPlaying + } + if e.ReadClipboardImage != nil { + var ( + gotImg core.ClipboardImage + gotOK bool + gotErr error + called bool + ) + e.ReadClipboardImage(func(img core.ClipboardImage, ok bool, err error) { + gotImg, gotOK, gotErr, called = img, ok, err, true + }) + if called { + if gotErr != nil { + e.agent.attachErr = gotErr.Error() + e.notify() + return nil, true, gotErr + } + if gotOK && len(gotImg.PNG) > 0 { + img, err := e.AttachAgentReferenceBytes("pasted.png", gotImg.PNG) + if err != nil { + return nil, true, err + } + return []AgentReferenceImage{img}, true, nil + } + } + } + if e.ReadClipboardFiles != nil { + var uris []string + e.ReadClipboardFiles(func(u []string) { uris = u }) + if len(uris) > 0 { + attached, err := e.DropAgentReferenceFiles(uris) + return attached, true, err + } + } + if cx := e.agent.getScope(); cx != nil && !cx.Disposed() { + startRoot := e.agentProjectRoot() + cx.ReadClipboardImage(func(img core.ClipboardImage, ok bool, err error) { + if cx.Disposed() || e.playing || e.agent.mode == AgentModeNone || e.agentProjectRoot() != startRoot { + return + } + if err != nil { + e.agent.attachErr = err.Error() + e.Status = err.Error() + e.notify() + return + } + if ok && len(img.PNG) > 0 { + _, _ = e.AttachAgentReferenceBytes("pasted.png", img.PNG) + return + } + cx.ReadClipboardFiles(func(uris []string) { + if cx.Disposed() || e.playing || e.agent.mode == AgentModeNone || e.agentProjectRoot() != startRoot { + return + } + if len(uris) > 0 { + _, _ = e.DropAgentReferenceFiles(uris) + } + }) + }) + return nil, true, nil + } + return nil, false, nil +} + +// PickAndAttachAgentReferenceImages opens the native file picker (or Editor.PickAgentReferenceFiles in tests) +// for PNG, JPEG, and WebP images and attaches any chosen files to the next request. +func (e *Editor) PickAndAttachAgentReferenceImages() { + if e == nil || e.playing || e.agent.mode == AgentModeNone { + return + } + if e.PickAgentReferenceFiles != nil { + e.PickAgentReferenceFiles(func(uris []string) { + if len(uris) > 0 { + _, _ = e.DropAgentReferenceFiles(uris) + } + }) + return + } + cx := e.agent.getScope() + if cx == nil || cx.Disposed() { + return + } + startDir := e.agentProjectRoot() + cx.PickFiles(core.PickFilesOptions{ + Multiple: true, + Types: []string{"image/png", "image/jpeg", "image/webp", ".png", ".jpg", ".jpeg", ".webp"}, + TypesName: "Images (PNG, JPEG, WebP)", + Title: "Attach reference image", + Button: "Attach", + Start: startDir, + }, func(files []core.File, err error) { + if err != nil || len(files) == 0 || cx.Disposed() || e.playing || e.agent.mode == AgentModeNone || e.agentProjectRoot() != startDir { + return + } + uris := make([]string, 0, len(files)) + for _, f := range files { + if f.Path != "" { + uris = append(uris, f.Path) + } + } + if len(uris) > 0 { + _, _ = e.DropAgentReferenceFiles(uris) + } + }) +} + +// RemoveAgentReferenceImage removes an attached one-shot image chip from the current composer draft. +func (e *Editor) RemoveAgentReferenceImage(id string) bool { + if e == nil || id == "" { + return false + } + idx := -1 + for i := range e.agent.attachedImages { + if e.agent.attachedImages[i].ID == id { + idx = i + break + } + } + if idx < 0 { + return false + } + e.agent.attachedImages = append(e.agent.attachedImages[:idx], e.agent.attachedImages[idx+1:]...) + if e.agent.previewImageID == id { + e.agent.previewImageID = "" + } + e.notify() + return true +} + +// ClearAgentAttachedImages removes all one-shot reference image attachments from the current composer draft. +func (e *Editor) ClearAgentAttachedImages() { + if e == nil || len(e.agent.attachedImages) == 0 { + return + } + e.agent.attachedImages = nil + if e.agent.previewImageID != "" && e.agent.previewImageID != AgentBriefPreviewID { + e.agent.previewImageID = "" + } + e.notify() +} + +// verifyBriefReadPath ensures absPath is lexically inside rootDir, traverses no symlinks +// anywhere below rootDir (file or intermediate directories), and resolves within rootDir. +func verifyBriefReadPath(rootDir, absPath, relLabel string) error { + if err := verifyAssetGenWritePath(rootDir, absPath, relLabel); err != nil { + return err + } + return verifyFileWithinRoot(rootDir, absPath, relLabel) +} + +func (e *Editor) readBriefMeta() (exists bool, refs []BriefReference) { + root := e.agentProjectRoot() + if root == "" { + return false, nil + } + briefAbs := filepath.Join(root, project.BriefFileName) + info, err := os.Lstat(briefAbs) + if err != nil { + e.agent.briefMeta = cachedBriefMeta{valid: true, path: briefAbs, exists: false} + return false, nil + } + if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() { + e.agent.briefMeta = cachedBriefMeta{valid: true, path: briefAbs, exists: false} + return false, nil + } + if e.agent.briefMeta.valid && + e.agent.briefMeta.path == briefAbs && + e.agent.briefMeta.exists && + e.agent.briefMeta.size == info.Size() && + e.agent.briefMeta.modTime.Equal(info.ModTime()) { + return true, slices.Clone(e.agent.briefMeta.refs) + } + if err := verifyBriefReadPath(root, briefAbs, project.BriefFileName); err != nil { + e.agent.briefMeta = cachedBriefMeta{valid: true, path: briefAbs, exists: false} + return false, nil + } + data, err := readFileLimited(briefAbs, maxAgentBriefYAMLBytes) + if err != nil { + e.agent.briefMeta = cachedBriefMeta{valid: true, path: briefAbs, exists: true, modTime: info.ModTime(), size: info.Size()} + return true, nil + } + parsed := parseBriefReferencesYAML(data) + e.agent.briefMeta = cachedBriefMeta{ + valid: true, + path: briefAbs, + exists: true, + modTime: info.ModTime(), + size: info.Size(), + refs: slices.Clone(parsed), + } + return true, parsed +} + +// BriefFileExists reports whether brief.yaml exists as a regular confined file at the open project root. +func (e *Editor) BriefFileExists() bool { + exists, _ := e.readBriefMeta() + return exists +} + +// BriefReferences reads the list of pinned reference images under art.references in /brief.yaml. +func (e *Editor) BriefReferences() []BriefReference { + _, refs := e.readBriefMeta() + return refs +} + +func parseBriefReferencesYAML(data []byte) []BriefReference { + var root yaml.Node + if err := yaml.Unmarshal(data, &root); err != nil { + return nil + } + doc := &root + if doc.Kind == yaml.DocumentNode && len(doc.Content) > 0 { + doc = doc.Content[0] + } + if doc.Kind != yaml.MappingNode { + return nil + } + artNode := yamlMapValue(doc, "art") + if artNode == nil || artNode.Kind != yaml.MappingNode { + return nil + } + refsNode := yamlMapValue(artNode, "references") + if refsNode == nil || refsNode.Kind != yaml.SequenceNode { + return nil + } + var out []BriefReference + for _, item := range refsNode.Content { + switch item.Kind { + case yaml.ScalarNode: + p := cleanBriefRefPath(item.Value) + if p != "" { + out = append(out, BriefReference{Path: p}) + } + case yaml.MappingNode: + pNode := yamlMapValue(item, "path") + if pNode == nil || pNode.Kind != yaml.ScalarNode { + continue + } + p := cleanBriefRefPath(pNode.Value) + if p == "" { + continue + } + var note string + if nNode := yamlMapValue(item, "note"); nNode != nil && nNode.Kind == yaml.ScalarNode { + note = strings.TrimSpace(nNode.Value) + } + out = append(out, BriefReference{Path: p, Note: note}) + } + } + return out +} + +func cleanBriefRefPath(raw string) string { + s := strings.TrimSpace(strings.ReplaceAll(raw, "\\", "/")) + if s == "" { + return "" + } + s = path.Clean(s) + s = strings.TrimPrefix(s, "./") + if s == "." || s == ".." || strings.HasPrefix(s, "../") || strings.HasPrefix(s, "/") { + return "" + } + return s +} + +func yamlMapValue(m *yaml.Node, key string) *yaml.Node { + if m == nil || m.Kind != yaml.MappingNode { + return nil + } + for i := 0; i+1 < len(m.Content); i += 2 { + if m.Content[i].Kind == yaml.ScalarNode && m.Content[i].Value == key { + return m.Content[i+1] + } + } + return nil +} + +// BriefReferenceImages loads and validates all pinned PNG/JPEG/WebP reference images listed in brief.yaml. +// Valid images are cached by file modtime and size so repeated UI renders do not re-decode from disk. +func (e *Editor) BriefReferenceImages() []AgentReferenceImage { + root := e.agentProjectRoot() + if root == "" { + return nil + } + refs := e.BriefReferences() + if len(refs) == 0 { + return nil + } + if e.agent.briefRefCache == nil { + e.agent.briefRefCache = make(map[string]cachedBriefRefImage) + } + var out []AgentReferenceImage + seen := make(map[string]bool, len(refs)) + for _, ref := range refs { + if len(out) >= maxAgentBriefRefImages { + break + } + if seen[ref.Path] { + continue + } + seen[ref.Path] = true + abs := filepath.Join(root, filepath.FromSlash(ref.Path)) + if err := verifyBriefReadPath(root, abs, ref.Path); err != nil { + continue + } + info, err := os.Lstat(abs) + if err != nil || !info.Mode().IsRegular() || info.Size() <= 0 || info.Size() > maxAgentRefImageBytes { + continue + } + if cached, ok := e.agent.briefRefCache[ref.Path]; ok && cached.size == info.Size() && cached.modTime.Equal(info.ModTime()) { + img := cached.img.clone() + img.Note = ref.Note + out = append(out, img) + continue + } + data, err := readFileLimited(abs, maxAgentRefImageBytes) + if err != nil { + continue + } + decoded, err := DecodeAgentReferenceImage(path.Base(ref.Path), data) + if err != nil { + continue + } + e.agent.attachImgVer++ + decoded.ID = "brief:" + ref.Path + decoded.Name = path.Base(ref.Path) + decoded.Path = ref.Path + decoded.Pinned = true + decoded.FromBrief = true + decoded.Note = ref.Note + decoded.ImageVersion = e.agent.attachImgVer + e.agent.briefRefCache[ref.Path] = cachedBriefRefImage{ + modTime: info.ModTime(), + size: info.Size(), + img: decoded.clone(), + } + out = append(out, decoded) + } + for k := range e.agent.briefRefCache { + if !seen[k] { + delete(e.agent.briefRefCache, k) + } + } + return out +} + +// PinAgentReferenceImage copies the attached image with the given ID to art/reference/ +// and adds it to art.references in brief.yaml as one atomic, undoable Editor.History step. +// Undo removes both the copied file and the YAML entry cleanly. +func (e *Editor) PinAgentReferenceImage(id, note string) (BriefPinNotice, error) { + if e == nil { + return BriefPinNotice{}, errors.New("editor: nil editor") + } + if e.playing { + return BriefPinNotice{}, ErrPlaying + } + if e.MergeConflictOpen() { + return BriefPinNotice{}, ErrMergeConflictInProgress + } + if e.HistoryPreviewActive() { + return BriefPinNotice{}, ErrHistoryPreview + } + root := e.agentProjectRoot() + if root == "" { + return BriefPinNotice{}, ErrNoProject + } + idx := -1 + for i := range e.agent.attachedImages { + if e.agent.attachedImages[i].ID == id { + idx = i + break + } + } + if idx < 0 { + return BriefPinNotice{}, fmt.Errorf("editor: attached image %q not found", id) + } + img := e.agent.attachedImages[idx] + if img.Pinned && img.Path != "" { + if e.agent.lastPinNotice != nil && e.agent.lastPinNotice.ImageID == id { + return *e.AgentLastPinNotice(), nil + } + return BriefPinNotice{ + ImageID: id, + Name: path.Base(img.Path), + RelPath: img.Path, + Note: strings.TrimSpace(note), + }, nil + } + + // Resolve unique target file path under art/reference/. + relPath, absImagePath, fileExisted, err := resolvePinImageTarget(root, img.Name, img.Data) + if err != nil { + return BriefPinNotice{}, err + } + artDirAbs := filepath.Join(root, "art") + refDirAbs := filepath.Join(root, "art", "reference") + _, errArt := os.Stat(artDirAbs) + artDirExisted := errArt == nil + _, errRef := os.Stat(refDirAbs) + refDirExisted := errRef == nil + + briefAbs := filepath.Join(root, project.BriefFileName) + if err := verifyAssetGenWritePath(root, briefAbs, project.BriefFileName); err != nil { + return BriefPinNotice{}, err + } + var beforeBrief []byte + briefExisted := false + if fi, statErr := os.Lstat(briefAbs); statErr == nil { + if !fi.Mode().IsRegular() { + return BriefPinNotice{}, fmt.Errorf("editor: %s is not a regular file", project.BriefFileName) + } + if err := verifyBriefReadPath(root, briefAbs, project.BriefFileName); err != nil { + return BriefPinNotice{}, err + } + beforeBrief, err = readFileLimited(briefAbs, maxAgentBriefYAMLBytes) + if err != nil { + return BriefPinNotice{}, fmt.Errorf("editor: read brief.yaml: %w", err) + } + briefExisted = true + } else if !errors.Is(statErr, fs.ErrNotExist) { + return BriefPinNotice{}, statErr + } + + trimmedNote := sanitizeSingleLineMeta(note) + afterBrief, err := appendBriefReferenceYAML(beforeBrief, relPath, trimmedNote) + if err != nil { + return BriefPinNotice{}, err + } + diffLines := buildBriefPinDiff(beforeBrief, afterBrief) + notice := BriefPinNotice{ + ImageID: id, + Name: path.Base(relPath), + RelPath: relPath, + Note: trimmedNote, + Diff: diffLines, + } + + cmd := &pinReferenceImageCmd{ + ed: e, + rootDir: root, + label: fmt.Sprintf("Pin %s to brief", notice.Name), + imageID: id, + relPath: relPath, + absImagePath: absImagePath, + imageBytes: slices.Clone(img.Data), + fileExisted: fileExisted, + artDirAbs: artDirAbs, + artDirExisted: artDirExisted, + refDirAbs: refDirAbs, + refDirExisted: refDirExisted, + briefAbs: briefAbs, + briefExisted: briefExisted, + beforeBrief: slices.Clone(beforeBrief), + afterBrief: slices.Clone(afterBrief), + notice: notice, + } + if err := e.History.execute(cmd); err != nil { + return BriefPinNotice{}, err + } + return *e.AgentLastPinNotice(), nil +} + +// CanUndoLastBriefPin reports whether the most recent Pin to brief command is currently at the top +// of Editor.History and can be undone safely without reverting unrelated later edits. +func (e *Editor) CanUndoLastBriefPin() bool { + if e == nil || e.playing || e.MergeConflictOpen() || e.HistoryPreviewActive() { + return false + } + if e.agent.lastPinCmd == nil || e.History == nil { + return false + } + return e.History.topUndoCmd() == e.agent.lastPinCmd +} + +// UndoLastBriefPin undoes the Pin to brief step via Editor.Undo() only when it is still the latest +// command in Editor.History, never silently undoing unrelated later edits. +func (e *Editor) UndoLastBriefPin() bool { + if !e.CanUndoLastBriefPin() { + return false + } + return e.Undo() +} + +func resolvePinImageTarget(root, name string, data []byte) (relPath, absPath string, existedSame bool, err error) { + base := filepath.Base(strings.ReplaceAll(strings.TrimSpace(name), "\\", "/")) + if base == "" || base == "." || base == ".." { + base = "reference.png" + } + ext := path.Ext(base) + stem := strings.TrimSuffix(base, ext) + for attempt := 1; attempt <= 999; attempt++ { + candidate := base + if attempt > 1 { + candidate = fmt.Sprintf("%s_%d%s", stem, attempt, ext) + } + rel := path.Join(agentRefFolderRel, candidate) + abs := filepath.Join(root, filepath.FromSlash(rel)) + if err := verifyAssetGenWritePath(root, abs, rel); err != nil { + return "", "", false, err + } + fi, lerr := os.Lstat(abs) + if errors.Is(lerr, fs.ErrNotExist) { + return rel, abs, false, nil + } + if lerr != nil { + return "", "", false, lerr + } + if fi.Mode()&os.ModeSymlink != 0 { + return "", "", false, fmt.Errorf("editor: asset path %q refuses symlink file", rel) + } + if !fi.Mode().IsRegular() || fi.Size() != int64(len(data)) { + // Different size or directory: allocate a distinct suffixed filename without reading it. + continue + } + existing, rerr := readFileLimited(abs, maxAgentRefImageBytes) + if rerr != nil { + return "", "", false, rerr + } + if bytes.Equal(existing, data) { + return rel, abs, true, nil + } + } + return "", "", false, fmt.Errorf("editor: could not allocate unique filename under %s for %q", agentRefFolderRel, base) +} + +// appendBriefReferenceYAML parses existing brief.yaml (if non-empty) and appends an entry under art.references, +// preserving all existing keys, ordering, and comments. When creating a new brief.yaml, it emits a canonical +// version 1 header with BriefSchemaComment so project.ParseBrief accepts it cleanly. +func appendBriefReferenceYAML(existing []byte, relPath, note string) ([]byte, error) { + var doc yaml.Node + fresh := len(bytes.TrimSpace(existing)) == 0 + if fresh { + doc = yaml.Node{ + Kind: yaml.DocumentNode, + Content: []*yaml.Node{ + { + Kind: yaml.MappingNode, + Tag: "!!map", + Content: []*yaml.Node{ + {Kind: yaml.ScalarNode, Tag: "!!str", Value: "version"}, + {Kind: yaml.ScalarNode, Tag: "!!int", Value: fmt.Sprintf("%d", project.BriefVersion)}, + }, + }, + }, + } + } else { + if err := yaml.Unmarshal(existing, &doc); err != nil { + return nil, fmt.Errorf("editor: parse brief.yaml: %w", err) + } + if doc.Kind != yaml.DocumentNode || len(doc.Content) == 0 { + fresh = true + doc = yaml.Node{ + Kind: yaml.DocumentNode, + Content: []*yaml.Node{ + { + Kind: yaml.MappingNode, + Tag: "!!map", + Content: []*yaml.Node{ + {Kind: yaml.ScalarNode, Tag: "!!str", Value: "version"}, + {Kind: yaml.ScalarNode, Tag: "!!int", Value: fmt.Sprintf("%d", project.BriefVersion)}, + }, + }, + }, + } + } + if doc.Content[0].Kind != yaml.MappingNode { + return nil, errors.New("editor: brief.yaml root must be a YAML mapping") + } + } + + rootMap := doc.Content[0] + artNode := yamlMapValue(rootMap, "art") + if artNode == nil { + artNode = &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"} + rootMap.Content = append(rootMap.Content, + &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "art"}, + artNode, + ) + } else if artNode.Kind != yaml.MappingNode { + return nil, errors.New("editor: brief.yaml art field must be a YAML mapping") + } + + refsNode := yamlMapValue(artNode, "references") + if refsNode == nil { + refsNode = &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq"} + artNode.Content = append(artNode.Content, + &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "references"}, + refsNode, + ) + } else if refsNode.Kind != yaml.SequenceNode { + return nil, errors.New("editor: brief.yaml art.references field must be a YAML sequence") + } + + // Check if relPath is already present; if so, update note if requested and avoid duplicating the entry. + for _, item := range refsNode.Content { + if item.Kind == yaml.ScalarNode && cleanBriefRefPath(item.Value) == relPath { + return encodeBriefYAMLNode(&doc, fresh) + } + if item.Kind == yaml.MappingNode { + if pNode := yamlMapValue(item, "path"); pNode != nil && cleanBriefRefPath(pNode.Value) == relPath { + if note != "" { + if nNode := yamlMapValue(item, "note"); nNode != nil { + nNode.Value = note + } else { + item.Content = append(item.Content, + &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "note"}, + &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: note}, + ) + } + } + return encodeBriefYAMLNode(&doc, fresh) + } + } + } + + entry := &yaml.Node{ + Kind: yaml.MappingNode, + Tag: "!!map", + Content: []*yaml.Node{ + {Kind: yaml.ScalarNode, Tag: "!!str", Value: "path"}, + {Kind: yaml.ScalarNode, Tag: "!!str", Value: relPath}, + }, + } + if note != "" { + entry.Content = append(entry.Content, + &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "note"}, + &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: note}, + ) + } + refsNode.Content = append(refsNode.Content, entry) + return encodeBriefYAMLNode(&doc, fresh) +} + +func encodeBriefYAMLNode(doc *yaml.Node, withSchemaComment bool) ([]byte, error) { + var buf bytes.Buffer + if withSchemaComment { + buf.WriteString(project.BriefSchemaComment) + buf.WriteByte('\n') + } + enc := yaml.NewEncoder(&buf) + enc.SetIndent(2) + if err := enc.Encode(doc); err != nil { + _ = enc.Close() + return nil, fmt.Errorf("editor: encode brief.yaml: %w", err) + } + if err := enc.Close(); err != nil { + return nil, fmt.Errorf("editor: encode brief.yaml: %w", err) + } + return buf.Bytes(), nil +} + +// buildBriefPinDiff produces a concise diff showing the surrounding brief.yaml lines and the newly added lines. +func buildBriefPinDiff(before, after []byte) []BriefPinDiffLine { + oldLines := splitBriefDiffLines(before) + newLines := splitBriefDiffLines(after) + oldSet := make(map[string]int, len(oldLines)) + for _, l := range oldLines { + oldSet[l]++ + } + var all []BriefPinDiffLine + firstAdded := -1 + for _, l := range newLines { + if oldSet[l] > 0 { + oldSet[l]-- + all = append(all, BriefPinDiffLine{Sign: "", Text: l}) + } else { + if firstAdded < 0 { + firstAdded = len(all) + } + all = append(all, BriefPinDiffLine{Sign: "+", Text: l, Added: true}) + } + } + if firstAdded < 0 || len(all) <= 8 { + return all + } + start := max(0, firstAdded-4) + end := min(len(all), firstAdded+4) + return all[start:end] +} + +func splitBriefDiffLines(data []byte) []string { + s := strings.TrimRight(string(data), "\r\n") + if s == "" { + return nil + } + raw := strings.Split(s, "\n") + for i := range raw { + raw[i] = strings.TrimRight(raw[i], "\r") + } + return raw +} + +// pinReferenceImageCmd copies an attached reference image to art/reference/ and adds it to brief.yaml +// in one atomic, undoable Editor.History step. +type pinReferenceImageCmd struct { + ed *Editor + rootDir string + label string + imageID string + relPath string + absImagePath string + imageBytes []byte + fileExisted bool + artDirAbs string + artDirExisted bool + refDirAbs string + refDirExisted bool + briefAbs string + briefExisted bool + beforeBrief []byte + afterBrief []byte + notice BriefPinNotice +} + +func (c *pinReferenceImageCmd) Label() string { return c.label } +func (c *pinReferenceImageCmd) Do() { c.ed.report(c.do()) } +func (c *pinReferenceImageCmd) Undo() { c.ed.report(c.undo()) } + +func (c *pinReferenceImageCmd) do() error { + // Re-verify symlink containment on every Do/Redo to guard against TOCTOU symlink swaps. + if err := verifyAssetGenWritePath(c.rootDir, c.absImagePath, c.relPath); err != nil { + return err + } + if err := verifyAssetGenWritePath(c.rootDir, c.briefAbs, project.BriefFileName); err != nil { + return err + } + if !c.fileExisted { + if err := os.MkdirAll(filepath.Dir(c.absImagePath), 0o755); err != nil { + return fmt.Errorf("editor: create %s: %w", agentRefFolderRel, err) + } + if err := verifyAssetGenWritePath(c.rootDir, c.absImagePath, c.relPath); err != nil { + return err + } + if err := writeFileAtomic(c.absImagePath, c.imageBytes); err != nil { + return fmt.Errorf("editor: write %s: %w", c.relPath, err) + } + } + if err := writeFileAtomic(c.briefAbs, c.afterBrief); err != nil { + // Roll back the image file we just created if brief.yaml write fails. + if !c.fileExisted { + _ = os.Remove(c.absImagePath) + c.cleanupEmptyRefDirs() + } + return fmt.Errorf("editor: write brief.yaml: %w", err) + } + c.setAttachmentPinned(true, c.relPath) + noticeCopy := c.notice + noticeCopy.Diff = slices.Clone(c.notice.Diff) + c.ed.agent.lastPinNotice = ¬iceCopy + c.ed.agent.lastPinCmd = c + c.ed.Status = fmt.Sprintf("Pinned %s to brief.yaml", c.notice.Name) + c.refreshProjectAfterPin() + return nil +} + +func (c *pinReferenceImageCmd) undo() error { + // Re-verify symlink containment before restoring or removing files on Undo. + if err := verifyAssetGenWritePath(c.rootDir, c.briefAbs, project.BriefFileName); err != nil { + return err + } + if !c.fileExisted { + if err := verifyAssetGenWritePath(c.rootDir, c.absImagePath, c.relPath); err != nil { + return err + } + } + if c.briefExisted { + if err := writeFileAtomic(c.briefAbs, c.beforeBrief); err != nil { + return fmt.Errorf("editor: restore brief.yaml: %w", err) + } + } else { + if err := os.Remove(c.briefAbs); err != nil && !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("editor: remove brief.yaml: %w", err) + } + } + if !c.fileExisted { + if err := os.Remove(c.absImagePath); err != nil && !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("editor: remove %s: %w", c.relPath, err) + } + c.cleanupEmptyRefDirs() + } + c.setAttachmentPinned(false, "") + if c.ed.agent.lastPinCmd == c { + c.ed.agent.lastPinNotice = nil + c.ed.agent.lastPinCmd = nil + } + c.ed.Status = fmt.Sprintf("Undid pin of %s", c.notice.Name) + c.refreshProjectAfterPin() + return nil +} + +func (c *pinReferenceImageCmd) setAttachmentPinned(pinned bool, relPath string) { + for i := range c.ed.agent.attachedImages { + if c.ed.agent.attachedImages[i].ID == c.imageID { + c.ed.agent.attachedImages[i].Pinned = pinned + c.ed.agent.attachedImages[i].Path = relPath + break + } + } +} + +func (c *pinReferenceImageCmd) cleanupEmptyRefDirs() { + removeIfSafeEmptyDir := func(absDir, rel string) { + if err := verifyAssetGenWritePath(c.rootDir, absDir, rel); err != nil { + return + } + if fi, err := os.Lstat(absDir); err != nil || !fi.IsDir() || fi.Mode()&os.ModeSymlink != 0 { + return + } + _ = os.Remove(absDir) // succeeds only if empty + } + if !c.refDirExisted { + removeIfSafeEmptyDir(c.refDirAbs, agentRefFolderRel) + } + if !c.artDirExisted { + removeIfSafeEmptyDir(c.artDirAbs, "art") + } +} + +func (c *pinReferenceImageCmd) refreshProjectAfterPin() { + c.ed.invalidateBriefReferenceCaches() + c.ed.reloadBriefFromDisk() + c.ed.filesRev++ + c.ed.assetsRev++ + c.ed.invalidateProjectIndex() + if c.ed.ChangesOpen() { + _ = c.ed.RefreshChanges() + } else { + c.ed.RefreshChangesCount() + } + c.ed.CheckProblems() + c.ed.notify() +} + +// collectRequestReferenceImages snapshots the one-shot attached images and the pinned brief.yaml images +// for an outgoing AgentRequest, deduplicating by project-relative path so an image pinned during the +// current composer draft is never sent twice. +func (e *Editor) collectRequestReferenceImages() (attached, brief, combined []AgentReferenceImage) { + brief = e.BriefReferenceImages() + briefByPath := make(map[string]bool, len(brief)) + for _, img := range brief { + if img.Path != "" { + briefByPath[img.Path] = true + } + } + for _, img := range e.agent.attachedImages { + cp := img.clone() + // If the user pinned this chip before clicking Send, it already joins through brief.yaml. + if cp.Pinned && cp.Path != "" && briefByPath[cp.Path] { + continue + } + attached = append(attached, cp) + } + combined = make([]AgentReferenceImage, 0, len(attached)+len(brief)) + combined = append(combined, attached...) + combined = append(combined, brief...) + return attached, brief, combined +} diff --git a/packages/game/editor/agent_references_test.go b/packages/game/editor/agent_references_test.go new file mode 100644 index 000000000..04211c06f --- /dev/null +++ b/packages/game/editor/agent_references_test.go @@ -0,0 +1,847 @@ +package editor_test + +import ( + "bytes" + "context" + "image" + "image/color" + "image/gif" + "image/jpeg" + "image/png" + "net/url" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/project" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +// minimalValidWebP is a valid 1x1 lossless VP8L WebP image. +var minimalValidWebP = []byte{ + 0x52, 0x49, 0x46, 0x46, 0x1a, 0x00, 0x00, 0x00, + 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38, 0x4c, + 0x0d, 0x00, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x00, + 0x10, 0x07, 0x10, 0x11, 0x11, 0x88, 0x88, 0xfe, + 0x07, 0x00, +} + +func makeSpikesPNG(t *testing.T, w, h int) []byte { + t.Helper() + img := image.NewRGBA(image.Rect(0, 0, w, h)) + bg := color.RGBA{0x2A, 0x25, 0x20, 0xFF} + spike := color.RGBA{0xA2, 0x6B, 0x45, 0xFF} + hi := color.RGBA{0xD6, 0x9C, 0x6A, 0xFF} + for y := range h { + for x := range w { + img.SetRGBA(x, y, bg) + } + } + // Draw three triangular spikes along the bottom edge. + for s := range 3 { + cx := (s*2 + 1) * w / 6 + for y := h / 3; y < h; y++ { + half := (y - h/3) * (w / 8) / max(1, h-h/3) + for x := cx - half; x <= cx+half; x++ { + if x >= 0 && x < w { + if x == cx-half { + img.SetRGBA(x, y, hi) + } else { + img.SetRGBA(x, y, spike) + } + } + } + } + } + var buf bytes.Buffer + if err := png.Encode(&buf, img); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func makeSampleJPEG(t *testing.T, w, h int) []byte { + t.Helper() + img := image.NewRGBA(image.Rect(0, 0, w, h)) + for y := range h { + for x := range w { + img.SetRGBA(x, y, color.RGBA{0x4F, 0x8C, 0xFF, 0xFF}) + } + } + var buf bytes.Buffer + if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 85}); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func makeSampleGIF(t *testing.T) []byte { + t.Helper() + pal := color.Palette{color.RGBA{0x10, 0x12, 0x16, 0xFF}, color.RGBA{0xFF, 0x6B, 0x6B, 0xFF}} + img := image.NewPaletted(image.Rect(0, 0, 4, 4), pal) + var buf bytes.Buffer + if err := gif.Encode(&buf, img, nil); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func refFileURL(p string) string { + return (&url.URL{Scheme: "file", Path: filepath.ToSlash(p)}).String() +} + +func newRefProjectEditor(t *testing.T, withGit bool, initialBrief string) (*editor.Editor, string) { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, project.NSGoFileName), []byte("name: dungeon-run\nid: dev.example.dungeon\nversion: 0.1.0\n"), 0o644); err != nil { + t.Fatal(err) + } + gameYAML := "version: 1\nname: dungeon-run\nid: dev.example.dungeon\nappVersion: 0.1.0\nwindow:\n width: 640\n height: 360\n" + if err := os.WriteFile(filepath.Join(dir, "game.yaml"), []byte(gameYAML), 0o644); err != nil { + t.Fatal(err) + } + if initialBrief != "" { + if err := os.WriteFile(filepath.Join(dir, "brief.yaml"), []byte(initialBrief), 0o644); err != nil { + t.Fatal(err) + } + } + if withGit { + gitRun := func(args ...string) { + cmd := exec.Command("git", args...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), + "GIT_AUTHOR_NAME=Test", + "GIT_AUTHOR_EMAIL=test@example.com", + "GIT_COMMITTER_NAME=Test", + "GIT_COMMITTER_EMAIL=test@example.com", + ) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + } + gitRun("init", "-b", "main") + gitRun("add", ".") + gitRun("commit", "-m", "initial") + } + + ed := newTestEditor(t) + if err := ed.OpenProject(dir); err != nil { + t.Fatalf("OpenProject: %v", err) + } + ed.SetRightRailTab(editor.RightTabAgent) + ed.NotifyAgentMCPConnected(editor.AgentClientInfo{ + ID: "c1", + Name: "claude-code", + Transport: "stdio", + }) + return ed, dir +} + +// TestAgentDropPNGSentOnceNextRequestDoesNotCarryIt verifies Acceptance Criterion #1: +// dropping a PNG onto the composer attaches it as a chip whose hover shows it, the scripted +// agent receives it once on send, and the next request does not carry it. +func TestAgentDropPNGSentOnceNextRequestDoesNotCarryIt(t *testing.T) { + ed, _ := newRefProjectEditor(t, false, "") + pngBytes := makeSpikesPNG(t, 48, 36) + dropFile := filepath.Join(t.TempDir(), "spikes_ref.png") + if err := os.WriteFile(dropFile, pngBytes, 0o644); err != nil { + t.Fatal(err) + } + + reqs := make(chan editor.AgentRequest, 4) + ed.AgentRunner = editor.AgentRunnerFunc(func(_ context.Context, req editor.AgentRequest, emit func(editor.AgentEvent)) error { + reqs <- req + emit(editor.AgentEvent{Kind: editor.AgentEventMessage, Text: "Got it."}) + 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)) + + // Drag-over shows "Drop to attach". + ed.SetAgentComposerDragOver(true) + app.Settle() + if !app.Exists("id:agent-composer-drop-zone") { + t.Fatal("Drop to attach overlay did not appear") + } + if got := agentViewText(t, app, "id:agent-composer-drop-title"); got != "Drop to attach" { + t.Fatalf("drop title = %q, want %q", got, "Drop to attach") + } + + // Drop the PNG onto the composer -> becomes a chip whose hover shows the image. + app.DropFiles("id:agent-composer", refFileURL(dropFile)) + app.Settle() + if ed.AgentComposerDragOver() { + t.Fatal("drag-over overlay stayed active after drop") + } + if !app.Exists("id:agent-image-chip-0") { + t.Fatal("attached image chip did not appear after dropping PNG") + } + if got := agentViewText(t, app, "id:agent-image-name-0"); got != "spikes_ref.png" { + t.Fatalf("chip filename = %q, want spikes_ref.png", got) + } + + // Hovering the chip opens the preview showing the image and its dimensions. + app.Hover("id:agent-image-chip-0") + app.Settle() + if !app.Exists("id:agent-image-preview-popover") || !app.Exists("id:agent-image-preview-img") { + t.Fatal("hovering attached image chip did not show image preview popover") + } + if dims := agentViewText(t, app, "id:agent-image-preview-dims"); dims != "PNG · 48 × 36" { + t.Fatalf("preview dims = %q, want %q", dims, "PNG · 48 × 36") + } + app.HoverOut() + app.Settle() + + // First request carries the dropped PNG once. + ed.SetAgentComposerText("Make the spikes look like this.") + app.Settle() + app.Press("id:agent-composer-send") + app.Settle() + + req1 := <-reqs + if len(req1.AttachedImages) != 1 || len(req1.Images) != 1 { + t.Fatalf("req1 images = (%d attached, %d total), want (1, 1)", len(req1.AttachedImages), len(req1.Images)) + } + img1 := req1.Images[0] + if img1.Name != "spikes_ref.png" || img1.Format != editor.AgentImagePNG || img1.Width != 48 || img1.Height != 36 || img1.FromBrief || img1.Pinned { + t.Fatalf("unexpected req1 image metadata: %+v", img1) + } + if !bytes.Equal(img1.Data, pngBytes) { + t.Fatal("req1 image bytes did not match dropped PNG") + } + + app.WaitUntil(5*time.Second, func() bool { + return ed.AgentStatus() == editor.AgentStatusConnected && app.Exists("id:agent-turn-images-0") + }) + + // Chip was cleared after sending so the next request does NOT carry it. + if len(ed.AgentAttachedImages()) != 0 { + t.Fatalf("attached images after send = %d, want 0", len(ed.AgentAttachedImages())) + } + if app.Exists("id:agent-image-chip-0") { + t.Fatal("one-shot image chip remained after sending request") + } + + // Second request receives NO image. + if err := ed.SubmitAgentPrompt("Now add a torch on the wall."); err != nil { + t.Fatalf("second SubmitAgentPrompt: %v", err) + } + req2 := <-reqs + if len(req2.AttachedImages) != 0 || len(req2.BriefImages) != 0 || len(req2.Images) != 0 { + t.Fatalf("second request unexpectedly carried images: attached=%d brief=%d total=%d", len(req2.AttachedImages), len(req2.BriefImages), len(req2.Images)) + } + app.WaitUntil(5*time.Second, func() bool { + return ed.AgentStatus() == editor.AgentStatusConnected && len(ed.AgentTurns()) == 2 + }) +} + +// TestAgentPasteAndDropFormatsAndUnsupportedRefusal verifies PNG, JPEG, and WebP via paste and drop, +// and verifies that unsupported formats (GIF, SVG, TXT, corrupt PNG) are refused with the reason. +func TestAgentPasteAndDropFormatsAndUnsupportedRefusal(t *testing.T) { + ed, _ := newRefProjectEditor(t, false, "") + tmp := t.TempDir() + + pngBytes := makeSpikesPNG(t, 24, 24) + jpegBytes := makeSampleJPEG(t, 32, 20) + webpBytes := minimalValidWebP + + jpegFile := filepath.Join(tmp, "wall_ref.jpg") + webpFile := filepath.Join(tmp, "door_ref.webp") + gifFile := filepath.Join(tmp, "anim.gif") + txtFile := filepath.Join(tmp, "notes.txt") + svgFile := filepath.Join(tmp, "icon.svg") + badPNGFile := filepath.Join(tmp, "corrupt.png") + + for p, b := range map[string][]byte{ + jpegFile: jpegBytes, + webpFile: webpBytes, + gifFile: makeSampleGIF(t), + txtFile: []byte("hello world"), + svgFile: []byte(``), + badPNGFile: []byte("this is not actually a png"), + } { + if err := os.WriteFile(p, b, 0o644); err != nil { + t.Fatal(err) + } + } + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900)) + + // 1. Paste a PNG via core.PasteEvent into the composer input. + app.Paste("id:agent-composer-input", core.PasteEvent{ + Files: []core.PastedFile{{Name: "pasted_ref.png", MIME: "image/png", Data: pngBytes}}, + }) + app.Settle() + + // 2. Drop JPEG and WebP files onto the composer. + app.DropFiles("id:agent-composer", refFileURL(jpegFile), refFileURL(webpFile)) + app.Settle() + + imgs := ed.AgentAttachedImages() + if len(imgs) != 3 { + t.Fatalf("attached images = %d, want 3 (PNG, JPEG, WebP)", len(imgs)) + } + if imgs[0].Format != editor.AgentImagePNG || imgs[1].Format != editor.AgentImageJPEG || imgs[2].Format != editor.AgentImageWebP { + t.Fatalf("formats = [%s, %s, %s], want [png, jpeg, webp]", imgs[0].Format, imgs[1].Format, imgs[2].Format) + } + + // Remove the middle chip via its × button. + app.Press("id:agent-image-remove-1") + app.Settle() + if len(ed.AgentAttachedImages()) != 2 { + t.Fatalf("after remove attached images = %d, want 2", len(ed.AgentAttachedImages())) + } + + // 3. Unsupported formats must be refused with clear reasons and leave attached chips untouched. + for _, tc := range []struct { + name string + file string + wantText string + }{ + {"GIF", gifFile, "only PNG, JPEG, or WebP"}, + {"TXT", txtFile, ".txt"}, + {"SVG", svgFile, ".svg"}, + {"corrupt PNG", badPNGFile, "only PNG, JPEG, or WebP"}, + } { + app.DropFiles("id:agent-composer", refFileURL(tc.file)) + app.Settle() + if !app.Exists("id:agent-attach-error") { + t.Fatalf("%s: refusal banner did not appear", tc.name) + } + gotErr := agentViewText(t, app, "id:agent-attach-error-text") + if !strings.Contains(gotErr, tc.wantText) { + t.Fatalf("%s: error = %q, want substring %q", tc.name, gotErr, tc.wantText) + } + if len(ed.AgentAttachedImages()) != 2 { + t.Fatalf("%s: attached count changed to %d", tc.name, len(ed.AgentAttachedImages())) + } + } + + // Dismissing error banner clears it. + app.Press("id:agent-attach-error-dismiss") + app.Settle() + if app.Exists("id:agent-attach-error") { + t.Fatal("error banner stayed visible after dismiss") + } + + // 4. Pasting an SVG via PasteEvent is also refused with "SVG". + app.Paste("id:agent-composer-input", core.PasteEvent{ + Files: []core.PastedFile{{Name: "vector.svg", MIME: "image/svg+xml", Data: []byte(``)}}, + }) + app.Settle() + if gotErr := ed.AgentAttachError(); !strings.Contains(gotErr, "SVG") || !strings.Contains(gotErr, "only PNG, JPEG, or WebP") { + t.Fatalf("pasted SVG error = %q", gotErr) + } + + // 5. Clipboard hook paste attaches a PNG cleanly. + ed.ReadClipboardImage = func(done func(core.ClipboardImage, bool, error)) { + done(core.ClipboardImage{PNG: pngBytes}, true, nil) + } + pasted, ok, err := ed.PasteAgentReferenceImage() + if err != nil || !ok || len(pasted) != 1 || pasted[0].Format != editor.AgentImagePNG { + t.Fatalf("PasteAgentReferenceImage = (%v, %v, %v)", pasted, ok, err) + } +} + +// TestAgentPinToBriefWritesFileAndYAMLCarriesNextRequestAndUndoRemovesBoth verifies Acceptance Criterion #2: +// Pin to brief writes art/reference/ and one YAML line in brief.yaml, shows in Review/Changes, +// carries the image in every subsequent request through the Always chip, and Undo removes both. +func TestAgentPinToBriefWritesFileAndYAMLCarriesNextRequestAndUndoRemovesBoth(t *testing.T) { + initialBrief := "art:\n direction: chunky pixel art, 16 px tiles\n references:\n - path: art/reference/torch_ref.png\n" + ed, projDir := newRefProjectEditor(t, true, initialBrief) + + // Write existing torch_ref.png so brief.yaml has 1 valid prior reference. + if err := os.MkdirAll(filepath.Join(projDir, "art", "reference"), 0o755); err != nil { + t.Fatal(err) + } + torchBytes := makeSpikesPNG(t, 16, 16) + if err := os.WriteFile(filepath.Join(projDir, "art", "reference", "torch_ref.png"), torchBytes, 0o644); err != nil { + t.Fatal(err) + } + + spikesBytes := makeSpikesPNG(t, 48, 32) + dropFile := filepath.Join(t.TempDir(), "spikes_ref.png") + if err := os.WriteFile(dropFile, spikesBytes, 0o644); err != nil { + t.Fatal(err) + } + + reqs := make(chan editor.AgentRequest, 4) + ed.AgentRunner = editor.AgentRunnerFunc(func(_ context.Context, req editor.AgentRequest, emit func(editor.AgentEvent)) error { + reqs <- req + emit(editor.AgentEvent{Kind: editor.AgentEventMessage, Text: "Applied style from brief."}) + 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)) + + // Always chip initially shows brief.yaml · 1 ref. + if got := agentViewText(t, app, "id:agent-always-brief-text"); got != "brief.yaml · 1 ref" { + t.Fatalf("initial Always chip = %q, want %q", got, "brief.yaml · 1 ref") + } + + // Drop spikes_ref.png onto composer, then press "Pin to brief". + app.DropFiles("id:agent-composer", refFileURL(dropFile)) + app.Settle() + if got := agentViewText(t, app, "id:agent-image-pin-text-0"); got != "Pin to brief" { + t.Fatalf("pin button before click = %q, want Pin to brief", got) + } + + app.Press("id:agent-image-pin-0") + app.Settle() + + // 1. Verify art/reference/spikes_ref.png was written with exact bytes. + pinnedAbs := filepath.Join(projDir, "art", "reference", "spikes_ref.png") + gotImgBytes, err := os.ReadFile(pinnedAbs) + if err != nil { + t.Fatalf("pinned file missing: %v", err) + } + if !bytes.Equal(gotImgBytes, spikesBytes) { + t.Fatal("art/reference/spikes_ref.png bytes do not match source PNG") + } + + // 2. Verify brief.yaml has exactly one added line for spikes_ref.png and preserved existing keys. + gotBriefBytes, err := os.ReadFile(filepath.Join(projDir, "brief.yaml")) + if err != nil { + t.Fatalf("read brief.yaml: %v", err) + } + gotBrief := string(gotBriefBytes) + if !strings.Contains(gotBrief, "direction: chunky pixel art, 16 px tiles") { + t.Fatalf("brief.yaml lost existing direction field:\n%s", gotBrief) + } + if !strings.Contains(gotBrief, "- path: art/reference/spikes_ref.png") { + t.Fatalf("brief.yaml missing pinned reference line:\n%s", gotBrief) + } + oldLines := strings.Split(strings.TrimRight(initialBrief, "\n"), "\n") + newLines := strings.Split(strings.TrimRight(gotBrief, "\n"), "\n") + if len(newLines)-len(oldLines) != 1 { + t.Fatalf("expected exactly 1 YAML line added to brief.yaml, got +%d lines:\n%s", len(newLines)-len(oldLines), gotBrief) + } + + // 3. UI reflects pinned state, confirmation card with Undo, and Always chip shows 2 refs. + if got := agentViewText(t, app, "id:agent-image-pin-text-0"); got != "Pinned" { + t.Fatalf("pin button after click = %q, want Pinned", got) + } + if !app.Exists("id:agent-pin-notice-card") || !app.Exists("id:agent-pin-notice-undo") { + t.Fatal("Pin to brief confirmation card or Undo button did not appear") + } + if got := agentViewText(t, app, "id:agent-always-brief-text"); got != "brief.yaml · 2 refs" { + t.Fatalf("Always chip after pin = %q, want %q", got, "brief.yaml · 2 refs") + } + + // Hovering the Always chip previews the pinned brief references. + app.Hover("id:agent-always-brief") + app.Settle() + if !app.Exists("id:agent-brief-ref-row-1") { + t.Fatal("hovering brief.yaml Always chip did not list both pinned references") + } + app.HoverOut() + app.Settle() + + // 4. Both art/reference/spikes_ref.png and brief.yaml show up in Review / Changes like any change. + if err := ed.OpenChangesPanel(); err != nil { + t.Fatalf("OpenChangesPanel: %v", err) + } + sess := ed.ChangesSession() + if sess == nil { + t.Fatal("ChangesSession returned nil") + } + var sawBrief, sawSpikes bool + for _, f := range sess.Files { + if f.ProjectPath == "brief.yaml" { + sawBrief = true + } + if f.ProjectPath == "art/reference/spikes_ref.png" { + sawSpikes = true + } + } + ed.CloseChangesPanel() + app.Settle() + if !sawBrief || !sawSpikes { + t.Fatalf("Changes/Review missing pinned files (brief=%v, spikes=%v): %+v", sawBrief, sawSpikes, sess.Files) + } + + // 5. Clear one-shot chips and send a brand-new request -> agent receives spikes_ref.png via brief.yaml! + ed.ClearAgentAttachedImages() + if err := ed.SubmitAgentPrompt("Build floor 2 traps matching our brief."); err != nil { + t.Fatalf("SubmitAgentPrompt: %v", err) + } + reqPinned := <-reqs + if len(reqPinned.AttachedImages) != 0 { + t.Fatalf("expected 0 one-shot attached images, got %d", len(reqPinned.AttachedImages)) + } + if len(reqPinned.BriefImages) != 2 || len(reqPinned.Images) != 2 { + t.Fatalf("expected 2 brief images on next request, got brief=%d total=%d", len(reqPinned.BriefImages), len(reqPinned.Images)) + } + if reqPinned.BriefImages[1].Path != "art/reference/spikes_ref.png" || !reqPinned.BriefImages[1].Pinned || !reqPinned.BriefImages[1].FromBrief { + t.Fatalf("unexpected brief image entry: %+v", reqPinned.BriefImages[1]) + } + if !bytes.Equal(reqPinned.BriefImages[1].Data, spikesBytes) { + t.Fatal("brief image bytes did not match pinned spikes_ref.png") + } + app.WaitUntil(5*time.Second, func() bool { + return ed.AgentStatus() == editor.AgentStatusConnected + }) + + // 6. Undo removes BOTH art/reference/spikes_ref.png and the YAML line from brief.yaml. + app.Press("id:agent-pin-notice-undo") + app.Settle() + + if _, err := os.Stat(pinnedAbs); !os.IsNotExist(err) { + t.Fatalf("after Undo art/reference/spikes_ref.png still exists (err=%v)", err) + } + restoredBrief, err := os.ReadFile(filepath.Join(projDir, "brief.yaml")) + if err != nil { + t.Fatalf("read brief.yaml after Undo: %v", err) + } + if string(restoredBrief) != initialBrief { + t.Fatalf("brief.yaml after Undo =\n%q\nwant:\n%q", string(restoredBrief), initialBrief) + } + if app.Exists("id:agent-pin-notice-card") { + t.Fatal("pin confirmation card stayed visible after Undo") + } + if got := agentViewText(t, app, "id:agent-always-brief-text"); got != "brief.yaml · 1 ref" { + t.Fatalf("Always chip after Undo = %q, want %q", got, "brief.yaml · 1 ref") + } + + // Subsequent request no longer carries spikes_ref.png. + if err := ed.SubmitAgentPrompt("Check the floor."); err != nil { + t.Fatalf("SubmitAgentPrompt after undo: %v", err) + } + reqAfterUndo := <-reqs + if len(reqAfterUndo.BriefImages) != 1 || reqAfterUndo.BriefImages[0].Path != "art/reference/torch_ref.png" { + t.Fatalf("after Undo brief images = %+v, want only torch_ref.png", reqAfterUndo.BriefImages) + } + app.WaitUntil(5*time.Second, func() bool { + return ed.AgentStatus() == editor.AgentStatusConnected + }) + + // 7. Redo cleanly restores both art/reference/spikes_ref.png and brief.yaml. + if !ed.Redo() { + t.Fatal("Redo returned false") + } + if _, err := os.Stat(pinnedAbs); err != nil { + t.Fatalf("after Redo art/reference/spikes_ref.png missing: %v", err) + } + if refs := ed.BriefReferences(); len(refs) != 2 || refs[1].Path != "art/reference/spikes_ref.png" { + t.Fatalf("after Redo BriefReferences = %+v", refs) + } +} + +// TestAgentPinCreatesAndUndoDeletesFreshBriefYAML verifies that in a project without brief.yaml, +// pinning creates art/reference/ and brief.yaml, and Undo removes both files cleanly. +func TestAgentPinCreatesAndUndoDeletesFreshBriefYAML(t *testing.T) { + ed, projDir := newRefProjectEditor(t, false, "") + pngBytes := makeSpikesPNG(t, 24, 24) + img, err := ed.AttachAgentReferenceBytes("boss_ref.png", pngBytes) + if err != nil { + t.Fatalf("AttachAgentReferenceBytes: %v", err) + } + notice, err := ed.PinAgentReferenceImage(img.ID, "") + if err != nil { + t.Fatalf("PinAgentReferenceImage: %v", err) + } + if notice.RelPath != "art/reference/boss_ref.png" { + t.Fatalf("notice.RelPath = %q", notice.RelPath) + } + briefPath := filepath.Join(projDir, "brief.yaml") + imgPath := filepath.Join(projDir, "art", "reference", "boss_ref.png") + if _, err := os.Stat(briefPath); err != nil { + t.Fatalf("brief.yaml not created: %v", err) + } + if _, err := os.Stat(imgPath); err != nil { + t.Fatalf("art/reference/boss_ref.png not created: %v", err) + } + + if !ed.Undo() { + t.Fatal("Undo failed") + } + if _, err := os.Stat(briefPath); !os.IsNotExist(err) { + t.Fatalf("brief.yaml still exists after Undo (err=%v)", err) + } + if _, err := os.Stat(imgPath); !os.IsNotExist(err) { + t.Fatalf("art/reference/boss_ref.png still exists after Undo (err=%v)", err) + } + if _, err := os.Stat(filepath.Join(projDir, "art", "reference")); !os.IsNotExist(err) { + t.Fatalf("empty art/reference dir was not cleaned up on Undo (err=%v)", err) + } +} + +func TestAgentReferenceImagesSpecLightDarkTokens(t *testing.T) { + ed, _ := newRefProjectEditor(t, false, "art:\n direction: pixel art\n") + pngBytes := makeSpikesPNG(t, 32, 24) + img, err := ed.AttachAgentReferenceBytes("spikes_ref.png", pngBytes) + if err != nil { + t.Fatal(err) + } + ed.SetAgentImagePreviewID(img.ID) + ed.SetAgentComposerDragOver(true) + + 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: false, + Locale: "en-US", + })) + + light := editor.LightSpecPalette() + dark := editor.DarkSpecPalette() + + if got := app.Find("id:agent-image-preview-popover").Style.Background; got != light.Raised { + t.Fatalf("light preview popover bg = %#x, want %#x", uint32(got), uint32(light.Raised)) + } + if got := app.Find("id:agent-composer-drop-zone").Style.Background; got != light.Accent.Fill { + t.Fatalf("light drop zone bg = %#x, want %#x", uint32(got), uint32(light.Accent.Fill)) + } + if got := app.Find("id:agent-image-chip-0").Style.Background; got != light.LineRaised { + t.Fatalf("light chip bg = %#x, want %#x", uint32(got), uint32(light.LineRaised)) + } + + app.SetEnvironment(core.Environment{ + OS: core.OSMacOS, + Idiom: core.IdiomDesktop, + Dark: true, + Locale: "en-US", + }) + if got := app.Find("id:agent-image-preview-popover").Style.Background; got != dark.Raised { + t.Fatalf("dark preview popover bg = %#x, want %#x", uint32(got), uint32(dark.Raised)) + } + if got := app.Find("id:agent-composer-drop-zone").Style.Background; got != dark.Accent.Fill { + t.Fatalf("dark drop zone bg = %#x, want %#x", uint32(got), uint32(dark.Accent.Fill)) + } + if got := app.Find("id:agent-image-chip-0").Style.Background; got != dark.LineRaised { + t.Fatalf("dark chip bg = %#x, want %#x", uint32(got), uint32(dark.LineRaised)) + } +} + +func TestAgentPinBriefInteropWithSettingsBrief(t *testing.T) { + ed, projDir := newRefProjectEditor(t, false, "") + pngBytes := makeSpikesPNG(t, 24, 24) + img, err := ed.AttachAgentReferenceBytes("spikes_ref.png", pngBytes) + if err != nil { + t.Fatal(err) + } + if _, err := ed.PinAgentReferenceImage(img.ID, "rusty iron spikes\ninjection"); err != nil { + t.Fatalf("PinAgentReferenceImage: %v", err) + } + + // Fresh brief.yaml must be valid versioned YAML parseable by project.ParseBrief. + briefPath := filepath.Join(projDir, project.BriefFileName) + raw, err := os.ReadFile(briefPath) + if err != nil { + t.Fatal(err) + } + parsed, err := project.ParseBrief(raw) + if err != nil { + t.Fatalf("project.ParseBrief failed on pinned brief.yaml:\n%s\nerr: %v", raw, err) + } + if parsed.Art == nil || len(parsed.Art.References) != 1 || parsed.Art.References[0].Path != "art/reference/spikes_ref.png" { + t.Fatalf("unexpected parsed brief art: %+v", parsed.Art) + } + if strings.Contains(parsed.Art.References[0].Note, "\n") { + t.Fatalf("control char/newline leaked into brief note: %q", parsed.Art.References[0].Note) + } + + // Editor's Settings > Game brief state must have reloaded automatically. + if !ed.BriefExists() || ed.BriefLoadErr() != nil { + t.Fatalf("BriefExists=%v BriefLoadErr=%v after pin", ed.BriefExists(), ed.BriefLoadErr()) + } + // Editing pitch in Settings > Game brief must preserve pinned art.references. + if err := ed.EditBrief("Set pitch", func(b *project.Brief) { + b.Pitch = "A tight dungeon platformer." + }); err != nil { + t.Fatalf("EditBrief after pin: %v", err) + } + refs := ed.BriefReferences() + if len(refs) != 1 || refs[0].Path != "art/reference/spikes_ref.png" { + t.Fatalf("pinned reference lost after Settings EditBrief: %+v", refs) + } +} + +func TestAgentReferenceSymlinkAndTOCTOUGuards(t *testing.T) { + outside := t.TempDir() + outsidePNG := filepath.Join(outside, "secret.png") + outsideBrief := filepath.Join(outside, "outside_brief.yaml") + if err := os.WriteFile(outsidePNG, makeSpikesPNG(t, 16, 16), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(outsideBrief, []byte("version: 1\nart:\n references:\n - path: art/reference/escape.png\n"), 0o644); err != nil { + t.Fatal(err) + } + + // 1. Symlinked brief.yaml pointing outside project must be ignored & refused for writes. + ed1, projDir1 := newRefProjectEditor(t, false, "") + if err := os.Symlink(outsideBrief, filepath.Join(projDir1, "brief.yaml")); err != nil { + t.Skipf("symlink unavailable: %v", err) + } + if ed1.BriefFileExists() { + t.Fatal("BriefFileExists returned true for symlinked brief.yaml") + } + if refs := ed1.BriefReferences(); len(refs) != 0 { + t.Fatalf("BriefReferences read symlinked brief.yaml: %+v", refs) + } + img1, err := ed1.AttachAgentReferenceBytes("test.png", makeSpikesPNG(t, 16, 16)) + if err != nil { + t.Fatal(err) + } + if _, err := ed1.PinAgentReferenceImage(img1.ID, ""); err == nil { + t.Fatal("PinAgentReferenceImage succeeded against symlinked brief.yaml") + } + + // 2. Symlinked art/reference directory or image inside brief.yaml must be refused. + ed2, projDir2 := newRefProjectEditor(t, false, "version: 1\nart:\n references:\n - path: art/reference/escape.png\n") + if err := os.MkdirAll(filepath.Join(projDir2, "art", "reference"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outsidePNG, filepath.Join(projDir2, "art", "reference", "escape.png")); err != nil { + t.Fatal(err) + } + if imgs := ed2.BriefReferenceImages(); len(imgs) != 0 { + t.Fatalf("BriefReferenceImages loaded symlinked image: %+v", imgs) + } + + // 3. TOCTOU symlink swap before Undo must refuse to delete outside file. + ed3, projDir3 := newRefProjectEditor(t, false, "") + img3, err := ed3.AttachAgentReferenceBytes("safe.png", makeSpikesPNG(t, 16, 16)) + if err != nil { + t.Fatal(err) + } + if _, err := ed3.PinAgentReferenceImage(img3.ID, ""); err != nil { + t.Fatal(err) + } + pinnedPath := filepath.Join(projDir3, "art", "reference", "safe.png") + if err := os.Remove(pinnedPath); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outsidePNG, pinnedPath); err != nil { + t.Fatal(err) + } + if ed3.Undo() { + t.Fatal("Undo succeeded despite symlink swap on pinned image") + } + if _, err := os.Stat(outsidePNG); err != nil { + t.Fatalf("outside target was touched by Undo: %v", err) + } +} + +func TestAgentReferenceCapsAndInputSafety(t *testing.T) { + ed, _ := newRefProjectEditor(t, false, "") + pngBytes := makeSpikesPNG(t, 16, 16) + + // Remote URI schemes and non-localhost file:// URIs must be refused. + for _, bad := range []string{ + "https://example.com/ref.png", + "file://evil.example.com/share/ref.png", + t.TempDir(), // directory, not regular file + } { + if _, err := ed.AttachAgentReferenceFile(bad); err == nil { + t.Fatalf("AttachAgentReferenceFile(%q) unexpectedly succeeded", bad) + } + } + + // Enforce per-request attachment cap (8). + for i := range 8 { + if _, err := ed.AttachAgentReferenceBytes("ref.png", pngBytes); err != nil { + t.Fatalf("attach #%d failed: %v", i+1, err) + } + } + if _, err := ed.AttachAgentReferenceBytes("ninth.png", pngBytes); err == nil { + t.Fatal("expected 9th attachment to be refused by per-request cap") + } +} + +func TestAgentUndoLastBriefPinOnlyUndoesPinAtTopOfHistory(t *testing.T) { + ed, projDir := newRefProjectEditor(t, false, "version: 1\npitch: Initial\n") + img, err := ed.AttachAgentReferenceBytes("spikes_ref.png", makeSpikesPNG(t, 24, 24)) + if err != nil { + t.Fatal(err) + } + if _, err := ed.PinAgentReferenceImage(img.ID, ""); err != nil { + t.Fatal(err) + } + if !ed.CanUndoLastBriefPin() { + t.Fatal("CanUndoLastBriefPin should be true right after pinning") + } + + // Perform an unrelated edit on top of the pin. + if err := ed.EditBrief("Update pitch", func(b *project.Brief) { + b.Pitch = "Updated pitch" + }); err != nil { + t.Fatal(err) + } + if ed.CanUndoLastBriefPin() { + t.Fatal("CanUndoLastBriefPin should be false after another command pushed onto History") + } + if ed.UndoLastBriefPin() { + t.Fatal("UndoLastBriefPin must not undo an unrelated later command") + } + if got := ed.Brief().Pitch; got != "Updated pitch" { + t.Fatalf("unrelated edit was reverted: pitch = %q", got) + } + if _, err := os.Stat(filepath.Join(projDir, "art", "reference", "spikes_ref.png")); err != nil { + t.Fatalf("pinned file unexpectedly removed: %v", err) + } +} + +func TestAgentComposerFocusPreservedAcrossImageAttachAndPin(t *testing.T) { + ed, _ := newRefProjectEditor(t, false, "version: 1\npitch: Dungeon\n") + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900)) + + app.Focus("id:agent-composer-input") + app.Settle() + + var img editor.AgentReferenceImage + var attachErr error + app.Post(func() { + img, attachErr = ed.AttachAgentReferenceBytes("spikes_ref.png", makeSpikesPNG(t, 24, 24)) + }) + app.Settle() + if attachErr != nil { + t.Fatal(attachErr) + } + app.Key("a") + app.Settle() + if !strings.Contains(ed.AgentComposerText(), "a") { + t.Fatalf("attaching image stole focus from agent-composer-input (text=%q)", ed.AgentComposerText()) + } + + app.Post(func() { + ed.SetAgentImagePreviewID(img.ID) + }) + app.Settle() + app.Key("b") + app.Settle() + if !strings.Contains(ed.AgentComposerText(), "b") { + t.Fatalf("opening image preview stole focus from agent-composer-input (text=%q)", ed.AgentComposerText()) + } + + var pinErr error + app.Post(func() { + _, pinErr = ed.PinAgentReferenceImage(img.ID, "spikes") + }) + app.Settle() + if pinErr != nil { + t.Fatal(pinErr) + } + app.Key("c") + app.Settle() + if !strings.Contains(ed.AgentComposerText(), "c") { + t.Fatalf("pinning image stole focus from agent-composer-input (text=%q)", ed.AgentComposerText()) + } +} diff --git a/packages/game/editor/agent_references_ui.go b/packages/game/editor/agent_references_ui.go new file mode 100644 index 000000000..e8cfe70a1 --- /dev/null +++ b/packages/game/editor/agent_references_ui.go @@ -0,0 +1,970 @@ +package editor + +import ( + "fmt" + "strings" + + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/icons/lucide" + "github.com/nsgo-dev/nsgo/ui" +) + +type agentComposerRefKey struct { + sel string + scene string + attachedSig string + briefExists bool + briefSig string + dragOver bool + previewID string + attachErr string + pinNoticeSig string + canUndoPin bool + working bool + lang Language +} + +func buildAgentComposerRefKey(ed *Editor) agentComposerRefKey { + var sceneName string + if ed.Doc != nil { + sceneName = ed.Doc.Name + } + var ab strings.Builder + for _, img := range ed.agent.attachedImages { + fmt.Fprintf(&ab, "%s:%s:%v:%d|", img.ID, img.Path, img.Pinned, img.ImageVersion) + } + briefExists, briefRefs := ed.readBriefMeta() + var bb strings.Builder + for _, r := range briefRefs { + fmt.Fprintf(&bb, "%s:%s|", r.Path, r.Note) + } + var pinSig string + if n := ed.agent.lastPinNotice; n != nil { + pinSig = fmt.Sprintf("%s|%s|%d", n.ImageID, n.RelPath, len(n.Diff)) + } + return agentComposerRefKey{ + sel: ed.SelectedID, + scene: sceneName, + attachedSig: ab.String(), + briefExists: briefExists, + briefSig: bb.String(), + dragOver: ed.agent.composerDragOver, + previewID: ed.agent.previewImageID, + attachErr: ed.agent.attachErr, + pinNoticeSig: pinSig, + canUndoPin: ed.CanUndoLastBriefPin(), + working: ed.AgentWorking(), + lang: ed.Language(), + } +} + +// agentImagePreviewPopover renders the floating preview card above the composer when the user +// hovers or focuses an attached image chip or the brief.yaml Always chip. +func agentImagePreviewPopover(ed *Editor, p SpecPalette) core.Node { + previewID := ed.AgentImagePreviewID() + if previewID == "" { + return nil + } + if previewID == AgentBriefPreviewID { + return agentBriefPreviewPopover(ed, p) + } + var target *AgentReferenceImage + for i := range ed.agent.attachedImages { + if ed.agent.attachedImages[i].ID == previewID { + cp := ed.agent.attachedImages[i] + target = &cp + break + } + } + if target == nil { + return nil + } + + scopeText := ed.T("agent.ref.sentOnce") + scopeCol := p.TextFaint + if target.Pinned && target.Path != "" { + scopeText = fmt.Sprintf("%s · %s", ed.T("agent.ref.pinned"), target.Path) + scopeCol = p.Added.Fg + } + dimsText := fmt.Sprintf("%s · %d × %d", target.Format.Label(), target.Width, target.Height) + + children := []core.Node{ + core.View{ + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifySpaceBetween, + Gap: 8, + }, + Children: []core.Node{ + core.Text{ + TestID: "agent-image-preview-title", + Content: target.Name, + Style: core.Style{ + FlexGrow: 1, + FlexShrink: 1, + MinWidth: core.Pt(0), + FontSize: 13, + FontWeight: 600, + Color: p.TextPrimary, + }, + }, + core.Text{ + TestID: "agent-image-preview-dims", + Content: dimsText, + Style: core.Style{ + FontSize: 11.5, + FontFamily: core.FontMonospace, + Color: p.TextFaint, + FlexShrink: 0, + }, + }, + }, + }, + core.View{ + Style: core.Style{ + Height: core.Pt(164), + CornerRadius: 8, + Background: p.Inset, + BorderWidth: 1, + BorderColor: p.LineRaised, + Overflow: core.Hidden, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Padding: core.All(4), + }, + Children: []core.Node{ + core.Image{ + TestID: "agent-image-preview-img", + Source: core.ImageSource{Pixels: target.Pixels, Version: target.ImageVersion}, + ResizeMode: core.Contain, + Label: target.Name, + Style: core.Style{ + Width: core.Pct(100), + Height: core.Pct(100), + }, + }, + }, + }, + core.Text{ + TestID: "agent-image-preview-scope", + Content: scopeText, + Style: core.Style{ + FontSize: 11.5, + Color: scopeCol, + }, + }, + } + + return core.View{ + TestID: "agent-image-preview-popover", + Style: core.Style{ + CornerRadius: 12, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + Padding: core.All(12), + Gap: 8, + }, + Children: children, + } +} + +func agentBriefPreviewPopover(ed *Editor, p SpecPalette) core.Node { + imgs := ed.BriefReferenceImages() + children := []core.Node{ + core.View{ + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifySpaceBetween, + Gap: 8, + }, + Children: []core.Node{ + core.Text{ + TestID: "agent-image-preview-title", + Content: ed.T("agent.ref.briefPreviewTitle"), + Style: core.Style{ + FontSize: 13, + FontWeight: 600, + Color: p.TextPrimary, + }, + }, + core.Text{ + Content: "brief.yaml", + Style: core.Style{ + FontSize: 11.5, + FontFamily: core.FontMonospace, + Color: p.TextFaint, + }, + }, + }, + }, + } + if len(imgs) == 0 { + children = append(children, core.Text{ + Content: ed.T("agent.ref.briefEmpty"), + Style: core.Style{ + FontSize: 11.5, + Color: p.TextMuted, + }, + }) + } else { + for idx, img := range imgs { + meta := fmt.Sprintf("%s · %d × %d", img.Format.Label(), img.Width, img.Height) + if img.Note != "" { + meta = img.Note + " · " + meta + } + children = append(children, core.View{ + TestID: fmt.Sprintf("agent-brief-ref-row-%d", idx), + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(44), + Height: core.Pt(32), + CornerRadius: 6, + Background: p.Inset, + BorderWidth: 1, + BorderColor: p.LineRaised, + Overflow: core.Hidden, + FlexShrink: 0, + }, + Children: []core.Node{ + core.Image{ + Source: core.ImageSource{Pixels: img.Pixels, Version: img.ImageVersion}, + ResizeMode: core.Contain, + Label: img.Name, + Style: core.Style{ + Width: core.Pct(100), + Height: core.Pct(100), + }, + }, + }, + }, + core.View{ + Style: core.Style{ + FlexGrow: 1, + FlexShrink: 1, + MinWidth: core.Pt(0), + Gap: 2, + }, + Children: []core.Node{ + core.Text{ + Content: img.Path, + Style: core.Style{ + FontSize: 11.5, + FontFamily: core.FontMonospace, + Color: p.TextSecondary, + }, + }, + core.Text{ + Content: meta, + Style: core.Style{ + FontSize: 11, + Color: p.TextFaint, + }, + }, + }, + }, + }, + }) + } + } + return core.View{ + TestID: "agent-image-preview-popover", + Style: core.Style{ + CornerRadius: 12, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + Padding: core.All(12), + Gap: 8, + }, + Children: children, + } +} + +// agentPinNoticeCardView renders the "Pin to brief" confirmation card matching docs/design/editor/Sketch.dc.html: +// green check, "Pinned ", Undo button, monospace YAML diff with added lines highlighted, and caption. +func agentPinNoticeCardView(ed *Editor, p SpecPalette) core.Node { + notice := ed.AgentLastPinNotice() + if notice == nil { + return nil + } + + diffRows := make([]core.Node, 0, len(notice.Diff)) + for i, line := range notice.Diff { + var rowBg core.Color + textCol := p.TextFaint + signCol := p.TextFaint + if line.Added { + rowBg = p.Added.Fill + textCol = p.Added.Fg + signCol = p.Added.Fg + } + sign := line.Sign + if sign == "" { + sign = " " + } + diffRows = append(diffRows, core.View{ + TestID: fmt.Sprintf("agent-pin-diff-line-%d", i), + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignStart, + Padding: core.Symmetric(2, 8), + Gap: 4, + Background: rowBg, + }, + Children: []core.Node{ + core.Text{ + Content: sign, + Style: core.Style{ + Width: core.Pt(10), + FlexShrink: 0, + FontFamily: core.FontMonospace, + FontSize: 11, + Color: signCol, + }, + }, + core.Text{ + Content: line.Text, + Style: core.Style{ + FlexGrow: 1, + FlexShrink: 1, + MinWidth: core.Pt(0), + FontFamily: core.FontMonospace, + FontSize: 11, + Color: textCol, + }, + }, + }, + }) + } + + headerChildren := []core.Node{ + core.SVGView{ + SVG: lucide.Check(), + Style: core.Style{ + Width: core.Pt(14), + Height: core.Pt(14), + Color: p.Added.Fg, + FlexShrink: 0, + }, + }, + core.Text{ + TestID: "agent-pin-notice-title", + Content: fmt.Sprintf("%s %s", ed.T("agent.ref.pinned"), notice.Name), + Style: core.Style{ + FlexGrow: 1, + FlexShrink: 1, + MinWidth: core.Pt(0), + FontSize: 12.5, + FontWeight: 500, + Color: p.TextPrimary, + }, + }, + } + if ed.CanUndoLastBriefPin() { + headerChildren = append(headerChildren, core.View{ + TestID: "agent-pin-notice-undo", + Role: core.RoleButton, + Label: ed.T("agent.ref.undo"), + Style: core.Style{ + Height: core.Pt(28), + Padding: core.Symmetric(0, 8), + CornerRadius: 6, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.UndoLastBriefPin() + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("agent.ref.undo"), + Style: core.Style{ + FontSize: 11.5, + Color: p.TextMuted, + }, + }, + }, + }) + } + headerChildren = append(headerChildren, core.View{ + TestID: "agent-pin-notice-dismiss", + Role: core.RoleButton, + Label: ed.T("agent.ref.dismissNotice"), + Style: core.Style{ + Width: core.Pt(24), + Height: core.Pt(24), + CornerRadius: 6, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.DismissAgentPinNotice() + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.X(), + Style: core.Style{ + Width: core.Pt(11), + Height: core.Pt(11), + Color: p.TextFaint, + }, + }, + }, + }) + + children := []core.Node{ + core.View{ + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + }, + Children: headerChildren, + }, + } + + if len(diffRows) > 0 { + children = append(children, core.View{ + TestID: "agent-pin-notice-diff", + Style: core.Style{ + CornerRadius: 8, + Background: p.Bg, + BorderWidth: 1, + BorderColor: p.Line, + Padding: core.Symmetric(6, 0), + Overflow: core.Hidden, + }, + Children: diffRows, + }) + } + + children = append(children, core.Text{ + TestID: "agent-pin-notice-caption", + Content: strings.ReplaceAll(ed.T("agent.ref.pinnedCaption"), "{path}", notice.RelPath), + Style: core.Style{ + FontSize: 11.5, + Color: p.TextFaint, + }, + }) + + return core.View{ + TestID: "agent-pin-notice-card", + Style: core.Style{ + CornerRadius: 12, + Background: p.Panel, + BorderWidth: 1, + BorderColor: p.LineRaised, + Padding: core.All(12), + Gap: 10, + }, + Children: children, + } +} + +// agentComposerDropZoneView renders the "Drop to attach" target shown while dragging images over the composer. +func agentComposerDropZoneView(ed *Editor, p SpecPalette) core.Node { + if !ed.AgentComposerDragOver() { + return nil + } + return core.View{ + TestID: "agent-composer-drop-zone", + Style: core.Style{ + MinHeight: core.Pt(96), + CornerRadius: 12, + Background: p.Accent.Fill, + BorderWidth: 1.5, + BorderColor: p.Accent.Edge, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Padding: core.All(12), + Gap: 4, + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.Upload(), + Style: core.Style{ + Width: core.Pt(20), + Height: core.Pt(20), + Color: p.Accent.Fg, + }, + }, + core.Text{ + TestID: "agent-composer-drop-title", + Content: ed.T("agent.ref.dropTitle"), + Style: core.Style{ + FontSize: 12.5, + FontWeight: 500, + Color: p.TextPrimary, + }, + }, + core.Text{ + TestID: "agent-composer-drop-subtitle", + Content: ed.T("agent.ref.dropSubtitle"), + Style: core.Style{ + FontSize: 11.5, + Color: p.TextMuted, + }, + }, + }, + } +} + +// agentAttachErrorBannerView renders the refusal reason when an unsupported file type is dropped or pasted. +func agentAttachErrorBannerView(ed *Editor, p SpecPalette) core.Node { + msg := ed.AgentAttachError() + if msg == "" { + return nil + } + return core.View{ + TestID: "agent-attach-error", + Role: core.RoleAlert, + LiveRegion: core.LiveRegionPolite, + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + Padding: core.Symmetric(8, 10), + CornerRadius: 8, + Background: p.Removed.Fill, + BorderWidth: 1, + BorderColor: p.Removed.Edge, + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.TriangleAlert(), + Style: core.Style{ + Width: core.Pt(14), + Height: core.Pt(14), + Color: p.Removed.Fg, + FlexShrink: 0, + }, + }, + core.Text{ + TestID: "agent-attach-error-text", + Content: msg, + Style: core.Style{ + FlexGrow: 1, + FlexShrink: 1, + MinWidth: core.Pt(0), + FontSize: 11.5, + Color: p.Removed.Fg, + }, + }, + core.View{ + TestID: "agent-attach-error-dismiss", + Role: core.RoleButton, + Label: ed.T("agent.ref.dismissError"), + Style: core.Style{ + Width: core.Pt(24), + Height: core.Pt(24), + CornerRadius: 4, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FocusVisible: p.FocusRing(2), + FlexShrink: 0, + }, + OnPress: func(core.PressEvent) { + ed.DismissAgentAttachError() + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.X(), + Style: core.Style{ + Width: core.Pt(11), + Height: core.Pt(11), + Color: p.Removed.Fg, + }, + }, + }, + }, + }, + } +} + +// agentAttachedImageChipsView renders the attached PNG/JPEG/WebP image chips inside the composer +// matching Sketch.dc.html: 32×24 thumbnail, filename, "Pin to brief" / "Pinned" toggle, and × remove button. +func agentAttachedImageChipsView(ed *Editor, p SpecPalette) []core.Node { + imgs := ed.AgentAttachedImages() + if len(imgs) == 0 { + return nil + } + previewID := ed.AgentImagePreviewID() + nodes := make([]core.Node, 0, len(imgs)) + for i, img := range imgs { + idx := i + item := img + isPreview := previewID == item.ID + borderCol := p.LineRaised + if isPreview { + borderCol = p.Accent.Edge + } + + pinBg := p.Raised + pinFg := p.TextSecondary + pinText := ed.T("agent.ref.pinToBrief") + pinTip := ed.T("agent.ref.pinTooltip") + if item.Pinned { + pinBg = p.Added.Fill + pinFg = p.Added.Fg + pinText = ed.T("agent.ref.pinned") + pinTip = ed.T("agent.ref.pinnedTooltip") + } + + pinBtn := core.View{ + TestID: fmt.Sprintf("agent-image-pin-%d", idx), + Role: core.RoleButton, + Label: fmt.Sprintf("%s %s", pinText, item.Name), + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Height: core.Pt(24), + Padding: core.Symmetric(0, 8), + Gap: 4, + CornerRadius: 6, + Background: pinBg, + FocusVisible: p.FocusRing(2), + FlexShrink: 0, + }, + OnPress: func(core.PressEvent) { + if item.Pinned { + return + } + _, err := ed.PinAgentReferenceImage(item.ID, "") + ed.report(err) + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.Pin(), + Style: core.Style{ + Width: core.Pt(11), + Height: core.Pt(11), + Color: pinFg, + FlexShrink: 0, + }, + }, + core.Text{ + TestID: fmt.Sprintf("agent-image-pin-text-%d", idx), + Content: pinText, + Style: core.Style{ + FontSize: 11, + Color: pinFg, + }, + }, + }, + } + + nodes = append(nodes, core.View{ + TestID: fmt.Sprintf("agent-image-chip-%d", idx), + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Height: core.Pt(32), + Padding: core.Edges{Left: 4, Right: 2}, + Gap: 6, + CornerRadius: 6, + Background: p.LineRaised, + BorderWidth: 1, + BorderColor: borderCol, + }, + OnMouseEnter: func(core.MouseEvent) { + ed.SetAgentImagePreviewID(item.ID) + }, + OnMouseLeave: func(core.MouseEvent) { + if ed.AgentImagePreviewID() == item.ID { + ed.SetAgentImagePreviewID("") + } + }, + Children: []core.Node{ + core.View{ + TestID: fmt.Sprintf("agent-image-preview-btn-%d", idx), + Role: core.RoleButton, + Label: strings.ReplaceAll(ed.T("agent.ref.previewImage"), "{name}", item.Name), + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Height: core.Pt(28), + Gap: 6, + Padding: core.Edges{Right: 2}, + CornerRadius: 4, + FocusVisible: p.FocusRing(2), + }, + OnFocus: func() { + ed.SetAgentImagePreviewID(item.ID) + }, + OnBlur: func() { + if ed.AgentImagePreviewID() == item.ID { + ed.SetAgentImagePreviewID("") + } + }, + OnPress: func(core.PressEvent) { + if ed.AgentImagePreviewID() == item.ID { + ed.SetAgentImagePreviewID("") + } else { + ed.SetAgentImagePreviewID(item.ID) + } + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(32), + Height: core.Pt(24), + CornerRadius: 4, + Background: p.Inset, + Overflow: core.Hidden, + FlexShrink: 0, + }, + Children: []core.Node{ + core.Image{ + Source: core.ImageSource{Pixels: item.Pixels, Version: item.ImageVersion}, + ResizeMode: core.Contain, + Label: item.Name, + Style: core.Style{ + Width: core.Pct(100), + Height: core.Pct(100), + }, + }, + }, + }, + core.Text{ + TestID: fmt.Sprintf("agent-image-name-%d", idx), + Content: item.Name, + Style: core.Style{ + FontSize: 11.5, + Color: p.TextPrimary, + }, + }, + }, + }, + ui.Tooltip{ + Text: pinTip, + Trigger: pinBtn, + }, + core.View{ + TestID: fmt.Sprintf("agent-image-remove-%d", idx), + Role: core.RoleButton, + Label: strings.ReplaceAll(ed.T("agent.ref.removeImage"), "{name}", item.Name), + Style: core.Style{ + Width: core.Pt(24), + Height: core.Pt(24), + CornerRadius: 4, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FocusVisible: p.FocusRing(2), + FlexShrink: 0, + }, + OnPress: func(core.PressEvent) { + ed.RemoveAgentReferenceImage(item.ID) + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.X(), + Style: core.Style{ + Width: core.Pt(10), + Height: core.Pt(10), + Color: p.TextMuted, + }, + }, + }, + }, + }, + }) + } + return nodes +} + +// agentAlwaysBriefRowView renders the "Always" context row with the brief.yaml chip (and pinned reference count) +// matching Threads.dc.html and Sketch.dc.html. Hovering or pressing previews the pinned reference images. +func agentAlwaysBriefRowView(ed *Editor, p SpecPalette) core.Node { + exists, refs := ed.readBriefMeta() + if !exists && len(refs) == 0 { + return nil + } + label := "brief.yaml" + if len(refs) == 1 { + label = ed.T("agent.ref.briefCountOne") + } else if len(refs) > 1 { + label = strings.ReplaceAll(ed.T("agent.ref.briefCountMany"), "{count}", fmt.Sprintf("%d", len(refs))) + } + + previewing := ed.AgentImagePreviewID() == AgentBriefPreviewID + borderCol := p.LineRaised + textCol := p.TextFaint + if len(refs) > 0 { + textCol = p.TextMuted + } + if previewing { + borderCol = p.Accent.Edge + textCol = p.TextPrimary + } + + chipChildren := []core.Node{ + core.SVGView{ + SVG: lucide.Lock(), + Style: core.Style{ + Width: core.Pt(10), + Height: core.Pt(10), + Color: textCol, + FlexShrink: 0, + }, + }, + core.Text{ + TestID: "agent-always-brief-text", + Content: label, + Style: core.Style{ + FontSize: 11.5, + Color: textCol, + }, + }, + } + + briefChip := core.View{ + TestID: "agent-always-brief", + Role: core.RoleButton, + Label: strings.ReplaceAll(ed.T("agent.ref.alwaysIncluded"), "{label}", label), + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Height: core.Pt(22), + Padding: core.Symmetric(0, 8), + Gap: 4, + CornerRadius: 6, + BorderWidth: 1, + BorderColor: borderCol, + FocusVisible: p.FocusRing(2), + }, + OnMouseEnter: func(core.MouseEvent) { + ed.SetAgentImagePreviewID(AgentBriefPreviewID) + }, + OnMouseLeave: func(core.MouseEvent) { + if ed.AgentImagePreviewID() == AgentBriefPreviewID { + ed.SetAgentImagePreviewID("") + } + }, + OnFocus: func() { + ed.SetAgentImagePreviewID(AgentBriefPreviewID) + }, + OnBlur: func() { + if ed.AgentImagePreviewID() == AgentBriefPreviewID { + ed.SetAgentImagePreviewID("") + } + }, + OnPress: func(core.PressEvent) { + if ed.AgentImagePreviewID() == AgentBriefPreviewID { + ed.SetAgentImagePreviewID("") + } else { + ed.SetAgentImagePreviewID(AgentBriefPreviewID) + } + }, + Children: chipChildren, + } + + return core.View{ + TestID: "agent-always-row", + Style: core.Style{ + Direction: core.Row, + Wrap: core.Wrap, + AlignItems: core.AlignCenter, + Gap: 6, + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("agent.ref.always"), + Style: core.Style{ + FontSize: 11, + Color: p.TextFaint, + }, + }, + briefChip, + }, + } +} + +// agentAttachImageButtonView renders the composer toolbar button matching Sketch.dc.html's image icon button. +func agentAttachImageButtonView(ed *Editor, p SpecPalette) core.Node { + btn := core.View{ + TestID: "agent-composer-attach-image", + Role: core.RoleButton, + Label: ed.T("agent.ref.attachLabel"), + Style: core.Style{ + Width: core.Pt(28), + Height: core.Pt(28), + CornerRadius: 6, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FocusVisible: p.FocusRing(2), + FlexShrink: 0, + }, + OnPress: func(core.PressEvent) { + ed.PickAndAttachAgentReferenceImages() + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.Image(), + Style: core.Style{ + Width: core.Pt(15), + Height: core.Pt(15), + Color: p.TextMuted, + }, + }, + }, + } + return ui.Tooltip{ + Text: ed.T("agent.ref.attachTooltip"), + Trigger: btn, + } +} + +// agentTurnImagesRowView renders compact thumbnails of reference images sent with a user turn bubble. +func agentTurnImagesRowView(turnIdx int, imgs []AgentReferenceImage, p SpecPalette) core.Node { + if len(imgs) == 0 { + return nil + } + thumbs := make([]core.Node, 0, len(imgs)) + for i, img := range imgs { + thumbs = append(thumbs, core.View{ + TestID: fmt.Sprintf("agent-turn-image-%d-%d", turnIdx, i), + Style: core.Style{ + Width: core.Pt(56), + Height: core.Pt(40), + CornerRadius: 6, + Background: p.Inset, + BorderWidth: 1, + BorderColor: p.LineRaised, + Overflow: core.Hidden, + FlexShrink: 0, + }, + Children: []core.Node{ + core.Image{ + Source: core.ImageSource{Pixels: img.Pixels, Version: img.ImageVersion}, + ResizeMode: core.Contain, + Label: img.Name, + Style: core.Style{ + Width: core.Pct(100), + Height: core.Pct(100), + }, + }, + }, + }) + } + return core.View{ + TestID: fmt.Sprintf("agent-turn-images-%d", turnIdx), + Style: core.Style{ + Direction: core.Row, + Wrap: core.Wrap, + Gap: 6, + }, + Children: thumbs, + } +} diff --git a/packages/game/editor/agent_runner_desktop.go b/packages/game/editor/agent_runner_desktop.go index 6c1595294..389358ce6 100644 --- a/packages/game/editor/agent_runner_desktop.go +++ b/packages/game/editor/agent_runner_desktop.go @@ -74,7 +74,14 @@ func (r *CLIAgentRunner) Run(ctx context.Context, req AgentRequest, emit func(Ag if err != nil { return err } - args, err := buildCLIArgs(kind, req) + ephemeralFiles, cleanup, err := materializeEphemeralCLIImages(req.Images) + if err != nil { + return err + } + if cleanup != nil { + defer cleanup() + } + args, err := buildCLIArgsWithEphemeral(kind, req, ephemeralFiles) if err != nil { return err } @@ -177,19 +184,121 @@ func validateCLISessionID(id string) error { return nil } +type cliRefImage struct { + absPath string + display string + note string +} + +func materializeEphemeralCLIImages(images []AgentReferenceImage) ([]cliRefImage, func(), error) { + var ephemeral []AgentReferenceImage + for _, img := range images { + if img.Path == "" && len(img.Data) > 0 { + ephemeral = append(ephemeral, img) + } + } + if len(ephemeral) == 0 { + return nil, nil, nil + } + tmpDir, err := os.MkdirTemp("", "nsgo-agent-ref-*") + if err != nil { + return nil, nil, fmt.Errorf("agent runner: create temp dir for reference images: %w", err) + } + cleanup := func() { + _ = os.RemoveAll(tmpDir) + } + out := make([]cliRefImage, 0, len(ephemeral)) + for i, img := range ephemeral { + format := img.Format + if format == "" { + format = AgentImagePNG + } + cleanName := sanitizeReferenceFileName(img.Name, format) + fileName := fmt.Sprintf("%02d_%s", i+1, cleanName) + absPath := filepath.Join(tmpDir, fileName) + if err := os.WriteFile(absPath, img.Data, 0o600); err != nil { + cleanup() + return nil, nil, fmt.Errorf("agent runner: write temp reference image: %w", err) + } + out = append(out, cliRefImage{ + absPath: absPath, + display: absPath, + note: sanitizeSingleLineMeta(img.Note), + }) + } + return out, cleanup, nil +} + func buildCLIArgs(kind ExternalAgentKind, req AgentRequest) ([]string, error) { + return buildCLIArgsWithEphemeral(kind, req, nil) +} + +func buildCLIArgsWithEphemeral(kind ExternalAgentKind, req AgentRequest, ephemeral []cliRefImage) ([]string, error) { if err := validateCLISessionID(req.SessionID); err != nil { return nil, err } + prompt := req.Prompt + var refs []cliRefImage + if len(req.Images) > 0 && req.ProjectRoot != "" { + for _, img := range req.Images { + if img.Path == "" { + continue + } + cleanRel := cleanBriefRefPath(img.Path) + if cleanRel == "" || strings.HasPrefix(cleanRel, "-") { + continue + } + abs := filepath.Join(req.ProjectRoot, filepath.FromSlash(cleanRel)) + if strings.HasPrefix(abs, "-") { + continue + } + if err := verifyAssetGenWritePath(req.ProjectRoot, abs, cleanRel); err != nil { + continue + } + refs = append(refs, cliRefImage{ + absPath: abs, + display: cleanRel, + note: sanitizeSingleLineMeta(img.Note), + }) + } + } + for _, eph := range ephemeral { + if eph.absPath != "" && !strings.HasPrefix(eph.absPath, "-") { + refs = append(refs, eph) + } + } + + appendRefPrompt := func(base string) string { + if len(refs) == 0 { + return base + } + var b strings.Builder + b.WriteString(base) + b.WriteString("\n\nReference images:") + for _, ref := range refs { + b.WriteString("\n- ") + b.WriteString(ref.display) + if ref.note != "" { + b.WriteString(" (") + b.WriteString(ref.note) + b.WriteByte(')') + } + } + return b.String() + } + if kind == ExternalAgentCodex { if req.SessionID != "" { - return []string{"exec", "resume", "--json", "--", req.SessionID, req.Prompt}, nil + return []string{"exec", "resume", "--json", "--", req.SessionID, appendRefPrompt(prompt)}, nil } args := []string{"exec", "--json"} if req.ProjectRoot != "" { args = append(args, "-C", req.ProjectRoot) } - return append(args, "--", req.Prompt), nil + for _, ref := range refs { + args = append(args, "-i", ref.absPath) + } + return append(args, "--", prompt), nil } args := []string{"--print", "--output-format=stream-json", "--verbose"} if req.ProjectRoot != "" { @@ -201,5 +310,6 @@ func buildCLIArgs(kind ExternalAgentKind, req AgentRequest) ([]string, error) { if req.SessionID != "" { args = append(args, "--resume", req.SessionID) } - return append(args, "--", req.Prompt), nil + prompt = appendRefPrompt(prompt) + return append(args, "--", prompt), nil } diff --git a/packages/game/editor/agent_runner_desktop_test.go b/packages/game/editor/agent_runner_desktop_test.go index d64439d17..43e385ab7 100644 --- a/packages/game/editor/agent_runner_desktop_test.go +++ b/packages/game/editor/agent_runner_desktop_test.go @@ -4,6 +4,8 @@ package editor import ( "bytes" + "os" + "path/filepath" "strings" "testing" ) @@ -81,3 +83,82 @@ func TestCappedBufferTruncatesAtLimit(t *testing.T) { t.Fatalf("len(got) = %d, want %d", len(got), maxCLISstderrBytes+len(suffix)) } } + +func TestBuildCLIArgsReferenceImageContainmentAndSanitization(t *testing.T) { + proj := t.TempDir() + outside := t.TempDir() + outsideImg := filepath.Join(outside, "secret.png") + if err := os.WriteFile(outsideImg, []byte("secret"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(proj, "art", "reference"), 0o755); err != nil { + t.Fatal(err) + } + symlinkAttempt := filepath.Join(proj, "art", "reference", "sym.png") + _ = os.Symlink(outsideImg, symlinkAttempt) + + req := AgentRequest{ + Prompt: "Match this look", + ProjectRoot: proj, + Images: []AgentReferenceImage{ + {Path: "../secret.png"}, + {Path: "-flag.png"}, + {Path: "art/reference/sym.png"}, + {Path: "art/reference/spikes_ref.png", Note: "rusty spikes\n- injected"}, + }, + } + + codexArgs, err := buildCLIArgs(ExternalAgentCodex, req) + if err != nil { + t.Fatalf("buildCLIArgs(codex): %v", err) + } + joinedCodex := strings.Join(codexArgs, "\x00") + if strings.Contains(joinedCodex, "secret.png") || strings.Contains(joinedCodex, "-flag.png") || strings.Contains(joinedCodex, "sym.png") { + t.Fatalf("unsafe image path leaked into codex args: %q", codexArgs) + } + wantAbs := filepath.Join(proj, "art", "reference", "spikes_ref.png") + if !strings.Contains(joinedCodex, "-i\x00"+wantAbs) { + t.Fatalf("valid pinned image missing from codex args: %q", codexArgs) + } + + claudeArgs, err := buildCLIArgs(ExternalAgentClaudeCode, req) + if err != nil { + t.Fatalf("buildCLIArgs(claude): %v", err) + } + claudePrompt := claudeArgs[len(claudeArgs)-1] + if strings.Contains(claudePrompt, "secret.png") || strings.Contains(claudePrompt, "sym.png") { + t.Fatalf("unsafe image path leaked into claude prompt: %q", claudePrompt) + } + if !strings.Contains(claudePrompt, "- art/reference/spikes_ref.png (rusty spikes- injected)") { + t.Fatalf("expected sanitized note in claude prompt, got: %q", claudePrompt) + } + + // Resumed Codex session includes reference image paths in prompt. + req.SessionID = "sess-42" + resumeArgs, err := buildCLIArgs(ExternalAgentCodex, req) + if err != nil { + t.Fatalf("buildCLIArgs(codex resume): %v", err) + } + if !strings.Contains(resumeArgs[len(resumeArgs)-1], "art/reference/spikes_ref.png") { + t.Fatalf("codex resume dropped reference image from prompt: %q", resumeArgs) + } + + // Ephemeral in-memory images materialize into a private temp dir and clean up cleanly. + eph, cleanup, err := materializeEphemeralCLIImages([]AgentReferenceImage{ + {Name: "pasted.png", Format: AgentImagePNG, Data: []byte("pngbytes")}, + }) + if err != nil { + t.Fatalf("materializeEphemeralCLIImages: %v", err) + } + if len(eph) != 1 { + t.Fatalf("ephemeral count = %d, want 1", len(eph)) + } + if _, err := os.Stat(eph[0].absPath); err != nil { + t.Fatalf("ephemeral temp file missing: %v", err) + } + tmpDir := filepath.Dir(eph[0].absPath) + cleanup() + if _, err := os.Stat(tmpDir); !os.IsNotExist(err) { + t.Fatalf("ephemeral temp dir not cleaned up (err=%v)", err) + } +} diff --git a/packages/game/editor/agent_ui.go b/packages/game/editor/agent_ui.go index 86e70c033..ca207aa89 100644 --- a/packages/game/editor/agent_ui.go +++ b/packages/game/editor/agent_ui.go @@ -939,7 +939,7 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N ed.agentThreads.expandedRequestID, ) for _, t := range ed.agent.turns { - fmt.Fprintf(&b, "%s:%s:%d:%v:%v:%v:%s:%s:%d:%d:%d|", t.ID, t.Status, len(t.Steps), t.Done, t.Stopped, t.SkipPlan, t.ReviewState, t.CheckpointID, len(t.Summary), len(t.Reply), len(t.Error)) + fmt.Fprintf(&b, "%s:%s:%d:%d:%v:%v:%v:%s:%s:%d:%d:%d|", t.ID, t.Status, len(t.Steps), len(t.Images), t.Done, t.Stopped, t.SkipPlan, t.ReviewState, t.CheckpointID, len(t.Summary), len(t.Reply), len(t.Error)) for _, st := range t.Steps { fmt.Fprintf(&b, "%s=%s;", st.ID, st.Status) } @@ -1251,19 +1251,22 @@ func agentTurnView(ed *Editor, turnIdx int, turn AgentTurn, p SpecPalette) core. Color: p.TextFaint, }, }) - } else if turn.Prompt != "" { - promptChildren := []core.Node{ - core.Text{ + } else if turn.Prompt != "" || len(turn.Images) > 0 { + var bubbleChildren []core.Node + if imgRow := agentTurnImagesRowView(turnIdx, turn.Images, p); imgRow != nil { + bubbleChildren = append(bubbleChildren, imgRow) + } + if turn.Prompt != "" { + bubbleChildren = append(bubbleChildren, core.Text{ Content: turn.Prompt, Style: core.Style{ FontSize: 12.5, Color: p.TextSecondary, }, - }, + }) } - chips := agentTurnContextChips(ed, turn, p) - if len(chips) > 0 { - promptChildren = append(promptChildren, core.View{ + if chips := agentTurnContextChips(ed, turn, p); len(chips) > 0 { + bubbleChildren = append(bubbleChildren, core.View{ Style: core.Style{ Direction: core.Row, Wrap: core.Wrap, @@ -1279,13 +1282,13 @@ func agentTurnView(ed *Editor, turnIdx int, turn AgentTurn, p SpecPalette) core. AlignSelf: core.AlignEnd, MaxWidth: core.Pt(296), Padding: core.Symmetric(8, 12), + Gap: 8, CornerRadius: 12, Background: p.Raised, BorderWidth: 1, BorderColor: p.LineRaised, - Gap: 6, }, - Children: promptChildren, + Children: bubbleChildren, }) } @@ -2006,20 +2009,40 @@ func agentOpenRequestCard(ed *Editor, req *AgentOpenRequest, ref *core.Ref, p Sp } func agentComposerView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], p SpecPalette, composerFocused *core.Signal[bool]) core.Node { - type composerContextKey struct { - sel string - scene string - } - contextMemo := core.NewMemo(cx, func() composerContextKey { + refMemo := core.NewMemo(cx, func() agentComposerRefKey { _ = rev.Get() - var sceneName string - if ed.Doc != nil { - sceneName = ed.Doc.Name + return buildAgentComposerRefKey(ed) + }) + + aboveComposer := core.Dynamic(func(cx *core.Scope) core.Node { + _ = refMemo.Get() + var nodes []core.Node + if pop := agentImagePreviewPopover(ed, p); pop != nil { + nodes = append(nodes, pop) + } + if pinCard := agentPinNoticeCardView(ed, p); pinCard != nil { + nodes = append(nodes, pinCard) + } + if errBanner := agentAttachErrorBannerView(ed, p); errBanner != nil { + nodes = append(nodes, errBanner) + } + if dropZone := agentComposerDropZoneView(ed, p); dropZone != nil { + nodes = append(nodes, dropZone) + } + if len(nodes) == 0 { + return nil + } + return core.View{ + Style: core.Style{ + Gap: 8, + }, + Children: nodes, } - return composerContextKey{sel: ed.SelectedID, scene: sceneName} }) + contextChips := core.Dynamic(func(cx *core.Scope) core.Node { - ctxKey := contextMemo.Get() + ctxKey := refMemo.Get() + var rows []core.Node var chips []core.Node if ctxKey.sel != "" { chips = append(chips, core.View{ @@ -2074,29 +2097,55 @@ func agentComposerView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], p S }, }) } - if len(chips) == 0 { + chips = append(chips, agentAttachedImageChipsView(ed, p)...) + if len(chips) > 0 { + rows = append(rows, core.View{ + TestID: "agent-composer-chips", + Style: core.Style{ + Direction: core.Row, + Wrap: core.Wrap, + AlignItems: core.AlignCenter, + Gap: 6, + }, + Children: chips, + }) + } + if alwaysRow := agentAlwaysBriefRowView(ed, p); alwaysRow != nil { + rows = append(rows, alwaysRow) + } + if len(rows) == 0 { return nil } return core.View{ Style: core.Style{ - Direction: core.Row, - Wrap: core.Wrap, - Gap: 6, + Gap: 6, }, - Children: chips, + Children: rows, } }) return core.View{ TestID: "agent-composer", + OnFileDragEnter: func() { + ed.SetAgentComposerDragOver(true) + }, + OnFileDragLeave: func() { + ed.SetAgentComposerDragOver(false) + }, + OnFileDrop: func(uris []string) { + _, err := ed.DropAgentReferenceFiles(uris) + ed.report(err) + }, Style: core.Style{ Padding: core.All(12), + Gap: 8, Borders: core.Edges{Top: 1}, BorderColor: p.Line, Background: p.Panel, FlexShrink: 0, }, Children: []core.Node{ + aboveComposer, core.View{ Style: core.Style{ CornerRadius: 12, @@ -2133,6 +2182,10 @@ func agentComposerView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], p S OnSubmit: func(text string) { ed.report(ed.SubmitAgentPrompt(text)) }, + OnPaste: func(ev core.PasteEvent) { + _, _, err := ed.HandleAgentComposerPaste(ev) + ed.report(err) + }, OnFocus: func() { composerFocused.Set(true) }, @@ -2157,9 +2210,10 @@ func agentComposerView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], p S Style: core.Style{ Direction: core.Row, AlignItems: core.AlignCenter, - Gap: 8, + Gap: 6, }, Children: []core.Node{ + agentAttachImageButtonView(ed, p), core.Text{ Content: ed.T("agent.composerHint"), Style: core.Style{ diff --git a/packages/game/editor/asset_gen.go b/packages/game/editor/asset_gen.go index e453e63cc..7f01d0ce4 100644 --- a/packages/game/editor/asset_gen.go +++ b/packages/game/editor/asset_gen.go @@ -530,6 +530,7 @@ func parseBriefStyleYAML(data []byte, base AssetStyleBrief) AssetStyleBrief { Art struct { Summary string `yaml:"summary"` Style string `yaml:"style"` + Direction string `yaml:"direction"` PixelGrid int `yaml:"pixelGrid"` PixelGridAlt int `yaml:"pixel_grid"` MaxColors int `yaml:"maxColors"` @@ -558,6 +559,8 @@ func parseBriefStyleYAML(data []byte, base AssetStyleBrief) AssetStyleBrief { base.Summary = s } else if s := strings.TrimSpace(doc.Art.Style); s != "" { base.Summary = s + } else if s := strings.TrimSpace(doc.Art.Direction); s != "" { + base.Summary = s } else if s := strings.TrimSpace(doc.ArtDirection); s != "" { base.Summary = s } else if s := strings.TrimSpace(doc.Summary); s != "" { diff --git a/packages/game/editor/brief_rules.go b/packages/game/editor/brief_rules.go index cd07b5450..4e1035005 100644 --- a/packages/game/editor/brief_rules.go +++ b/packages/game/editor/brief_rules.go @@ -232,6 +232,46 @@ func (e *Editor) loadAgentDocsForProject(projectDir string) { e.agentDocs.rev++ } +// reloadBriefFromDisk reloads only brief.yaml into e.agentDocs without resetting rules, pending reviews, or outcomes. +func (e *Editor) reloadBriefFromDisk() { + if e == nil { + return + } + projectDir := e.agentDocs.rootDir + if projectDir == "" { + projectDir = e.agentProjectRoot() + } + if projectDir == "" { + return + } + briefPath := filepath.Join(projectDir, project.BriefFileName) + e.agentDocs.rootDir = projectDir + e.agentDocs.briefPath = briefPath + e.agentDocs.brief = nil + e.agentDocs.briefExists = false + e.agentDocs.briefSaved = nil + e.agentDocs.briefLoadErr = nil + + if raw, err := readConfinedAgentDoc(projectDir, briefPath, project.BriefFileName); err == nil { + if b, perr := project.ParseBrief(raw); perr == nil { + e.agentDocs.brief = b + e.agentDocs.briefExists = true + if enc, eerr := project.EncodeBrief(b); eerr == nil { + e.agentDocs.briefSaved = enc + } else { + e.agentDocs.briefSaved = bytes.Clone(raw) + } + } else { + e.agentDocs.briefLoadErr = perr + } + } else if !errors.Is(err, fs.ErrNotExist) { + e.agentDocs.briefLoadErr = err + } + e.agentDocs.briefContentRev++ + e.agentDocs.rev++ + e.syncAssetStyleBriefFromAgentDocs() +} + // Brief returns a deep copy of the project's brief.yaml document, or nil when no brief exists yet. func (e *Editor) Brief() *project.Brief { if e == nil || !e.agentDocs.briefExists || e.agentDocs.brief == nil { @@ -342,6 +382,7 @@ func (c *briefCmd) do() error { } ed.agentDocs.briefContentRev++ ed.agentDocs.rev++ + ed.invalidateBriefReferenceCaches() ed.syncAssetStyleBriefFromAgentDocs() ed.notify() return nil @@ -391,6 +432,7 @@ func (c *briefCmd) undo() error { } ed.agentDocs.briefContentRev++ ed.agentDocs.rev++ + ed.invalidateBriefReferenceCaches() ed.syncAssetStyleBriefFromAgentDocs() ed.notify() return nil diff --git a/packages/game/editor/commands.go b/packages/game/editor/commands.go index b982544be..68554835a 100644 --- a/packages/game/editor/commands.go +++ b/packages/game/editor/commands.go @@ -103,6 +103,7 @@ const ( CmdGeneratedAssets = "project.generatedAssets" CmdConnectAgent = "agent.connect" CmdAgentPanel = "view.agent" + CmdAttachReferenceImage = "agent.attachImage" CmdPlayMark = "play.mark" CmdAskFrozenFrame = "play.askFrozenFrame" CmdPermissionsSettings = "settings.permissions" @@ -1774,6 +1775,22 @@ func (e *Editor) initBuiltinCommands() { return nil }, }, + { + ID: CmdAttachReferenceImage, + Label: "Attach Reference Image", + Description: "Attach a PNG, JPEG, or WebP reference image to the next agent request", + Category: "Project", + Keywords: []string{"agent", "image", "reference", "attach", "brief", "pin"}, + Scope: ScopeGlobal, + Enabled: func() bool { + return !e.Playing() && e.AgentMode() != AgentModeNone + }, + Run: func() error { + e.SetAgentPanelOpen(true) + e.PickAndAttachAgentReferenceImages() + return nil + }, + }, { ID: CmdMergeConflicts, Label: "Resolve Scene Merge Conflicts", @@ -2377,6 +2394,7 @@ var builtinCommandKeys = map[string][3]string{ CmdShortcutsSettings: {"cmd.shortcutsSettings.label", "cmd.shortcutsSettings.desc", "cmd.category.file"}, CmdConnectAgent: {"cmd.connectAgent.label", "cmd.connectAgent.desc", "cmd.category.project"}, CmdAgentPanel: {"cmd.agentPanel.label", "cmd.agentPanel.desc", "cmd.category.view"}, + CmdAttachReferenceImage: {"cmd.attachReferenceImage.label", "cmd.attachReferenceImage.desc", "cmd.category.project"}, CmdPermissionsSettings: {"cmd.permissionsSettings.label", "cmd.permissionsSettings.desc", "cmd.category.project"}, CmdMergeConflicts: {"cmd.mergeConflicts.label", "cmd.mergeConflicts.desc", "cmd.category.project"}, CmdToggleAssetsMode: {"cmd.assetDrawer.label", "cmd.assetDrawer.desc", "cmd.category.view"}, diff --git a/packages/game/editor/editorcmd/agent_references_screenshot_test.go b/packages/game/editor/editorcmd/agent_references_screenshot_test.go new file mode 100644 index 000000000..7abd2b1d6 --- /dev/null +++ b/packages/game/editor/editorcmd/agent_references_screenshot_test.go @@ -0,0 +1,189 @@ +package editorcmd_test + +import ( + "bytes" + "context" + "image" + "image/color" + "image/png" + "os" + "path/filepath" + "sync/atomic" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/project" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func renderReferenceArtPNG(t *testing.T, w, h int, accent color.RGBA) []byte { + t.Helper() + img := image.NewRGBA(image.Rect(0, 0, w, h)) + for y := range h { + // Warm dungeon stone gradient matching Sketch.dc.html spikes_ref.png thumbnail. + tVal := float64(y) / float64(max(1, h-1)) + r := uint8(0x3B - int(tVal*0x11)) + g := uint8(0x35 - int(tVal*0x10)) + b := uint8(0x30 - int(tVal*0x10)) + for x := range w { + img.SetRGBA(x, y, color.RGBA{r, g, b, 0xFF}) + } + } + // Three iron spikes along the floor. + floorY := h - h/5 + for y := floorY; y < h; y++ { + for x := range w { + img.SetRGBA(x, y, color.RGBA{0x1F, 0x23, 0x2A, 0xFF}) + } + } + for s := range 3 { + cx := (s*2 + 1) * w / 6 + tipY := h / 4 + baseHalf := w / 9 + for y := tipY; y < floorY; y++ { + half := (y - tipY) * baseHalf / max(1, floorY-tipY) + for x := cx - half; x <= cx+half; x++ { + if x >= 0 && x < w { + if x <= cx-half+1 { + img.SetRGBA(x, y, color.RGBA{0xE0, 0xA8, 0x7A, 0xFF}) + } else { + img.SetRGBA(x, y, accent) + } + } + } + } + } + var buf bytes.Buffer + if err := png.Encode(&buf, img); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +// TestAgentReferenceImagesMacOSScreenshots captures real macOS screenshots of the Agent composer's +// reference image drop overlay, attached chip with hover preview, Pin to brief YAML diff card, +// and unsupported-type refusal banner beside docs/design/editor/Sketch.dc.html and Spec.dc.html. +func TestAgentReferenceImagesMacOSScreenshots(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, project.NSGoFileName), []byte("name: dungeon-run\nid: dev.example.dungeon\nversion: 0.1.0\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "game.yaml"), []byte("version: 1\nname: dungeon-run\nid: dev.example.dungeon\nappVersion: 0.1.0\nwindow:\n width: 640\n height: 360\n"), 0o644); err != nil { + t.Fatal(err) + } + initialBrief := "art:\n direction: chunky pixel art, 16 px tiles\n references:\n - path: art/reference/torch_ref.png\n" + if err := os.WriteFile(filepath.Join(dir, "brief.yaml"), []byte(initialBrief), 0o644); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(dir, "art", "reference"), 0o755); err != nil { + t.Fatal(err) + } + torchPNG := renderReferenceArtPNG(t, 64, 48, color.RGBA{0xE9, 0xA8, 0x4A, 0xFF}) + if err := os.WriteFile(filepath.Join(dir, "art", "reference", "torch_ref.png"), torchPNG, 0o644); err != nil { + t.Fatal(err) + } + + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ed.Close() }) + ed.SetAppearance(editor.AppearanceDark) + ed.SetLanguage(editor.LanguageEnglish) + if err := ed.OpenDemo(); err != nil { + t.Fatal(err) + } + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + ed.SetRightRailTab(editor.RightTabAgent) + ed.NotifyAgentMCPConnected(editor.AgentClientInfo{ + ID: "c1", + Name: "claude-code", + Transport: "stdio", + }) + ed.AgentRunner = editor.AgentRunnerFunc(func(_ context.Context, _ editor.AgentRequest, emit func(editor.AgentEvent)) error { + emit(editor.AgentEvent{Kind: editor.AgentEventStep, StepID: "1", StepTitle: "Read level_01.scene.yaml and brief.yaml", StepStatus: editor.AgentStepDone, StepIndex: 1, StepTotal: 2}) + emit(editor.AgentEvent{Kind: editor.AgentEventStep, StepID: "2", StepTitle: "Placed 3 rusty iron spikes along the lower floor", StepStatus: editor.AgentStepDone, StepIndex: 2, StepTotal: 2}) + emit(editor.AgentEvent{Kind: editor.AgentEventMessage, Text: "Done. Spikes match spikes_ref.png."}) + 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)) + + onUI := func(fn func()) { + var done atomic.Bool + ed.Post(func() { + defer done.Store(true) + fn() + }) + app.WaitUntil(5*time.Second, done.Load) + } + + // Seed one completed turn with a reference thumbnail so the thread looks like a real session. + spikesPNG := renderReferenceArtPNG(t, 160, 96, color.RGBA{0xA2, 0x6B, 0x45, 0xFF}) + var stepErr error + onUI(func() { + if _, err := ed.AttachAgentReferenceBytes("torch_wall.png", torchPNG); err != nil { + stepErr = err + return + } + stepErr = ed.SubmitAgentPrompt("Add a torch beside the door.") + }) + if stepErr != nil { + t.Fatal(stepErr) + } + app.WaitUntil(5*time.Second, func() bool { + return app.Exists("id:agent-turn-summary-0") + }) + + // 1. Composer with attached spikes_ref.png chip + hover preview open + Always brief.yaml chip. + var img editor.AgentReferenceImage + onUI(func() { + var err error + img, err = ed.AttachAgentReferenceBytes("spikes_ref.png", spikesPNG) + if err != nil { + stepErr = err + return + } + ed.SetAgentComposerText("Build what I sketched. Spikes should look like the reference image.") + ed.SetAgentImagePreviewID(img.ID) + }) + if stepErr != nil { + t.Fatal(stepErr) + } + app.Settle() + app.Screenshot("agent-ref/composer-attached-preview") + + // 2. Drag-over "Drop to attach" overlay state matching Sketch.dc.html. + onUI(func() { + ed.SetAgentImagePreviewID("") + ed.SetAgentComposerDragOver(true) + }) + app.Settle() + app.Screenshot("agent-ref/composer-drop-zone") + + // 3. Pin to brief: green Pinned chip + "Pinned spikes_ref.png" YAML diff card with Undo + Always brief.yaml · 2 refs. + onUI(func() { + ed.SetAgentComposerDragOver(false) + _, stepErr = ed.PinAgentReferenceImage(img.ID, "rusty iron spikes, three per tile") + }) + if stepErr != nil { + t.Fatal(stepErr) + } + app.Settle() + app.Screenshot("agent-ref/composer-pinned-diff") + + // 4. Unsupported file refusal banner. + onUI(func() { + ed.DismissAgentPinNotice() + _, _ = ed.AttachAgentReferenceBytes("notes.svg", []byte(``)) + }) + app.Settle() + app.Screenshot("agent-ref/composer-refused-type") +} diff --git a/packages/game/editor/history.go b/packages/game/editor/history.go index fd2252679..44be43973 100644 --- a/packages/game/editor/history.go +++ b/packages/game/editor/history.go @@ -612,6 +612,13 @@ func (h *History) CanUndo() bool { return h != nil && h.cursor > 0 } +func (h *History) topUndoCmd() Command { + if !h.CanUndo() { + return nil + } + return h.commands[h.cursor-1] +} + // CanRedo reports whether Redo has a command to re-apply. func (h *History) CanRedo() bool { return h != nil && h.cursor < len(h.commands) diff --git a/packages/game/editor/locales/en.yaml b/packages/game/editor/locales/en.yaml index 1ba62a54c..814cee091 100644 --- a/packages/game/editor/locales/en.yaml +++ b/packages/game/editor/locales/en.yaml @@ -41,6 +41,27 @@ strings: agent.notify.reviewTitle: Ready to review agent.notify.waitingTitle: Agent needs permission agent.playDot.hoverFormat: '{summary} · stop Play to open' + agent.ref.always: Always + agent.ref.alwaysIncluded: 'Always included: {label}' + agent.ref.attachLabel: Attach an image + agent.ref.attachTooltip: Attach an image · paste or drop + agent.ref.briefCountMany: brief.yaml · {count} refs + agent.ref.briefCountOne: brief.yaml · 1 ref + agent.ref.briefEmpty: No reference images pinned yet. Pin an attached image to keep it for every request. + agent.ref.briefPreviewTitle: Pinned references + agent.ref.dismissError: Dismiss error + agent.ref.dismissNotice: Dismiss pinned notice + agent.ref.dropSubtitle: PNG, JPEG or WebP · sent with this request only + agent.ref.dropTitle: Drop to attach + agent.ref.pinToBrief: Pin to brief + agent.ref.pinTooltip: Save to art/reference/ and add it to brief.yaml + agent.ref.pinned: Pinned + agent.ref.pinnedCaption: Copied to {path}. Every later request reads it through brief.yaml. + agent.ref.pinnedTooltip: Saved to art/reference/ and listed in brief.yaml + agent.ref.previewImage: Preview {name} + agent.ref.removeImage: Remove {name} from the request + agent.ref.sentOnce: Sent with this request only + agent.ref.undo: Undo agent.revert: Revert agent.status.disconnected: Disconnected agent.status.limitShort: Limit @@ -131,6 +152,8 @@ strings: cmd.askFrozenFrame.label: Something Looks Wrong cmd.assetDrawer.desc: Switch the left rail between Scene and Assets drawer mode cmd.assetDrawer.label: Asset Drawer + cmd.attachReferenceImage.desc: Attach a PNG, JPEG, or WebP reference image to the next agent request + cmd.attachReferenceImage.label: Attach Reference Image cmd.audioMixer.desc: Toggle the Audio Bus Mixer panel cmd.audioMixer.label: Audio Bus Mixer cmd.bakeNavMesh3d.desc: Bake a 3D navigation mesh from the open scene's static geometry diff --git a/packages/game/editor/locales/zh.yaml b/packages/game/editor/locales/zh.yaml index f5fee6589..8096d76da 100644 --- a/packages/game/editor/locales/zh.yaml +++ b/packages/game/editor/locales/zh.yaml @@ -41,6 +41,27 @@ strings: agent.notify.reviewTitle: 待审查 agent.notify.waitingTitle: 智能体需要权限 agent.playDot.hoverFormat: '{summary} · 停止播放以打开' + agent.ref.always: 始终附带 + agent.ref.alwaysIncluded: 始终附带:{label} + agent.ref.attachLabel: 附加参考图 + agent.ref.attachTooltip: 附加参考图 · 粘贴或拖放 + agent.ref.briefCountMany: brief.yaml · {count} 张参考图 + agent.ref.briefCountOne: brief.yaml · 1 张参考图 + agent.ref.briefEmpty: 尚未固定参考图。固定已附加的图片即可在每次请求中附带。 + agent.ref.briefPreviewTitle: 已固定的参考图 + agent.ref.dismissError: 关闭错误提示 + agent.ref.dismissNotice: 关闭固定提示 + agent.ref.dropSubtitle: PNG、JPEG 或 WebP · 仅随本次请求发送 + agent.ref.dropTitle: 拖放到此处以附加 + agent.ref.pinToBrief: 固定到简报 + agent.ref.pinTooltip: 保存到 art/reference/ 并添加到 brief.yaml + agent.ref.pinned: 已固定 + agent.ref.pinnedCaption: 已复制到 {path}。后续每次请求都会通过 brief.yaml 读取它。 + agent.ref.pinnedTooltip: 已保存到 art/reference/ 并记录在 brief.yaml 中 + agent.ref.previewImage: 预览 {name} + agent.ref.removeImage: 从本次请求移除 {name} + agent.ref.sentOnce: 仅随本次请求发送 + agent.ref.undo: 撤销 agent.revert: 还原 agent.status.disconnected: 已断开 agent.status.limitShort: 已达上限 @@ -131,6 +152,8 @@ strings: cmd.askFrozenFrame.label: 画面看起来不对 cmd.assetDrawer.desc: 在左侧栏的“场景”与“资源抽屉”模式之间切换 cmd.assetDrawer.label: 资源抽屉 + cmd.attachReferenceImage.desc: 为下一次智能体请求附加 PNG、JPEG 或 WebP 参考图 + cmd.attachReferenceImage.label: 附加参考图 cmd.audioMixer.desc: 切换音频总线混音器面板 cmd.audioMixer.label: 音频总线混音器 cmd.bakeNavMesh3d.desc: 从当前场景的静态几何体烘焙 3D 导航网格 diff --git a/packages/game/editor/play.go b/packages/game/editor/play.go index 2994a0a55..68ff99e53 100644 --- a/packages/game/editor/play.go +++ b/packages/game/editor/play.go @@ -431,6 +431,8 @@ func (e *Editor) startPlaySession(cx *core.Scope, playback *replay.Recording, st e.playTimeScale = 1 } e.playing = true + e.agent.composerDragOver = false + e.agent.previewImageID = "" e.refreshClipPreview() if startPaused { e.Status = "Paused · frame 0" diff --git a/packages/game/editor/state.go b/packages/game/editor/state.go index 4fab0809d..2a00fabf9 100644 --- a/packages/game/editor/state.go +++ b/packages/game/editor/state.go @@ -502,6 +502,12 @@ type Editor struct { WriteClipboard func(text string) // ReadClipboard, when set, overrides reading text from the system clipboard (used by Paste); when nil and a UI scope is attached, core.Scope.ReadClipboard is used. ReadClipboard func(done func(text string)) + // ReadClipboardImage, when set, overrides reading an image from the system clipboard (used by PasteAgentReferenceImage); when nil and a UI scope is attached, core.Scope.ReadClipboardImage is used. + ReadClipboardImage func(done func(img core.ClipboardImage, ok bool, err error)) + // ReadClipboardFiles, when set, overrides reading copied file URLs from the system clipboard (used by PasteAgentReferenceImage); when nil and a UI scope is attached, core.Scope.ReadClipboardFiles is used. + ReadClipboardFiles func(done func(uris []string)) + // PickAgentReferenceFiles, when set, overrides the native file picker opened by the Agent composer's Attach an image button. + PickAgentReferenceFiles func(done func(uris []string)) // DiskWatchInterval controls how often the editor polls watched open files (scene, clip, game.yaml) and the project tree for external changes while a UI scope is attached (defaults to 250ms when <= 0). DiskWatchInterval time.Duration // OnPlaytestPrompt, when set, is called when the author presses "Ask the agent to tune it" or clicks an actionable suggestion in the Playtest Report screen. diff --git a/packages/game/project/brief.go b/packages/game/project/brief.go index a06e0574c..617242c21 100644 --- a/packages/game/project/brief.go +++ b/packages/game/project/brief.go @@ -7,6 +7,7 @@ import ( "io" "io/fs" "os" + "path" "path/filepath" "slices" "strconv" @@ -66,12 +67,30 @@ type Brief struct { Platforms []string `yaml:"platforms,omitempty,flow"` // ArtDirection describes visual style, resolution, palette, and silhouette rules. ArtDirection string `yaml:"artDirection,omitempty"` + // Art holds structured visual direction notes and pinned reference images read by the agent before every request. + Art *BriefArt `yaml:"art,omitempty"` // ToneAndAudio describes mood, music, and sound direction. ToneAndAudio string `yaml:"toneAndAudio,omitempty"` // Feel describes game feel, difficulty pacing, and structured playtest targets. Feel *BriefFeel `yaml:"feel,omitempty"` } +// BriefArt holds structured art direction notes and pinned project-relative reference images. +type BriefArt struct { + // Direction optionally describes visual direction inline under art.direction. + Direction string `yaml:"direction,omitempty"` + // References lists pinned project-relative reference images included with every agent request. + References []BriefArtReference `yaml:"references,omitempty"` +} + +// BriefArtReference names one pinned reference image listed under art.references in brief.yaml. +type BriefArtReference struct { + // Path is the project-relative slash path to the reference image (for example "art/reference/spikes_ref.png"). + Path string `yaml:"path" schema:"required,minLength=1"` + // Note is an optional short description of what the reference illustrates. + Note string `yaml:"note,omitempty"` +} + // BriefFeel describes game feel, difficulty expectations, and machine-readable playtest targets. type BriefFeel struct { // Summary describes target game feel, controls responsiveness, and difficulty pacing in plain language. @@ -102,7 +121,7 @@ type BriefPlaytestTarget struct { func Float64(v float64) *float64 { return &v } const ( - fixBrief = "write brief.yaml as version: 1 with pitch, genre, tags, platforms, artDirection, toneAndAudio, and feel" + fixBrief = "write brief.yaml as version: 1 with pitch, genre, tags, platforms, artDirection, art, toneAndAudio, and feel" fixBriefVersion = "set version: 1" fixBriefYAMLRef = "write values directly without YAML anchors, aliases, or merge keys" ) @@ -304,6 +323,22 @@ func ValidateBrief(b *Brief) error { if err := validateBriefMultiline("artDirection", b.ArtDirection); err != nil { return err } + if b.Art != nil { + if err := validateBriefMultiline("art.direction", b.Art.Direction); err != nil { + return err + } + seenRefs := make(map[string]struct{}, len(b.Art.References)) + for i, ref := range b.Art.References { + at := loaderr.Path("art", "references", i) + if err := validateBriefArtReference(at, ref); err != nil { + return err + } + if _, dup := seenRefs[ref.Path]; dup { + return loaderr.Errorf(loaderr.Join(at, "path"), "remove duplicate reference paths from art.references", "project: duplicate brief art reference %q", ref.Path) + } + seenRefs[ref.Path] = struct{}{} + } + } if err := validateBriefMultiline("toneAndAudio", b.ToneAndAudio); err != nil { return err } @@ -358,6 +393,24 @@ func validateBriefLabels(field string, items []string) error { return nil } +func validateBriefArtReference(at string, ref BriefArtReference) error { + p := ref.Path + if p == "" || strings.TrimSpace(p) != p || strings.IndexFunc(p, unicode.IsControl) >= 0 { + return loaderr.Errorf(loaderr.Join(at, "path"), "set path to a clean project-relative slash path such as art/reference/spikes_ref.png", "project: brief art reference path %q is invalid", p) + } + if strings.Contains(p, "\\") || strings.HasPrefix(p, "/") { + return loaderr.Errorf(loaderr.Join(at, "path"), "use a slash-separated project-relative path without a leading slash", "project: brief art reference path %q must be project-relative with forward slashes", p) + } + cleaned := path.Clean(p) + if cleaned == "." || cleaned == ".." || strings.HasPrefix(cleaned, "../") || cleaned != p { + return loaderr.Errorf(loaderr.Join(at, "path"), "use a normalized project-relative path without . or .. segments", "project: brief art reference path %q must be a clean project-relative path", p) + } + if ref.Note != "" && (strings.TrimSpace(ref.Note) != ref.Note || strings.IndexFunc(ref.Note, unicode.IsControl) >= 0) { + return loaderr.Errorf(loaderr.Join(at, "note"), "use a single-line note without surrounding spaces or control characters", "project: brief art reference note %q is invalid", ref.Note) + } + return nil +} + func validateBriefTarget(at string, t BriefPlaytestTarget) error { if strings.TrimSpace(t.Metric) == "" || strings.TrimSpace(t.Metric) != t.Metric || strings.IndexFunc(t.Metric, unicode.IsControl) >= 0 { return loaderr.Errorf(loaderr.Join(at, "metric"), "set metric to a non-empty metric name such as median_time or deaths", "project: brief playtest target metric %q is invalid", t.Metric) @@ -415,6 +468,15 @@ func normalizeBrief(b *Brief) { if len(b.Platforms) == 0 { b.Platforms = nil } + if b.Art != nil { + b.Art.Direction = strings.TrimSpace(strings.ReplaceAll(b.Art.Direction, "\r\n", "\n")) + if len(b.Art.References) == 0 { + b.Art.References = nil + } + if b.Art.Direction == "" && len(b.Art.References) == 0 { + b.Art = nil + } + } if b.Feel != nil { b.Feel.Summary = strings.TrimSpace(strings.ReplaceAll(b.Feel.Summary, "\r\n", "\n")) for i := range b.Feel.Targets { @@ -541,6 +603,13 @@ func (b *Brief) Clone() *Brief { cp.Genre = slices.Clone(b.Genre) cp.Tags = slices.Clone(b.Tags) cp.Platforms = slices.Clone(b.Platforms) + if b.Art != nil { + artCopy := BriefArt{ + Direction: b.Art.Direction, + References: slices.Clone(b.Art.References), + } + cp.Art = &artCopy + } if b.Feel != nil { f := BriefFeel{ Summary: b.Feel.Summary, @@ -574,7 +643,7 @@ func (b *Brief) MissingSections() []BriefSection { if len(b.Platforms) == 0 { gaps = append(gaps, BriefSectionPlatforms) } - if strings.TrimSpace(b.ArtDirection) == "" { + if strings.TrimSpace(b.ArtDirection) == "" && (b.Art == nil || (strings.TrimSpace(b.Art.Direction) == "" && len(b.Art.References) == 0)) { gaps = append(gaps, BriefSectionArtDirection) } if b.Feel == nil || (strings.TrimSpace(b.Feel.Summary) == "" && len(b.Feel.Targets) == 0) { diff --git a/packages/game/project/brief_test.go b/packages/game/project/brief_test.go index f89e5cc22..7d5337d34 100644 --- a/packages/game/project/brief_test.go +++ b/packages/game/project/brief_test.go @@ -222,3 +222,53 @@ func TestBriefLoadRejectsOversizedFile(t *testing.T) { t.Fatal("ReadBriefFS accepted file > 1 MiB") } } + +func TestBriefArtReferencesRoundTripAndValidation(t *testing.T) { + b := &project.Brief{ + Version: project.BriefVersion, + Pitch: "Dungeon run", + Art: &project.BriefArt{ + Direction: "chunky pixel art, 16 px tiles", + References: []project.BriefArtReference{ + {Path: "art/reference/torch_ref.png"}, + {Path: "art/reference/spikes_ref.png", Note: "rusty iron spikes, three per tile"}, + }, + }, + } + raw, err := project.EncodeBrief(b) + if err != nil { + t.Fatalf("EncodeBrief: %v", err) + } + parsed, err := project.ParseBrief(raw) + if err != nil { + t.Fatalf("ParseBrief: %v", err) + } + again, err := project.EncodeBrief(parsed) + if err != nil { + t.Fatalf("re-EncodeBrief: %v", err) + } + if !bytes.Equal(raw, again) { + t.Fatalf("round-trip mismatch:\n%s\nvs\n%s", again, raw) + } + if slices.Contains(parsed.MissingSections(), project.BriefSectionArtDirection) { + t.Fatalf("artDirection reported missing despite art.direction/references: %v", parsed.MissingSections()) + } + + invalid := []struct { + name string + yaml string + }{ + {"traversal", "version: 1\nart:\n references:\n - path: ../escape.png\n"}, + {"leading slash", "version: 1\nart:\n references:\n - path: /etc/passwd\n"}, + {"backslash", "version: 1\nart:\n references:\n - path: art\\reference\\a.png\n"}, + {"duplicate", "version: 1\nart:\n references:\n - path: art/reference/a.png\n - path: art/reference/a.png\n"}, + {"note newline", "version: 1\nart:\n references:\n - path: art/reference/a.png\n note: \"line1\\nline2\"\n"}, + } + for _, tc := range invalid { + t.Run(tc.name, func(t *testing.T) { + if _, err := project.ParseBrief([]byte(tc.yaml)); err == nil { + t.Fatalf("ParseBrief accepted invalid %s", tc.name) + } + }) + } +}