From c3c317631d6f3b838227786b8ec6d5d68d1675fd Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Thu, 26 Nov 2026 12:13:31 +0900 Subject: [PATCH 1/5] feat(editor,editormcp): add viewport sketch layer, reading card, and scene_edit hold gate Add a session-only 2D viewport sketch layer in scene coordinates (Pen, Arrow, Box, Text) with sequential numbered badges, optional labels, floating sketch bar, Scene Tree row, keyboard scope (ScopeSketch) without adding extra buttons to the compact 2D editor-toolbar, structured + PNG agent request payload, MCP tools (sketch_read, sketch_reading), a scene_edit confirmation hold gate, and post-edit review Sketch overlay with Keep/Revert behavior. Fixes #1025 --- ...2026-11-26-editor-viewport-sketch-agent.md | 39 + changelog.d/editor-viewport-sketch-agent.md | 3 + docs/en/editor.md | 10 + docs/en/mcp.md | 2 + docs/zh/editor.md | 10 + docs/zh/mcp.md | 2 + packages/game/editor/clipboard_group.go | 6 +- packages/game/editor/commands.go | 402 +++- .../editorcmd/sketch_screenshot_test.go | 114 ++ packages/game/editor/editormcp/edit.go | 12 +- .../game/editor/editormcp/example_test.go | 2 + packages/game/editor/editormcp/inspector.go | 3 + packages/game/editor/editormcp/object_menu.go | 12 + packages/game/editor/editormcp/proxy_test.go | 2 +- packages/game/editor/editormcp/server_test.go | 2 +- packages/game/editor/editormcp/sketch.go | 222 +++ packages/game/editor/editormcp/sketch_test.go | 196 ++ packages/game/editor/editormcp/tiles.go | 9 + packages/game/editor/editormcp/tools.go | 2 +- packages/game/editor/locales/en.yaml | 45 + packages/game/editor/locales/zh.yaml | 45 + packages/game/editor/menubar.go | 34 +- packages/game/editor/scenetree.go | 1 + packages/game/editor/shortcuts.go | 11 + packages/game/editor/sketch.go | 1742 +++++++++++++++++ packages/game/editor/sketch_png.go | 275 +++ packages/game/editor/sketch_test.go | 524 +++++ packages/game/editor/sketch_ui.go | 1394 +++++++++++++ packages/game/editor/state.go | 6 + packages/game/editor/tabs.go | 4 + packages/game/editor/tile_review.go | 2 + packages/game/editor/tile_review_ui.go | 62 +- packages/game/editor/ui.go | 24 +- packages/game/editor/viewport.go | 58 +- 34 files changed, 5195 insertions(+), 82 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-11-26-editor-viewport-sketch-agent.md create mode 100644 changelog.d/editor-viewport-sketch-agent.md create mode 100644 packages/game/editor/editorcmd/sketch_screenshot_test.go create mode 100644 packages/game/editor/editormcp/sketch.go create mode 100644 packages/game/editor/editormcp/sketch_test.go create mode 100644 packages/game/editor/sketch.go create mode 100644 packages/game/editor/sketch_png.go create mode 100644 packages/game/editor/sketch_test.go create mode 100644 packages/game/editor/sketch_ui.go diff --git a/.agents/notes/implemented/feature/2026-11-26-editor-viewport-sketch-agent.md b/.agents/notes/implemented/feature/2026-11-26-editor-viewport-sketch-agent.md new file mode 100644 index 000000000..fef369fb6 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-26-editor-viewport-sketch-agent.md @@ -0,0 +1,39 @@ +# Agent Note: Editor Viewport Sketch Layer, Reading Card, and Scene Edit Hold Gate + +Status: implemented + +## Problem + +Authors often need to point at empty areas of a 2D level—where no object or tile exists yet—and describe what an agent should build there ("3 spikes", "platform, back and forth", "locked until the lever"). Relying solely on text prompts forces manual coordinate lookup, while letting an agent immediately mutate the scene risks misinterpreting rough intent. At the same time, annotations must never leak into `*.scene.yaml` or pollute scene undo history, must remain accurate across viewport zoom and pan levels, and must not crowd the compact 2D `editor-toolbar`. + +## Decision + +The editor adds a session-only 2D viewport sketch layer (`packages/game/editor/sketch.go`, `sketch_png.go`, `sketch_ui.go`) paired with `editormcp` tools (`packages/game/editor/editormcp/sketch.go`) and a confirmation hold gate on mutating scene tools: + +- **Strict scene-coordinate session state**: Sketch marks (`Pen` polyline, `Arrow` start → end, `Box` rect, `Text` point + label) live exclusively on `Editor.sketch` and per-tab `sceneTab.sketch`, never on `sceneformat.SceneDoc` or `Editor.History`. Pointer drags convert canvas points immediately via `Editor.CanvasToWorld` and re-project during rendering via `Editor.WorldToCanvas`, keeping geometry invariant across zoom and pan changes. Sketch undo uses an isolated mark snapshot stack (`undoStack`) so undoing a mark never alters scene history or marks a scene dirty. +- **Dedicated `ScopeSketch` keyboard scope**: Entering sketch mode (`D` in `ScopeViewport2D`, or `View > Sketch`) activates `ScopeSketch` (priority `5` while sketching in 2D), enabling single-key tool shortcuts (`P` Pen, `A` Arrow, `B` Box, `T` Text, `I` Add mark at cursor, `H` Hide/Show marks, `⌘Z` Undo last mark) without colliding with `ScopeViewport` / `ScopeTile` bindings or adding extra buttons to `editor-toolbar`. `Esc` exits sketch drawing mode while retaining marks until sent, cleared, or kept. +- **Structured payload + rendered PNG**: `Editor.SendSketch` emits a `SketchAgentRequest` carrying `"Sketch · N marks"`, structured marks in scene coordinates, and a software-rasterized PNG (`RenderSketchViewportPNG` via `packages/game/mcp.RenderPNG` plus a 5×7 bitmap text pass for numbered badges and labels). +- **MCP reading card and hold gate**: Sending a sketch transitions the hold state to `SketchHoldPending` (and `SketchHoldReading` once the agent calls `sketch_reading`). While `Editor.SketchHoldActive()` is true, `scene_edit` and other mutating scene MCP tools (`tile_paint`, `tile_autotile`, `tile_erase`, `object_paste_yaml`, `object_duplicate`, `object_group`, `object_move_under`, `object_set_field`) refuse cleanly with a structured `*EditError` and leave the scene and history untouched. `ApproveSketchReading` (**Go ahead**) or `ReplyToSketchReading` releases the hold and captures a pre-edit scene snapshot; `CorrectSketchMark` (**Correct a mark**) reopens sketch mode with that exact mark selected while keeping the hold active. +- **Review overlay and Keep / Revert symmetry**: Approved `scene_edit` calls record changes into `sketchReviewState` (opening the review card with a **Sketch overlay** toggle that renders the sketch as a faint dotted reference over added/changed outlines). Both `KeepSketchReview` and `KeepTileReview` clear the sketch layer; both `RevertSketchReview` and `RevertAllTileReview` restore the scene while preserving the sketch marks so the author can send them again. + +### Related notes + +- Builds on [Editor MCP Server](../../implemented/architecture/2026-11-25-editor-mcp-server.md) for tool registration, `EditError` refusals, and in-memory MCP testing. +- Complements [Editor Viewport Overlays](../../implemented/feature/2026-11-26-editor-viewport-overlays.md) and [Editor MCP Tile Review](../../implemented/feature/2026-11-26-editor-mcp-tile-review.md) by sharing the Spec dark/light token palette and Keep/Revert lifecycle. +- Uses the scope-aware shortcut registry from [Editor Settings and Shortcuts](../../implemented/feature/2026-11-26-editor-settings-shortcuts.md). + +## Alternatives considered + +- **Storing sketch marks as temporary objects or metadata inside `SceneDoc`**: Would automatically inherit scene rendering and undo history, but violates the core invariant that every author-created YAML file stays clean and reviewable and risks saving transient marks into git diffs. Rejected in favor of session-only `sketchState` synced per `sceneTab`. +- **Adding a Sketch button directly to `editor-toolbar`**: Matches the top bar in `Sketch.dc.html`, but the current 2D `editor-toolbar` already wraps at 1200 px and has layout tests verifying toolbar compactness. Rejected in favor of keyboard shortcut `D`, `View > Sketch`, Command Palette, Scene Tree `SKETCH LAYER`, and the floating top-center sketch toolbar. +- **Blocking `scene_edit` in `Editor` mutators themselves**: Would prevent manual editor edits while a sketch is pending, even when the user wants to tweak something by hand before confirming. Rejected in favor of enforcing the hold gate specifically on mutating `editormcp` handlers via `Editor.SketchHoldActive()`. + +## Consequences + +- **Benefits**: + - Authors can annotate empty regions with four tools and numbered badges at any zoom level without ever dirtying `.scene.yaml` or scene undo history. + - Agents receive both exact scene coordinates and a visual PNG with numbered badges, and must restate their interpretation via `sketch_reading` before mutating the scene. + - Review lets authors visually compare added/changed objects against their original sketch and either clear marks on Keep or keep marks ready to re-send on Revert. +- **Costs**: + - Adding `sketch_read` and `sketch_reading` increases the built-in `editormcp` tool surface (requiring updates to tool-list conformance tests and docs). + - `packages/game/editor` now contains a lightweight 5×7 bitmap text rasterizer (`sketch_png.go`) parallel to `editormcp/viewport_text.go` so `Editor.RenderSketchViewportPNG` works without introducing a package cycle between `editor` and `editormcp`. diff --git a/changelog.d/editor-viewport-sketch-agent.md b/changelog.d/editor-viewport-sketch-agent.md new file mode 100644 index 000000000..e5b7514fe --- /dev/null +++ b/changelog.d/editor-viewport-sketch-agent.md @@ -0,0 +1,3 @@ +### Added + +- `game/editor`, `game/editor/editormcp`: add a session-only viewport sketch layer (Pen, Arrow, Box, Text in scene coordinates with numbered badges, labels, rendered PNG export, keyboard shortcuts in `ScopeSketch`), `sketch_read` / `sketch_reading` MCP tools with a confirmation hold gate on `scene_edit` until Go ahead or Correct a mark, and a review Sketch overlay toggle where Keep clears marks and Revert keeps them (#1025). diff --git a/docs/en/editor.md b/docs/en/editor.md index bb7c20826..ce664b537 100644 --- a/docs/en/editor.md +++ b/docs/en/editor.md @@ -1522,3 +1522,13 @@ The right rail (`RightRailView`) switches between **Agent** (`AgentPanelView` / - **Folded earlier requests, History link, and Jump to latest**: earlier reviewed requests fold to one line each (`N EARLIER REQUESTS`) and expand on click to show the full prompt, changed fields, steps, and **Open this step in History** (`OpenHistoryStep`), which opens the unified History timeline highlighted on that step. Expanding an earlier request surfaces a floating **Jump to latest** pill (`JumpToLatestAgentRequest`). - **Empty-thread view (`AgentAlwaysReadItems`, `AgentBriefSuggestions`)**: an empty thread lists what the agent reads with every request (` · whole scene`, `brief.yaml`, `AGENTS.md`, `Viewport image`) and up to three starter prompts read safely from the project's `brief.yaml` (`FROM YOUR BRIEF`). - **Inspector footer attribution (`LastAgentChangeForObject`, `OpenAgentRequest`)**: when a selected object was changed by a non-reverted agent request (via `SendAgentRequestWith`, `RecordAgentStep`, or `editormcp`'s `scene_edit`), the Inspector footer displays `Changed in “” · ` and clicking it opens that thread and expands that request. + +## Viewport sketch layer for the agent (#1025) + +Draw session-only numbered annotations directly over the 2D viewport to point at empty places in a level before asking the agent to build them (`docs/design/editor/Sketch.dc.html`, styled exclusively with `docs/design/editor/Spec.dc.html` tokens): + +- **Four sketch tools in scene coordinates**: press `D` (`CmdSketchToggle`, or `View > Sketch`) to toggle Sketch mode without adding extra buttons to the compact 2D `editor-toolbar`. Switch between **Pen** (`P`, freehand polyline), **Arrow** (`A`, start → end), **Box** (`B`, rect), and **Text** (`T`, point + label) in `ScopeSketch`, or place a mark at the cursor with `I` (`CmdSketchAddMarkAtCursor`). Every mark gets a sequential numbered badge (`1`, `2`, `3`, …) and an optional label (such as `"3 spikes"`, `"platform, back and forth"`, `"locked until the lever"`). All geometry is converted through `CanvasToWorld` and stored strictly in scene coordinates so marks scale and pan accurately across zoom levels and are **never** written into `SceneDoc`, `*.scene.yaml`, or scene undo `History`. +- **Sketch bar, Scene Tree row, and status bar**: the floating sketch bar displays the four tools, **Undo last mark** (`⌘Z` in `ScopeSketch`), **Hide / Show marks** (`H`), `"N marks not saved"`, **Clear**, and **Done**. Pressing `Esc` finishes sketch mode while keeping drawn marks until sent, cleared, or kept. The Scene Tree displays a compact `SKETCH LAYER` row (`N marks · not saved`), and the status bar shows live scene coordinates and the active sketch tool. +- **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. diff --git a/docs/en/mcp.md b/docs/en/mcp.md index b21166e53..96f404492 100644 --- a/docs/en/mcp.md +++ b/docs/en/mcp.md @@ -346,6 +346,8 @@ claude mcp add game-editor -- nsgo game mcp | `datatable_review_propose` | edit | `files` (required), `prompt`, `checks` (optional) | Validates one or more version-1 YAML data table files against `datatable.ParseDocument` (and any registered Go row type) and opens the row-by-row Data Table review screen with old → new, `Δ%`, per-record Revert/Restore, and optional named agent check figures without modifying disk until Keep. | | `datatable_review_checks` | edit | `checks` (required) | Attaches or refreshes named agent check figures (`label`, `value`, `before`, `basis`) on the active Data Table review and clears `checksOutOfDate` after the person reverts, edits, or reorders records. | | `datatable_review_status` | read | `file` (optional) | Reports the active Data Table review's files, kept/reverted/user-edited counts, active record states, attached check figures, and whether `checksOutOfDate` is true. | +| `sketch_read` | read | `includeImage`, `scale` | Reads the active or sent viewport sketch marks (Pen, Arrow, Box, Text) with sequential badge numbers, exact scene coordinates, labels, prompt, hold state, and an optional rendered PNG of the viewport with numbered marks overlaid. | +| `sketch_reading` | edit | `summary`, `items`, `assumptions` | Posts the agent's restatement card (`"I read your sketch as: …"`) and assumptions for a sent viewport sketch; while a sent sketch awaits confirmation, `scene_edit` and other mutating scene tools hold cleanly until the person chooses **Go ahead**, **Correct a mark**, or replies in words. | Every tool registered on the editor's MCP server can be turned on or off per computer in **Settings › Tools** (`Editor.SetMCPToolEnabled`): disabling a tool removes it from the server's advertised tool list (`tools/list_changed`) and returns a readable refusal if called. Outbound content categories in **Settings › Usage and privacy** (**WHAT MAY LEAVE THIS COMPUTER**: Scene and data files, Viewport images, Go source code, Art and audio files) are enforced for every connected agent across all tools (including symlink-resolved file paths) and all resources (`editor://scene`, `editor://selection`, `editor://agent/turn`, `editor://brief`, `editor://rules`, `editor://context`), refusing calls with the reason whenever the requested content kind is switched off. Additional MCP servers configured in **Settings › Tools** (starting with `nsgo-game` for the running game via `go tool nsgo mcp`) are synced into `.mcp.json` and `.codex/config.toml` via `editormcp.InstallWithServers`. diff --git a/docs/zh/editor.md b/docs/zh/editor.md index ba37f84fa..e5ca3351a 100644 --- a/docs/zh/editor.md +++ b/docs/zh/editor.md @@ -1522,3 +1522,13 @@ func main() { - **折叠较早请求、跳转历史记录与跳到最新**:已审查的较早请求折叠为单行(`N 条较早请求`),点击展开显示完整提示词、变更明细、步骤列表以及**在历史记录中打开此步骤**(`OpenHistoryStep`)链接,点击后在统一历史时间线中高亮该步骤;展开较早请求时底部浮现**跳到最新**按钮(`JumpToLatestAgentRequest`)。 - **空白线程视图(`AgentAlwaysReadItems`、`AgentBriefSuggestions`)**:空白线程会列出智能体每次请求必读的上下文(`<场景> · 整个场景`、`brief.yaml`、`AGENTS.md`、`视口图像`),并安全读取项目 `brief.yaml` 中的建议提示(`来自项目简报`)。 - **检查器页脚来源链接(`LastAgentChangeForObject`、`OpenAgentRequest`)**:当选中对象曾被未还原的智能体请求修改(无论是通过 `SendAgentRequestWith`、`RecordAgentStep` 还是 `editormcp` 的 `scene_edit`),检查器页脚会显示“修改自“<请求标题>” · <时间>”,点击即可打开对应线程并定位/展开该请求。 + +## 面向智能体的视口草图层(#1025) + +在 2D 视口上直接绘制会话级编号草图,指向关卡中尚不存在对象的区域再交给智能体构建(对应 `docs/design/editor/Sketch.dc.html`,严格使用 `docs/design/editor/Spec.dc.html` 令牌): + +- **场景坐标下的四种草图工具**:按 `D`(`CmdSketchToggle` 或 `视图 > 草图`)开启/关闭草图模式,不向紧凑的 2D `editor-toolbar` 额外增加按钮。在 `ScopeSketch` 作用域下可切换 **画笔(Pen,`P`,自由折线)**、**箭头(Arrow,`A`,起点 → 终点)**、**方框(Box,`B`,矩形区域)** 与 **文本(Text,`T`,锚点 + 标签)**,也可按 `I`(`CmdSketchAddMarkAtCursor`)在光标处用键盘放置标记。每个标记自动分配连续编号徽章(`1`、`2`、`3`…)和可选标签(例如 `"3 spikes"`、`"platform, back and forth"`、`"locked until the lever"`)。所有几何坐标均通过 `CanvasToWorld` 严格保存在场景坐标中,跨缩放与平移保持精准,且**绝不**写入 `SceneDoc`、`*.scene.yaml` 或场景撤销 `History`。 +- **悬浮草图栏、场景树行与状态栏**:顶部悬浮草图栏提供四种工具、**撤销上一个标记**(`ScopeSketch` 下的 `⌘Z`)、**隐藏 / 显示标记**(`H`)、`"N marks not saved"` 计数、**Clear** 与 **Done**。按 `Esc` 结束草图绘制模式并保留已绘标记,直到发送、清空或审查保留。场景树底部展示紧凑的 `SKETCH LAYER` 行(`N marks · not saved`),状态栏实时显示场景坐标与当前草图工具。 +- **将草图发送给智能体(`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`)撤销修改但保留草图标记以便再次发送。 diff --git a/docs/zh/mcp.md b/docs/zh/mcp.md index 3b5525c44..7ca06f9f5 100644 --- a/docs/zh/mcp.md +++ b/docs/zh/mcp.md @@ -346,6 +346,8 @@ claude mcp add game-editor -- nsgo game mcp | `datatable_review_propose` | edit | `files`(必填)、`prompt`、`checks`(可选) | 使用 `datatable.ParseDocument`(及已注册的 Go 行类型)校验一个或多个版本 1 YAML 数据表文件,并打开带旧值 → 新值、`Δ%`、单行 Revert/Restore 与可选智能体核验指标的逐行数据表审查界面,在用户点击 Keep 前不修改磁盘。 | | `datatable_review_checks` | edit | `checks`(必填) | 在当前数据表审查中附上或刷新智能体的具名核验指标(`label`、`value`、`before`、`basis`),并在作者还原、编辑或重排记录后清除 `checksOutOfDate` 标记。 | | `datatable_review_status` | read | `file`(可选) | 返回当前数据表审查的文件列表、保留/还原/用户编辑计数、当前文件改动记录状态、已附带的核验指标以及 `checksOutOfDate` 是否为真。 | +| `sketch_read` | read | `includeImage`、`scale` | 读取当前或已发送的视口草图标记(画笔、箭头、方框、文本),返回连续编号、精确场景坐标、标签、提示词、确认闸门状态,以及可选的叠加编号标记的视口渲染 PNG。 | +| `sketch_reading` | edit | `summary`、`items`、`assumptions` | 向编辑器提交智能体对已发送草图的复述卡片(`"I read your sketch as: …"`)与假设说明;在草图等待确认期间,`scene_edit` 及其他变更场景的工具会被拦住,直到用户点击 **Go ahead**、**Correct a mark** 或以文字回复。 | 编辑器 MCP 服务器注册的每个工具都可在**设置 › 工具**中按电脑独立开关(`Editor.SetMCPToolEnabled`):关闭后会从服务器公布的工具列表中移除(发送 `tools/list_changed`),被直接调用时返回可读的拒绝原因。**设置 › 用量与隐私**中的四项**允许离开此计算机的内容**开关(场景与数据文件、视口画面、Go 源代码、美术与音频文件)对所有已连接智能体的全部工具调用(包含符号链接解析后的真实路径)与全部资源读取(`editor://scene`、`editor://selection`、`editor://agent/turn`、`editor://brief`、`editor://rules`、`editor://context`)强制生效,只要对应内容类型已关闭即返回拒绝原因。在**设置 › 工具**中配置的其他 MCP 服务器(默认包含经由 `go tool nsgo mcp` 访问运行中游戏的 `nsgo-game`)会通过 `editormcp.InstallWithServers` 自动同步到项目的 `.mcp.json` 与 `.codex/config.toml`。 diff --git a/packages/game/editor/clipboard_group.go b/packages/game/editor/clipboard_group.go index b4135f77f..364739893 100644 --- a/packages/game/editor/clipboard_group.go +++ b/packages/game/editor/clipboard_group.go @@ -172,11 +172,15 @@ func (e *Editor) SetViewportPointer2D(canvasX, canvasY float32) { return } pos := math2d.Vec2{X: canvasX, Y: canvasY} - if !e.hasPointer2D || e.pointer2D != pos { + changed := !e.hasPointer2D || e.pointer2D != pos + if changed { e.pasteStreak = 0 } e.pointer2D = pos e.hasPointer2D = true + if changed && e.SketchActive() { + e.notify() + } } // SetViewportPointer3D records the mouse pointer's canvas position over the 3D viewport diff --git a/packages/game/editor/commands.go b/packages/game/editor/commands.go index 4b4355c48..a1de660c7 100644 --- a/packages/game/editor/commands.go +++ b/packages/game/editor/commands.go @@ -129,6 +129,23 @@ const ( CmdReviewKeep = "review.keep" CmdReviewRevertAll = "review.revertAll" CmdNewAgentThread = "agent.newThread" + // Viewport sketch layer commands (issue #1025). + CmdSketchToggle = "sketch.toggle" + CmdSketchToolPen = "sketch.tool.pen" + CmdSketchToolArrow = "sketch.tool.arrow" + CmdSketchToolBox = "sketch.tool.box" + CmdSketchToolText = "sketch.tool.text" + CmdSketchAddMarkAtCursor = "sketch.addMarkAtCursor" + CmdSketchUndoMark = "sketch.undoMark" + CmdSketchToggleMarks = "sketch.toggleMarks" + CmdSketchClear = "sketch.clear" + CmdSketchDone = "sketch.done" + CmdSketchSend = "sketch.send" + CmdSketchApproveReading = "sketch.approveReading" + CmdSketchCorrectMark = "sketch.correctMark" + CmdSketchToggleReviewOverlay = "sketch.toggleReviewOverlay" + CmdSketchKeepReview = "sketch.keepReview" + CmdSketchRevertReview = "sketch.revertReview" ) var ( @@ -1921,6 +1938,243 @@ func (e *Editor) initBuiltinCommands() { return nil }, }, + { + ID: CmdSketchToggle, + Label: "Sketch on Viewport", + Description: "Toggle the session-only viewport sketch layer for the agent", + Category: "Tools", + Keywords: []string{"sketch", "draw", "annotate", "agent", "viewport", "marks"}, + Scope: ScopeViewport2D, + Shortcut: "d", + Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D }, + Checked: func() bool { return e.SketchActive() }, + Run: func() error { + e.ToggleSketch() + return nil + }, + }, + { + ID: CmdSketchToolPen, + Label: "Sketch Tool: Pen", + Description: "Draw a freehand polyline mark on the viewport sketch layer", + Category: "Tools", + Keywords: []string{"sketch", "pen", "freehand", "line", "polyline"}, + Scope: ScopeSketch, + Shortcut: "p", + Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchActive() }, + Checked: func() bool { return e.SketchActive() && e.SketchTool() == SketchToolPen }, + Run: func() error { + e.SetSketchTool(SketchToolPen) + return nil + }, + }, + { + ID: CmdSketchToolArrow, + Label: "Sketch Tool: Arrow", + Description: "Draw a directed arrow mark on the viewport sketch layer", + Category: "Tools", + Keywords: []string{"sketch", "arrow", "pointer", "direction"}, + Scope: ScopeSketch, + Shortcut: "a", + Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchActive() }, + Checked: func() bool { return e.SketchActive() && e.SketchTool() == SketchToolArrow }, + Run: func() error { + e.SetSketchTool(SketchToolArrow) + return nil + }, + }, + { + ID: CmdSketchToolBox, + Label: "Sketch Tool: Box", + Description: "Draw a rectangular area mark on the viewport sketch layer", + Category: "Tools", + Keywords: []string{"sketch", "box", "rect", "rectangle", "area"}, + Scope: ScopeSketch, + Shortcut: "b", + Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchActive() }, + Checked: func() bool { return e.SketchActive() && e.SketchTool() == SketchToolBox }, + Run: func() error { + e.SetSketchTool(SketchToolBox) + return nil + }, + }, + { + ID: CmdSketchToolText, + Label: "Sketch Tool: Text", + Description: "Place a labelled text mark on the viewport sketch layer", + Category: "Tools", + Keywords: []string{"sketch", "text", "label", "note", "callout"}, + Scope: ScopeSketch, + Shortcut: "t", + Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchActive() }, + Checked: func() bool { return e.SketchActive() && e.SketchTool() == SketchToolText }, + Run: func() error { + e.SetSketchTool(SketchToolText) + return nil + }, + }, + { + ID: CmdSketchAddMarkAtCursor, + Label: "Sketch: Add Mark at Cursor", + Description: "Place a numbered sketch mark at the current cursor or viewport center", + Category: "Tools", + Keywords: []string{"sketch", "add", "insert", "mark", "keyboard"}, + Scope: ScopeSketch, + Shortcut: "i", + Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchActive() }, + Run: func() error { + e.AddSketchMarkAtCursor("") + return nil + }, + }, + { + ID: CmdSketchUndoMark, + Label: "Sketch: Undo Last Mark", + Description: "Undo the most recent change to the viewport sketch layer", + Category: "Edit", + Keywords: []string{"sketch", "undo", "mark", "remove"}, + Scope: ScopeSketch, + Shortcut: "mod+z", + Enabled: func() bool { + return notPlaying() && e.ViewMode == ViewMode2D && e.SketchActive() && e.CanUndoSketchMark() + }, + Run: func() error { + e.UndoLastSketchMark() + return nil + }, + }, + { + ID: CmdSketchToggleMarks, + Label: "Sketch: Hide / Show Marks", + Description: "Temporarily hide or show sketch marks on the viewport without clearing them", + Category: "View", + Keywords: []string{"sketch", "hide", "show", "visibility", "marks"}, + Scope: ScopeSketch, + Shortcut: "h", + Enabled: func() bool { + return notPlaying() && e.ViewMode == ViewMode2D && (e.SketchActive() || e.SketchMarkCount() > 0) + }, + Checked: func() bool { return e.SketchMarksHidden() }, + Run: func() error { + e.ToggleSketchMarksHidden() + return nil + }, + }, + { + ID: CmdSketchClear, + Label: "Sketch: Clear Marks", + Description: "Clear all sketch marks from the viewport sketch layer", + Category: "Edit", + Keywords: []string{"sketch", "clear", "delete", "marks"}, + Scope: ScopeSketch, + Shortcut: "mod+shift+backspace", + Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchMarkCount() > 0 }, + Run: func() error { + e.ClearSketch() + return nil + }, + }, + { + ID: CmdSketchDone, + Label: "Sketch: Finish Sketch Mode", + Description: "Leave sketch drawing mode while keeping drawn marks until sent or cleared", + Category: "Tools", + Keywords: []string{"sketch", "done", "finish", "exit"}, + Scope: ScopeSketch, + Shortcut: "shift+d", + Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchActive() }, + Run: func() error { + e.FinishSketch() + return nil + }, + }, + { + ID: CmdSketchSend, + Label: "Sketch: Send to Agent", + Description: "Send the viewport sketch marks in scene coordinates and rendered PNG to the agent", + Category: "Tools", + Keywords: []string{"sketch", "send", "agent", "request", "prompt"}, + Scope: ScopeSketch, + Shortcut: "mod+enter", + Enabled: func() bool { + return notPlaying() && e.ViewMode == ViewMode2D && e.SketchMarkCount() > 0 && !e.SketchHoldActive() + }, + Run: func() error { + _, err := e.SendSketch(e.SketchPromptDraft()) + return err + }, + }, + { + ID: CmdSketchApproveReading, + Label: "Sketch: Go Ahead", + Description: "Approve the agent's sketch reading and release the scene_edit confirmation hold", + Category: "Tools", + Keywords: []string{"sketch", "approve", "go ahead", "confirm", "agent", "reading"}, + Scope: ScopeViewport2D, + Shortcut: "mod+enter", + Enabled: func() bool { + return notPlaying() && e.ViewMode == ViewMode2D && e.SketchHoldActive() && e.SketchReading() != nil + }, + Run: func() error { return e.ApproveSketchReading() }, + }, + { + ID: CmdSketchCorrectMark, + Label: "Sketch: Correct a Mark", + Description: "Reopen sketch mode with the targeted mark selected to correct it", + Category: "Tools", + Keywords: []string{"sketch", "correct", "mark", "edit", "reading"}, + Scope: ScopeViewport2D, + Shortcut: "shift+m", + Enabled: func() bool { + return notPlaying() && e.ViewMode == ViewMode2D && e.SketchReading() != nil && e.SketchMarkCount() > 0 + }, + Run: func() error { + target := e.SelectedSketchMark() + if target <= 0 { + target = 1 + } + return e.CorrectSketchMark(target) + }, + }, + { + ID: CmdSketchToggleReviewOverlay, + Label: "Review: Toggle Sketch Overlay", + Description: "Lay the sent sketch faintly over the reviewed result in the 2D viewport", + Category: "View", + Keywords: []string{"sketch", "review", "overlay", "compare", "toggle"}, + Scope: ScopeViewport2D, + Shortcut: "o", + Enabled: func() bool { + return notPlaying() && e.ViewMode == ViewMode2D && (e.SketchReviewOpen() || e.TileReviewOpen()) && e.SketchMarkCount() > 0 + }, + Checked: func() bool { return e.SketchReviewOverlayVisible() }, + Run: func() error { + e.ToggleSketchReviewOverlay() + return nil + }, + }, + { + ID: CmdSketchKeepReview, + Label: "Review: Keep Changes and Clear Sketch", + Description: "Keep the agent's post-sketch scene edits and clear the viewport sketch layer", + Category: "Edit", + Keywords: []string{"sketch", "review", "keep", "accept", "clear"}, + Scope: ScopeViewport2D, + Shortcut: "mod+shift+enter", + Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchReviewOpen() }, + Run: func() error { return e.KeepSketchReview() }, + }, + { + ID: CmdSketchRevertReview, + Label: "Review: Revert Changes and Keep Sketch", + Description: "Revert the agent's post-sketch scene edits while keeping the sketch marks to send again", + Category: "Edit", + Keywords: []string{"sketch", "review", "revert", "undo", "keep marks"}, + Scope: ScopeViewport2D, + Shortcut: "mod+backspace", + Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchReviewOpen() }, + Run: func() error { return e.RevertSketchReview() }, + }, } } @@ -2062,72 +2316,88 @@ func pluginCommandID(pluginName, cmdID string) string { // builtinCommandKeys maps built-in command IDs to their localization keys for label, description and category. var builtinCommandKeys = map[string][3]string{ - CmdNewProject: {"cmd.newProject.label", "cmd.newProject.desc", "cmd.category.file"}, - CmdOpenProject: {"cmd.openProject.label", "cmd.openProject.desc", "cmd.category.file"}, - CmdStartScreen: {"cmd.startScreen.label", "cmd.startScreen.desc", "cmd.category.file"}, - CmdSave: {"cmd.save.label", "cmd.save.desc", "cmd.category.file"}, - CmdUndo: {"cmd.undo.label", "cmd.undo.desc", "cmd.category.edit"}, - CmdRedo: {"cmd.redo.label", "cmd.redo.desc", "cmd.category.edit"}, - CmdCopy: {"cmd.copy.label", "cmd.copy.desc", "cmd.category.edit"}, - CmdCut: {"cmd.cut.label", "cmd.cut.desc", "cmd.category.edit"}, - CmdPaste: {"cmd.paste.label", "cmd.paste.desc", "cmd.category.edit"}, - CmdPasteInto: {"cmd.pasteInto.label", "cmd.pasteInto.desc", "cmd.category.edit"}, - CmdDelete: {"cmd.delete.label", "cmd.delete.desc", "cmd.category.edit"}, - CmdDuplicate: {"cmd.duplicate.label", "cmd.duplicate.desc", "cmd.category.edit"}, - CmdGroup: {"cmd.group.label", "cmd.group.desc", "cmd.category.edit"}, - CmdUngroup: {"cmd.ungroup.label", "cmd.ungroup.desc", "cmd.category.edit"}, - CmdToolSelect: {"cmd.toolSelect.label", "cmd.toolSelect.desc", "cmd.category.tools"}, - CmdToolMove: {"cmd.toolMove.label", "cmd.toolMove.desc", "cmd.category.tools"}, - CmdToolPlace: {"cmd.toolPlace.label", "cmd.toolPlace.desc", "cmd.category.tools"}, - CmdToolPaintTile: {"cmd.toolPaintTile.label", "cmd.toolPaintTile.desc", "cmd.category.tools"}, - CmdToolEraseTile: {"cmd.toolEraseTile.label", "cmd.toolEraseTile.desc", "cmd.category.tools"}, - CmdToolFillTile: {"cmd.toolFillTile.label", "cmd.toolFillTile.desc", "cmd.category.tools"}, - CmdToolNavTestPath: {"cmd.toolNavTestPath.label", "cmd.toolNavTestPath.desc", "cmd.category.tools"}, - CmdGizmoTranslate: {"cmd.gizmoTranslate.label", "cmd.gizmoTranslate.desc", "cmd.category.gizmo3d"}, - CmdGizmoRotate: {"cmd.gizmoRotate.label", "cmd.gizmoRotate.desc", "cmd.category.gizmo3d"}, - CmdGizmoScale: {"cmd.gizmoScale.label", "cmd.gizmoScale.desc", "cmd.category.gizmo3d"}, - CmdGizmoSpace3D: {"cmd.gizmoSpace3d.label", "cmd.gizmoSpace3d.desc", "cmd.category.gizmo3d"}, - CmdView2D: {"cmd.view2d.label", "cmd.view2d.desc", "cmd.category.view"}, - CmdView3D: {"cmd.view3d.label", "cmd.view3d.desc", "cmd.category.view"}, - CmdShadingLit: {"cmd.shadingLit.label", "cmd.shadingLit.desc", "cmd.category.view"}, - CmdShadingUnlit: {"cmd.shadingUnlit.label", "cmd.shadingUnlit.desc", "cmd.category.view"}, - CmdShadingWire: {"cmd.shadingWire.label", "cmd.shadingWire.desc", "cmd.category.view"}, - CmdNavMeshPanel: {"cmd.navMeshPanel.label", "cmd.navMeshPanel.desc", "cmd.category.view"}, - CmdNavMeshOverlay: {"cmd.navMeshOverlay.label", "cmd.navMeshOverlay.desc", "cmd.category.view"}, - CmdBakeNavMesh3D: {"cmd.bakeNavMesh3d.label", "cmd.bakeNavMesh3d.desc", "cmd.category.project"}, - CmdFrameSelection: {"cmd.frameSelection.label", "cmd.frameSelection.desc", "cmd.category.view"}, - CmdView3DOrthographic: {"cmd.view3dOrtho.label", "cmd.view3dOrtho.desc", "cmd.category.view"}, - CmdToggleLightingPreview: {"cmd.lightingPreview.label", "cmd.lightingPreview.desc", "cmd.category.view"}, - CmdToggleNavMesh2D: {"cmd.navMesh2dOverlay.label", "cmd.navMesh2dOverlay.desc", "cmd.category.view"}, - CmdAskAgent: {"cmd.askAgent.label", "cmd.askAgent.desc", "cmd.category.view"}, - CmdAgentTab: {"cmd.agentTab.label", "cmd.agentTab.desc", "cmd.category.view"}, - CmdInspectorTab: {"cmd.inspectorTab.label", "cmd.inspectorTab.desc", "cmd.category.view"}, - CmdCommandPalette: {"cmd.commandPalette.label", "cmd.commandPalette.desc", "cmd.category.view"}, - CmdShortcutsSheet: {"cmd.shortcutsSheet.label", "cmd.shortcutsSheet.desc", "cmd.category.view"}, - CmdToggleTasks: {"cmd.tasks.label", "cmd.tasks.desc", "cmd.category.view"}, - CmdHistoryPanel: {"cmd.historyPanel.label", "cmd.historyPanel.desc", "cmd.category.view"}, - CmdPlayStop: {"cmd.playStop.label", "cmd.playStop.desc", "cmd.category.project"}, - CmdPlayMark: {"cmd.playMark.label", "cmd.playMark.desc", "cmd.category.project"}, - CmdAskFrozenFrame: {"cmd.askFrozenFrame.label", "cmd.askFrozenFrame.desc", "cmd.category.project"}, - CmdRunGame: {"cmd.runGame.label", "cmd.runGame.desc", "cmd.category.project"}, - CmdProjectSettings: {"cmd.projectSettings.label", "cmd.projectSettings.desc", "cmd.category.project"}, - CmdAudioMixer: {"cmd.audioMixer.label", "cmd.audioMixer.desc", "cmd.category.project"}, - CmdLocalization: {"cmd.localization.label", "cmd.localization.desc", "cmd.category.project"}, - CmdMaterialEditor: {"cmd.materialEditor.label", "cmd.materialEditor.desc", "cmd.category.project"}, - CmdExport: {"cmd.export.label", "cmd.export.desc", "cmd.category.project"}, - CmdBuildRelease: {"cmd.buildRelease.label", "cmd.buildRelease.desc", "cmd.category.project"}, - CmdProfiler: {"cmd.profiler.label", "cmd.profiler.desc", "cmd.category.project"}, - CmdCheckProblems: {"cmd.checkProblems.label", "cmd.checkProblems.desc", "cmd.category.project"}, - CmdFindUsages: {"cmd.findUsages.label", "cmd.findUsages.desc", "cmd.category.project"}, - CmdEditorSettings: {"cmd.editorSettings.label", "cmd.editorSettings.desc", "cmd.category.file"}, - 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"}, - 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"}, - CmdReplayTips: {"cmd.replayTips.label", "cmd.replayTips.desc", "cmd.category.help"}, - CmdNewAgentThread: {"cmd.newAgentThread.label", "cmd.newAgentThread.desc", "cmd.category.agent"}, + CmdNewProject: {"cmd.newProject.label", "cmd.newProject.desc", "cmd.category.file"}, + CmdOpenProject: {"cmd.openProject.label", "cmd.openProject.desc", "cmd.category.file"}, + CmdStartScreen: {"cmd.startScreen.label", "cmd.startScreen.desc", "cmd.category.file"}, + CmdSave: {"cmd.save.label", "cmd.save.desc", "cmd.category.file"}, + CmdUndo: {"cmd.undo.label", "cmd.undo.desc", "cmd.category.edit"}, + CmdRedo: {"cmd.redo.label", "cmd.redo.desc", "cmd.category.edit"}, + CmdCopy: {"cmd.copy.label", "cmd.copy.desc", "cmd.category.edit"}, + CmdCut: {"cmd.cut.label", "cmd.cut.desc", "cmd.category.edit"}, + CmdPaste: {"cmd.paste.label", "cmd.paste.desc", "cmd.category.edit"}, + CmdPasteInto: {"cmd.pasteInto.label", "cmd.pasteInto.desc", "cmd.category.edit"}, + CmdDelete: {"cmd.delete.label", "cmd.delete.desc", "cmd.category.edit"}, + CmdDuplicate: {"cmd.duplicate.label", "cmd.duplicate.desc", "cmd.category.edit"}, + CmdGroup: {"cmd.group.label", "cmd.group.desc", "cmd.category.edit"}, + CmdUngroup: {"cmd.ungroup.label", "cmd.ungroup.desc", "cmd.category.edit"}, + CmdToolSelect: {"cmd.toolSelect.label", "cmd.toolSelect.desc", "cmd.category.tools"}, + CmdToolMove: {"cmd.toolMove.label", "cmd.toolMove.desc", "cmd.category.tools"}, + CmdToolPlace: {"cmd.toolPlace.label", "cmd.toolPlace.desc", "cmd.category.tools"}, + CmdToolPaintTile: {"cmd.toolPaintTile.label", "cmd.toolPaintTile.desc", "cmd.category.tools"}, + CmdToolEraseTile: {"cmd.toolEraseTile.label", "cmd.toolEraseTile.desc", "cmd.category.tools"}, + CmdToolFillTile: {"cmd.toolFillTile.label", "cmd.toolFillTile.desc", "cmd.category.tools"}, + CmdToolNavTestPath: {"cmd.toolNavTestPath.label", "cmd.toolNavTestPath.desc", "cmd.category.tools"}, + CmdGizmoTranslate: {"cmd.gizmoTranslate.label", "cmd.gizmoTranslate.desc", "cmd.category.gizmo3d"}, + CmdGizmoRotate: {"cmd.gizmoRotate.label", "cmd.gizmoRotate.desc", "cmd.category.gizmo3d"}, + CmdGizmoScale: {"cmd.gizmoScale.label", "cmd.gizmoScale.desc", "cmd.category.gizmo3d"}, + CmdGizmoSpace3D: {"cmd.gizmoSpace3d.label", "cmd.gizmoSpace3d.desc", "cmd.category.gizmo3d"}, + CmdView2D: {"cmd.view2d.label", "cmd.view2d.desc", "cmd.category.view"}, + CmdView3D: {"cmd.view3d.label", "cmd.view3d.desc", "cmd.category.view"}, + CmdShadingLit: {"cmd.shadingLit.label", "cmd.shadingLit.desc", "cmd.category.view"}, + CmdShadingUnlit: {"cmd.shadingUnlit.label", "cmd.shadingUnlit.desc", "cmd.category.view"}, + CmdShadingWire: {"cmd.shadingWire.label", "cmd.shadingWire.desc", "cmd.category.view"}, + CmdNavMeshPanel: {"cmd.navMeshPanel.label", "cmd.navMeshPanel.desc", "cmd.category.view"}, + CmdNavMeshOverlay: {"cmd.navMeshOverlay.label", "cmd.navMeshOverlay.desc", "cmd.category.view"}, + CmdBakeNavMesh3D: {"cmd.bakeNavMesh3d.label", "cmd.bakeNavMesh3d.desc", "cmd.category.project"}, + CmdFrameSelection: {"cmd.frameSelection.label", "cmd.frameSelection.desc", "cmd.category.view"}, + CmdView3DOrthographic: {"cmd.view3dOrtho.label", "cmd.view3dOrtho.desc", "cmd.category.view"}, + CmdToggleLightingPreview: {"cmd.lightingPreview.label", "cmd.lightingPreview.desc", "cmd.category.view"}, + CmdToggleNavMesh2D: {"cmd.navMesh2dOverlay.label", "cmd.navMesh2dOverlay.desc", "cmd.category.view"}, + CmdAskAgent: {"cmd.askAgent.label", "cmd.askAgent.desc", "cmd.category.view"}, + CmdAgentTab: {"cmd.agentTab.label", "cmd.agentTab.desc", "cmd.category.view"}, + CmdInspectorTab: {"cmd.inspectorTab.label", "cmd.inspectorTab.desc", "cmd.category.view"}, + CmdCommandPalette: {"cmd.commandPalette.label", "cmd.commandPalette.desc", "cmd.category.view"}, + CmdShortcutsSheet: {"cmd.shortcutsSheet.label", "cmd.shortcutsSheet.desc", "cmd.category.view"}, + CmdToggleTasks: {"cmd.tasks.label", "cmd.tasks.desc", "cmd.category.view"}, + CmdHistoryPanel: {"cmd.historyPanel.label", "cmd.historyPanel.desc", "cmd.category.view"}, + CmdPlayStop: {"cmd.playStop.label", "cmd.playStop.desc", "cmd.category.project"}, + CmdPlayMark: {"cmd.playMark.label", "cmd.playMark.desc", "cmd.category.project"}, + CmdAskFrozenFrame: {"cmd.askFrozenFrame.label", "cmd.askFrozenFrame.desc", "cmd.category.project"}, + CmdRunGame: {"cmd.runGame.label", "cmd.runGame.desc", "cmd.category.project"}, + CmdProjectSettings: {"cmd.projectSettings.label", "cmd.projectSettings.desc", "cmd.category.project"}, + CmdAudioMixer: {"cmd.audioMixer.label", "cmd.audioMixer.desc", "cmd.category.project"}, + CmdLocalization: {"cmd.localization.label", "cmd.localization.desc", "cmd.category.project"}, + CmdMaterialEditor: {"cmd.materialEditor.label", "cmd.materialEditor.desc", "cmd.category.project"}, + CmdExport: {"cmd.export.label", "cmd.export.desc", "cmd.category.project"}, + CmdBuildRelease: {"cmd.buildRelease.label", "cmd.buildRelease.desc", "cmd.category.project"}, + CmdProfiler: {"cmd.profiler.label", "cmd.profiler.desc", "cmd.category.project"}, + CmdCheckProblems: {"cmd.checkProblems.label", "cmd.checkProblems.desc", "cmd.category.project"}, + CmdFindUsages: {"cmd.findUsages.label", "cmd.findUsages.desc", "cmd.category.project"}, + CmdEditorSettings: {"cmd.editorSettings.label", "cmd.editorSettings.desc", "cmd.category.file"}, + 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"}, + 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"}, + CmdReplayTips: {"cmd.replayTips.label", "cmd.replayTips.desc", "cmd.category.help"}, + CmdNewAgentThread: {"cmd.newAgentThread.label", "cmd.newAgentThread.desc", "cmd.category.agent"}, + CmdSketchToggle: {"cmd.sketchToggle.label", "cmd.sketchToggle.desc", "cmd.category.tools"}, + CmdSketchToolPen: {"cmd.sketchToolPen.label", "cmd.sketchToolPen.desc", "cmd.category.tools"}, + CmdSketchToolArrow: {"cmd.sketchToolArrow.label", "cmd.sketchToolArrow.desc", "cmd.category.tools"}, + CmdSketchToolBox: {"cmd.sketchToolBox.label", "cmd.sketchToolBox.desc", "cmd.category.tools"}, + CmdSketchToolText: {"cmd.sketchToolText.label", "cmd.sketchToolText.desc", "cmd.category.tools"}, + CmdSketchAddMarkAtCursor: {"cmd.sketchAddMark.label", "cmd.sketchAddMark.desc", "cmd.category.tools"}, + CmdSketchUndoMark: {"cmd.sketchUndoMark.label", "cmd.sketchUndoMark.desc", "cmd.category.edit"}, + CmdSketchToggleMarks: {"cmd.sketchToggleMarks.label", "cmd.sketchToggleMarks.desc", "cmd.category.view"}, + CmdSketchClear: {"cmd.sketchClear.label", "cmd.sketchClear.desc", "cmd.category.edit"}, + CmdSketchDone: {"cmd.sketchDone.label", "cmd.sketchDone.desc", "cmd.category.tools"}, + CmdSketchSend: {"cmd.sketchSend.label", "cmd.sketchSend.desc", "cmd.category.tools"}, + CmdSketchApproveReading: {"cmd.sketchApproveReading.label", "cmd.sketchApproveReading.desc", "cmd.category.tools"}, + CmdSketchCorrectMark: {"cmd.sketchCorrectMark.label", "cmd.sketchCorrectMark.desc", "cmd.category.tools"}, + CmdSketchToggleReviewOverlay: {"cmd.sketchReviewOverlay.label", "cmd.sketchReviewOverlay.desc", "cmd.category.view"}, + CmdSketchKeepReview: {"cmd.sketchKeepReview.label", "cmd.sketchKeepReview.desc", "cmd.category.edit"}, + CmdSketchRevertReview: {"cmd.sketchRevertReview.label", "cmd.sketchRevertReview.desc", "cmd.category.edit"}, } // Commands returns all currently active commands in deterministic order: diff --git a/packages/game/editor/editorcmd/sketch_screenshot_test.go b/packages/game/editor/editorcmd/sketch_screenshot_test.go new file mode 100644 index 000000000..8c175c7eb --- /dev/null +++ b/packages/game/editor/editorcmd/sketch_screenshot_test.go @@ -0,0 +1,114 @@ +package editorcmd_test + +import ( + "testing" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +const macosSketchPreviewScene = `version: 3 +name: level_01 +virtualWidth: 640 +virtualHeight: 360 +backgroundColor: "#15181D" +layers: + - name: Actors + space: world + order: 0 + objects: + - id: floor + name: Floor + x: 320 + y: 300 + - id: knight + name: Knight + x: 112 + y: 238 + z: 10 + - id: plank + name: Plank + x: 342 + y: 215 + - id: door + name: Door + x: 522 + y: 248 +` + +// TestSketchMacOSScreenshots renders real native macOS screenshots of the viewport sketch layer +// (active numbered marks + floating bar + Scene Tree SKETCH LAYER + Composer preview), +// the agent reading card (with Go ahead / Correct a mark + warning assumptions), +// and the post-sketch review card (with Sketch overlay toggle + Keep / Revert) +// for visual verification beside docs/design/editor/Sketch.dc.html and Spec.dc.html (#1025). +func TestSketchMacOSScreenshots(t *testing.T) { + doc, err := sceneformat.Parse([]byte(macosSketchPreviewScene)) + if err != nil { + t.Fatalf("sceneformat.Parse: %v", err) + } + ed, err := editor.New(doc, nil) + if err != nil { + t.Fatalf("editor.New: %v", err) + } + _ = ed.SetAppearance(editor.AppearanceDark) + ed.SetView2D(editor.View2D{X: 320, Y: 180, Zoom: 1.0}) + ed.StartSketch() + ed.AddSketchBox(171, 240, 109, 36, "3 spikes") + ed.AddSketchPen([]editor.SketchPoint{ + {X: 390, Y: 165}, + {X: 430, Y: 152}, + {X: 470, Y: 174}, + {X: 510, Y: 158}, + {X: 550, Y: 168}, + }, "platform, back and forth") + ed.AddSketchArrow(450, 108, 522, 245, "locked until the lever") + ed.SelectSketchMark(0) + ed.SetSketchTool(editor.SketchToolArrow) + ed.SetSketchPromptDraft("Build what I sketched. Spikes should look like the reference image.") + ed.SetSketchPreviewOpen(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: true, + Locale: "en-US", + })) + + app.Screenshot("sketch-active") + + // State 2: Sent sketch + agent reading card with Go ahead / Correct a mark. + app.Post(func() { + _, _ = ed.SendSketch("Build what I sketched. Spikes should look like the reference image.") + _ = ed.PostSketchReading(editor.SketchReading{ + Summary: "I read your sketch as:", + Items: []editor.SketchReadingItem{ + {Number: 1, Mark: "Box · “3 spikes”", Text: "Three spike tiles on the floor from x 171 to 280, using prefabs/spikes.prefab.yaml, 1 damage each."}, + {Number: 2, Mark: "Line · “platform, back and forth”", Text: "A new moving_platform, 64 px wide, going back and forth between x 390 and 550 at 40 px/s."}, + {Number: 3, Mark: "Arrow at Door · “locked until the lever”", Text: "Door stays locked until lever_01 is pulled once."}, + }, + Assumptions: []string{ + "There is no lever in level_01 yet. I will add lever_01 left of the plank at x 295 unless you point somewhere else.", + }, + }) + }) + app.Settle() + + app.Screenshot("sketch-reading") + + // State 3: Review with Sketch overlay toggle + Keep / Revert. + app.Post(func() { + _ = ed.ApproveSketchReading() + s1, _ := ed.PlaceObject("Actors", sceneformat.ObjectDoc{ID: "spikes_01", Name: "spikes_01", X: 225, Y: 258}) + p1, _ := ed.PlaceObject("Actors", sceneformat.ObjectDoc{ID: "moving_platform", Name: "moving_platform", X: 465, Y: 165}) + l1, _ := ed.PlaceObject("Actors", sceneformat.ObjectDoc{ID: "lever_01", Name: "lever_01", X: 295, Y: 280}) + _ = ed.SetProperty("door", "locked_until", "lever_01") + ed.RecordSketchReviewEdits("Agent: build sketch", []string{s1, p1, l1}, []string{"door"}, nil) + }) + app.Settle() + + app.Screenshot("sketch-review") +} diff --git a/packages/game/editor/editormcp/edit.go b/packages/game/editor/editormcp/edit.go index 685e823a4..3f42acadc 100644 --- a/packages/game/editor/editormcp/edit.go +++ b/packages/game/editor/editormcp/edit.go @@ -157,6 +157,9 @@ func sceneEdit(ctx context.Context, c *Call) (*Result, error) { if ed.Playing() { return &EditError{File: name, Problem: "the scene is playing in the editor, which refuses edits", Fix: "ask the person to stop playing, then edit"} } + if holdErr := sketchHoldEditError(ed, name); holdErr != nil { + return holdErr + } if c.taskID != "" { c.s.captureTaskBeforeYAML(c.taskID, ed) } @@ -183,7 +186,7 @@ func sceneEdit(ctx context.Context, c *Call) (*Result, error) { if title == "" { title = label } - var editedIDs []string + var editedIDs, changedIDs, removedIDs []string err := ed.RecordAgentTurn(editor.AgentTurnOptions{ Title: title, UndoLabel: label, @@ -198,8 +201,12 @@ func sceneEdit(ctx context.Context, c *Call) (*Result, error) { if id != "" { res.Objects = append(res.Objects, id) editedIDs = append(editedIDs, id) + } else if e.Op == "remove" && e.ID != "" { + editedIDs = append(editedIDs, e.ID) + removedIDs = append(removedIDs, e.ID) } else if e.ID != "" { editedIDs = append(editedIDs, e.ID) + changedIDs = append(changedIDs, e.ID) } } return nil @@ -210,6 +217,9 @@ func sceneEdit(ctx context.Context, c *Call) (*Result, error) { if len(editedIDs) > 0 { ed.NoteAgentEditedObjects(editedIDs, []string{scenePath(ed, root)}, label) } + if ed.SketchApproved() { + ed.RecordSketchReviewEdits(label, res.Objects, changedIDs, removedIDs) + } return nil }) if err != nil { diff --git a/packages/game/editor/editormcp/example_test.go b/packages/game/editor/editormcp/example_test.go index eb12cb9d2..f681cbe90 100644 --- a/packages/game/editor/editormcp/example_test.go +++ b/packages/game/editor/editormcp/example_test.go @@ -127,6 +127,8 @@ func ExampleServer_AddTool() { // scene_name read // scene_read read // selection_get read + // sketch_read read + // sketch_reading edit // states_test run // states_write edit // tasks_control edit diff --git a/packages/game/editor/editormcp/inspector.go b/packages/game/editor/editormcp/inspector.go index 218d455d4..67b2098a2 100644 --- a/packages/game/editor/editormcp/inspector.go +++ b/packages/game/editor/editormcp/inspector.go @@ -120,6 +120,9 @@ func objectSetField(ctx context.Context, c *Call) (*Result, error) { if ed.Playing() { return &EditError{File: name, Problem: "the scene is playing in the editor, which refuses edits", Fix: "stop playing first"} } + if holdErr := sketchHoldEditError(ed, name); holdErr != nil { + return holdErr + } targetID := args.ID if targetID == "" { targetID = ed.SelectedID diff --git a/packages/game/editor/editormcp/object_menu.go b/packages/game/editor/editormcp/object_menu.go index 625f7781c..b44f7f1ff 100644 --- a/packages/game/editor/editormcp/object_menu.go +++ b/packages/game/editor/editormcp/object_menu.go @@ -234,6 +234,9 @@ func objectPasteYAML(ctx context.Context, c *Call) (*Result, error) { var sceneFile string err := c.Editor(ctx, func(ed *editor.Editor) error { sceneFile = sceneName(ed, projectRoot(ed)) + if holdErr := sketchHoldEditError(ed, sceneFile); holdErr != nil { + return holdErr + } if c.taskID != "" { c.s.captureTaskBeforeYAML(c.taskID, ed) } @@ -314,6 +317,9 @@ func objectDuplicate(ctx context.Context, c *Call) (*Result, error) { var sceneFile string err := c.Editor(ctx, func(ed *editor.Editor) error { sceneFile = sceneName(ed, projectRoot(ed)) + if holdErr := sketchHoldEditError(ed, sceneFile); holdErr != nil { + return holdErr + } if c.taskID != "" { c.s.captureTaskBeforeYAML(c.taskID, ed) } @@ -391,6 +397,9 @@ func objectGroup(ctx context.Context, c *Call) (*Result, error) { var sceneFile string err := c.Editor(ctx, func(ed *editor.Editor) error { sceneFile = sceneName(ed, projectRoot(ed)) + if holdErr := sketchHoldEditError(ed, sceneFile); holdErr != nil { + return holdErr + } if c.taskID != "" { c.s.captureTaskBeforeYAML(c.taskID, ed) } @@ -505,6 +514,9 @@ func objectMoveUnder(ctx context.Context, c *Call) (*Result, error) { return nil } sceneFile = sceneName(ed, projectRoot(ed)) + if holdErr := sketchHoldEditError(ed, sceneFile); holdErr != nil { + return holdErr + } if c.taskID != "" { c.s.captureTaskBeforeYAML(c.taskID, ed) } diff --git a/packages/game/editor/editormcp/proxy_test.go b/packages/game/editor/editormcp/proxy_test.go index 6394f85d9..d671c5b43 100644 --- a/packages/game/editor/editormcp/proxy_test.go +++ b/packages/game/editor/editormcp/proxy_test.go @@ -62,7 +62,7 @@ func TestProxyFindsTheEditor(t *testing.T) { } }}, "") - if names := listNames(t, cs); !slices.Equal(names, []string{"agent_turn_get", "agent_turn_reply", "brief_edit", "cutscene_scrub", "cutscene_write", "datatable_review_checks", "datatable_review_propose", "datatable_review_status", "game_check", "game_playtest", "history_list", "merge_abort", "merge_finish", "merge_resolve", "merge_status", "object_copy_yaml", "object_duplicate", "object_find_usages", "object_group", "object_locate_yaml", "object_move_under", "object_paste_yaml", "object_select_same_prefab", "object_set_field", "object_visibility", "permissions_draft", "play_frozen_context", "play_replay_step", "playtest_define", "playtest_report", "problem_propose_fix", "project_context", "refactor_rename", "refs_find", "release_notes_draft", "release_review_uploads", "review_notes_get", "review_redo", "review_status", "rules_edit", "scene_edit", "scene_read", "selection_get", "states_test", "states_write", "tasks_control", "tasks_list", "tasks_submit", "tile_autotile", "tile_erase", "tile_paint", "tile_query", "tile_review_keep", "tile_review_restore_region", "tile_review_revert_all", "tile_review_revert_region", "tile_review_status", "tileset_edit", "tileset_read", "viewport_image"}) { + if names := listNames(t, cs); !slices.Equal(names, []string{"agent_turn_get", "agent_turn_reply", "brief_edit", "cutscene_scrub", "cutscene_write", "datatable_review_checks", "datatable_review_propose", "datatable_review_status", "game_check", "game_playtest", "history_list", "merge_abort", "merge_finish", "merge_resolve", "merge_status", "object_copy_yaml", "object_duplicate", "object_find_usages", "object_group", "object_locate_yaml", "object_move_under", "object_paste_yaml", "object_select_same_prefab", "object_set_field", "object_visibility", "permissions_draft", "play_frozen_context", "play_replay_step", "playtest_define", "playtest_report", "problem_propose_fix", "project_context", "refactor_rename", "refs_find", "release_notes_draft", "release_review_uploads", "review_notes_get", "review_redo", "review_status", "rules_edit", "scene_edit", "scene_read", "selection_get", "sketch_read", "sketch_reading", "states_test", "states_write", "tasks_control", "tasks_list", "tasks_submit", "tile_autotile", "tile_erase", "tile_paint", "tile_query", "tile_review_keep", "tile_review_restore_region", "tile_review_revert_all", "tile_review_revert_region", "tile_review_status", "tileset_edit", "tileset_read", "viewport_image"}) { t.Fatalf("tools without an editor: %v", names) } res := call(t, cs, editormcp.ToolSceneRead, nil) diff --git a/packages/game/editor/editormcp/server_test.go b/packages/game/editor/editormcp/server_test.go index 56599e2d1..647eb4de2 100644 --- a/packages/game/editor/editormcp/server_test.go +++ b/packages/game/editor/editormcp/server_test.go @@ -39,7 +39,7 @@ func TestServerListsToolsAndResources(t *testing.T) { } } slices.Sort(names) - want := []string{"agent_turn_get", "agent_turn_reply", "brief_edit", "cutscene_scrub", "cutscene_write", "datatable_review_checks", "datatable_review_propose", "datatable_review_status", "game_check", "game_playtest", "history_list", "merge_abort", "merge_finish", "merge_resolve", "merge_status", "object_copy_yaml", "object_duplicate", "object_find_usages", "object_group", "object_locate_yaml", "object_move_under", "object_paste_yaml", "object_select_same_prefab", "object_set_field", "object_visibility", "permissions_draft", "play_frozen_context", "play_replay_step", "playtest_define", "playtest_report", "problem_propose_fix", "project_context", "refactor_rename", "refs_find", "release_notes_draft", "release_review_uploads", "review_notes_get", "review_redo", "review_status", "rules_edit", "scene_edit", "scene_read", "selection_get", "states_test", "states_write", "tasks_control", "tasks_list", "tasks_submit", "tile_autotile", "tile_erase", "tile_paint", "tile_query", "tile_review_keep", "tile_review_restore_region", "tile_review_revert_all", "tile_review_revert_region", "tile_review_status", "tileset_edit", "tileset_read", "viewport_image"} + want := []string{"agent_turn_get", "agent_turn_reply", "brief_edit", "cutscene_scrub", "cutscene_write", "datatable_review_checks", "datatable_review_propose", "datatable_review_status", "game_check", "game_playtest", "history_list", "merge_abort", "merge_finish", "merge_resolve", "merge_status", "object_copy_yaml", "object_duplicate", "object_find_usages", "object_group", "object_locate_yaml", "object_move_under", "object_paste_yaml", "object_select_same_prefab", "object_set_field", "object_visibility", "permissions_draft", "play_frozen_context", "play_replay_step", "playtest_define", "playtest_report", "problem_propose_fix", "project_context", "refactor_rename", "refs_find", "release_notes_draft", "release_review_uploads", "review_notes_get", "review_redo", "review_status", "rules_edit", "scene_edit", "scene_read", "selection_get", "sketch_read", "sketch_reading", "states_test", "states_write", "tasks_control", "tasks_list", "tasks_submit", "tile_autotile", "tile_erase", "tile_paint", "tile_query", "tile_review_keep", "tile_review_restore_region", "tile_review_revert_all", "tile_review_revert_region", "tile_review_status", "tileset_edit", "tileset_read", "viewport_image"} if !slices.Equal(names, want) { t.Fatalf("tools = %v, want %v", names, want) } diff --git a/packages/game/editor/editormcp/sketch.go b/packages/game/editor/editormcp/sketch.go new file mode 100644 index 000000000..96d5d3de2 --- /dev/null +++ b/packages/game/editor/editormcp/sketch.go @@ -0,0 +1,222 @@ +package editormcp + +import ( + "context" + "fmt" + "strings" + + "github.com/nsgo-dev/game/packages/game/editor" +) + +// The names of the viewport sketch tools added to the editor's MCP server. +const ( + // ToolSketchRead reads the active/sent viewport sketch marks in scene coordinates and optional PNG image. + ToolSketchRead = "sketch_read" + // ToolSketchReading posts the agent's restatement of the user's sketch marks and assumptions before editing. + ToolSketchReading = "sketch_reading" +) + +const ( + sketchReadSchema = `{ + "type": "object", + "additionalProperties": false, + "properties": { + "includeImage": {"type": "boolean", "description": "Include a rendered PNG of the viewport with numbered sketch marks overlaid (defaults to true when marks exist)"}, + "scale": {"type": "number", "minimum": 0.25, "maximum": 4, "description": "Pixels per point for the viewport PNG; 1 when absent"} + } +}` + + sketchReadingSchema = `{ + "type": "object", + "additionalProperties": false, + "required": ["items"], + "properties": { + "summary": {"type": "string", "description": "Introductory heading shown on the reading card; defaults to \"I read your sketch as:\""}, + "items": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["number", "text"], + "properties": { + "number": {"type": "integer", "minimum": 1, "description": "1-based mark badge number from sketch_read"}, + "mark": {"type": "string", "description": "Optional short caption for the mark (for example 'Box · “3 spikes”'); derived from the mark when omitted"}, + "text": {"type": "string", "description": "Agent's restatement of what it will build for this mark"} + } + } + }, + "assumptions": { + "type": "array", + "items": {"type": "string"}, + "description": "Explicit assumptions or questions shown in a warning callout (for example where to add a missing lever)" + } + } +}` +) + +func sketchTools() []Tool { + return []Tool{ + { + Name: ToolSketchRead, + Title: "Read the viewport sketch", + Description: "Read the person's numbered viewport sketch marks (Pen, Arrow, Box, Text) with exact scene coordinates, labels, prompt, hold state, and an optional PNG of the viewport with the numbered marks overlaid.", + InputSchema: []byte(sketchReadSchema), + Action: ActionRead, + Handler: sketchRead, + }, + { + Name: ToolSketchReading, + Title: "Post a reading of the viewport sketch", + Description: "Post the agent's restatement of each numbered sketch mark (\"I read your sketch as: …\") and any assumptions to the editor's reading card. While a sent sketch is awaiting confirmation, scene_edit and other mutating scene tools hold until the person chooses Go ahead, Correct a mark, or replies in words.", + InputSchema: []byte(sketchReadingSchema), + Action: ActionEdit, + Handler: sketchReading, + }, + } +} + +// SketchReadResult is the structured payload returned by sketch_read. +type SketchReadResult struct { + Scene string `json:"scene"` + Active bool `json:"active"` + HoldState string `json:"holdState"` + HoldActive bool `json:"holdActive"` + ChipLabel string `json:"chipLabel,omitempty"` + Prompt string `json:"prompt,omitempty"` + SelectedMark int `json:"selectedMark,omitempty"` + View editor.View2D `json:"view"` + Marks []editor.SketchMark `json:"marks"` + Reading *editor.SketchReading `json:"reading,omitempty"` + Width int `json:"width,omitempty"` + Height int `json:"height,omitempty"` +} + +func sketchRead(ctx context.Context, c *Call) (*Result, error) { + var args struct { + IncludeImage *bool `json:"includeImage"` + Scale float64 `json:"scale"` + } + if err := c.Decode(&args); err != nil { + return nil, fmt.Errorf("sketch_read: %w", err) + } + scale := args.Scale + if scale == 0 { + scale = 1 + } + if !(scale >= 0.25 && scale <= 4) { + return nil, fmt.Errorf("sketch_read: scale %v must be between 0.25 and 4", args.Scale) + } + + var ( + out SketchReadResult + pngBytes []byte + ) + if err := c.Editor(ctx, func(ed *editor.Editor) error { + root := projectRoot(ed) + marks := ed.SketchMarks() + out = SketchReadResult{ + Scene: sceneName(ed, root), + Active: ed.SketchActive(), + HoldState: string(ed.SketchHoldState()), + HoldActive: ed.SketchHoldActive(), + SelectedMark: ed.SelectedSketchMark(), + View: ed.View2D(), + Marks: marks, + Reading: ed.SketchReading(), + } + if len(marks) > 0 { + out.ChipLabel = ed.SketchChipLabel() + } + if req, ok := ed.LastSketchRequest(); ok { + out.Prompt = req.Prompt + } else if draft := strings.TrimSpace(ed.SketchPromptDraft()); draft != "" { + out.Prompt = draft + } + wantImg := len(marks) > 0 + if args.IncludeImage != nil { + wantImg = *args.IncludeImage + } + if wantImg { + b, w, h, err := ed.RenderSketchViewportPNG(float32(scale)) + if err != nil { + return fmt.Errorf("sketch_read: %w", err) + } + pngBytes = b + out.Width, out.Height = w, h + } + return nil + }); err != nil { + return nil, err + } + + var b strings.Builder + if len(out.Marks) == 0 { + fmt.Fprintf(&b, "No sketch marks on %s (hold: %s).\n", out.Scene, out.HoldState) + } else { + fmt.Fprintf(&b, "%s on %s (scene coordinates, hold: %s):\n", out.ChipLabel, out.Scene, out.HoldState) + if out.Prompt != "" { + fmt.Fprintf(&b, "Prompt: %s\n", out.Prompt) + } + for _, m := range out.Marks { + fmt.Fprintf(&b, "%d. %s", m.Number, m.GeometrySummary()) + if m.Label != "" { + fmt.Fprintf(&b, " — %q", m.Label) + } + b.WriteByte('\n') + } + } + return &Result{Text: b.String(), Structured: out, PNG: pngBytes}, nil +} + +// SketchReadingResult is the structured payload returned by sketch_reading. +type SketchReadingResult struct { + Scene string `json:"scene"` + HoldState string `json:"holdState"` + HoldActive bool `json:"holdActive"` + Reading *editor.SketchReading `json:"reading"` +} + +func sketchReading(ctx context.Context, c *Call) (*Result, error) { + var args struct { + Summary string `json:"summary"` + Items []editor.SketchReadingItem `json:"items"` + Assumptions []string `json:"assumptions"` + } + if err := c.Decode(&args); err != nil { + return nil, fmt.Errorf("sketch_reading: %w", err) + } + var out SketchReadingResult + if err := c.Editor(ctx, func(ed *editor.Editor) error { + if err := ed.PostSketchReading(editor.SketchReading{ + Summary: args.Summary, + Items: args.Items, + Assumptions: args.Assumptions, + }); err != nil { + return err + } + out = SketchReadingResult{ + Scene: sceneName(ed, projectRoot(ed)), + HoldState: string(ed.SketchHoldState()), + HoldActive: ed.SketchHoldActive(), + Reading: ed.SketchReading(), + } + return nil + }); err != nil { + return nil, fmt.Errorf("sketch_reading: %w", err) + } + text := fmt.Sprintf("Posted sketch reading for %d mark(s) on %s. Scene edits remain held until the person chooses Go ahead, Correct a mark, or replies in words.", len(out.Reading.Items), out.Scene) + return &Result{Text: text, Structured: out}, nil +} + +// sketchHoldEditError returns a refusal error when a sent sketch is awaiting user confirmation. +func sketchHoldEditError(ed *editor.Editor, file string) *EditError { + if ed == nil || !ed.SketchHoldActive() { + return nil + } + return &EditError{ + File: file, + Problem: "a sent viewport sketch is waiting for the person to confirm before editing the scene", + Fix: "post your restatement with sketch_reading and wait for the person to choose Go ahead or reply before editing", + } +} diff --git a/packages/game/editor/editormcp/sketch_test.go b/packages/game/editor/editormcp/sketch_test.go new file mode 100644 index 000000000..01ef2bf71 --- /dev/null +++ b/packages/game/editor/editormcp/sketch_test.go @@ -0,0 +1,196 @@ +package editormcp_test + +import ( + "bytes" + "image/png" + "math" + "strings" + "testing" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/editor/editormcp" +) + +// #1025 Acceptance: End-to-end scripted MCP agent flow over sketch_read, sketch_reading, +// scene_edit hold gate until Go ahead, Correct a mark, two zoom levels, Keep vs Revert, +// and verifying scene YAML never persists sketch marks. +func TestSketchMCPReadReadingHoldGateAndKeepRevert(t *testing.T) { + f := openFixture(t) + f.ed.SetCanvasSize(640, 360) + s := editormcp.New(f.ed, editormcp.Options{}) + t.Cleanup(func() { _ = s.Close() }) + cs := connect(t, s, nil) + + initialYAML, err := f.ed.SaveYAML() + if err != nil { + t.Fatalf("SaveYAML: %v", err) + } + + // Draw Box, Arrow, and Text marks at Zoom 1.0, then send. + f.ed.SetView2D(editor.View2D{X: 320, Y: 180, Zoom: 1.0}) + f.ed.StartSketch() + f.ed.SetSketchTool(editor.SketchToolBox) + f.ed.BeginSketchDrag(180, 220) + f.ed.UpdateSketchDrag(290, 260) + f.ed.EndSketchDrag() + f.ed.SetSketchMarkLabel(1, "3 spikes") + + f.ed.SetSketchTool(editor.SketchToolArrow) + f.ed.BeginSketchDrag(410, 120) + f.ed.UpdateSketchDrag(490, 240) + f.ed.EndSketchDrag() + f.ed.SetSketchMarkLabel(2, "locked until the lever") + + f.ed.SetSketchTool(editor.SketchToolText) + f.ed.BeginSketchDrag(340, 150) + f.ed.EndSketchDrag() + f.ed.SetSketchMarkLabel(3, "platform, back and forth") + + if _, err := f.ed.SendSketch("Build what I sketched."); err != nil { + t.Fatalf("SendSketch: %v", err) + } + + // 1. Agent reads the sketch via sketch_read and gets exact scene coordinates + PNG. + readRes := call(t, cs, editormcp.ToolSketchRead, map[string]any{}) + readText := mustOK(t, readRes) + var sr editormcp.SketchReadResult + structured(t, readRes, &sr) + if len(sr.Marks) != 3 || sr.HoldState != "pending" || !sr.HoldActive { + t.Fatalf("sketch_read = %+v\n%s", sr, readText) + } + if sr.ChipLabel != "Sketch · 3 marks" || sr.Prompt != "Build what I sketched." { + t.Fatalf("sketch_read chip/prompt = %q / %q", sr.ChipLabel, sr.Prompt) + } + bx0, by0 := f.ed.CanvasToWorld(180, 220) + if math.Abs(float64(sr.Marks[0].Rect.X-bx0)) > 0.01 || math.Abs(float64(sr.Marks[0].Rect.Y-by0)) > 0.01 { + t.Fatalf("zoom 1 box scene coords = %+v, want (%v, %v)", sr.Marks[0].Rect, bx0, by0) + } + var gotPNG []byte + for _, content := range readRes.Content { + if ic, ok := content.(*mcp.ImageContent); ok && ic.MIMEType == "image/png" { + gotPNG = ic.Data + } + } + if len(gotPNG) == 0 { + t.Fatal("sketch_read did not return a PNG image") + } + if _, err := png.Decode(bytes.NewReader(gotPNG)); err != nil { + t.Fatalf("sketch_read returned invalid PNG: %v", err) + } + + // Verify coordinates stay identical in scene space after zooming viewport to 2.0x. + f.ed.SetView2D(editor.View2D{X: 380, Y: 200, Zoom: 2.0}) + readRes2 := call(t, cs, editormcp.ToolSketchRead, map[string]any{}) + mustOK(t, readRes2) + var sr2 editormcp.SketchReadResult + structured(t, readRes2, &sr2) + if math.Abs(float64(sr2.Marks[0].Rect.X-bx0)) > 0.01 || math.Abs(float64(sr2.Marks[0].Rect.Y-by0)) > 0.01 { + t.Fatalf("zoom 2 box scene coords drifted: %+v vs (%v, %v)", sr2.Marks[0].Rect, bx0, by0) + } + + // 2. scene_edit MUST hold/refuse while the sent sketch is awaiting confirmation. + editArgs := map[string]any{ + "edits": []any{ + map[string]any{"op": "add", "layer": "actors", "object": map[string]any{"id": "spikes_1", "x": 235, "y": 240}}, + }, + } + if res := call(t, cs, editormcp.ToolSceneEdit, editArgs); !res.IsError || !strings.Contains(text(res), "sketch") { + t.Fatalf("scene_edit while sketch pending = (%v, %q), want hold error", res.IsError, text(res)) + } + if obj, _, _ := f.ed.FindObject("spikes_1"); obj != nil { + t.Fatal("held scene_edit mutated the scene") + } + // Other mutating scene MCP tools must also refuse while held. + if res := call(t, cs, editormcp.ToolObjectDuplicate, map[string]any{"id": "hero"}); !res.IsError || !strings.Contains(text(res), "sketch") { + t.Fatalf("object_duplicate while sketch pending = (%v, %q), want hold error", res.IsError, text(res)) + } + + // 3. Agent posts its reading card via sketch_reading. + readingRes := call(t, cs, editormcp.ToolSketchReading, map[string]any{ + "items": []any{ + map[string]any{"number": 1, "text": "Place three spike tiles at x 180..290."}, + map[string]any{"number": 2, "text": "Lock the door until lever_01 is pulled."}, + map[string]any{"number": 3, "text": "Add a moving platform around (340, 150)."}, + }, + "assumptions": []string{ + "There is no lever in the scene yet; I will add lever_01 at x 295 unless you point elsewhere.", + }, + }) + mustOK(t, readingRes) + var rOut editormcp.SketchReadingResult + structured(t, readingRes, &rOut) + if rOut.HoldState != "reading" || !rOut.HoldActive || rOut.Reading == nil || len(rOut.Reading.Items) != 3 { + t.Fatalf("sketch_reading result = %+v", rOut) + } + + // scene_edit MUST STILL hold after reading is posted, until user clicks Go ahead! + if res := call(t, cs, editormcp.ToolSceneEdit, editArgs); !res.IsError || !strings.Contains(text(res), "sketch") { + t.Fatalf("scene_edit before Go ahead = (%v, %q), want hold error", res.IsError, text(res)) + } + + // 4. Correct a mark reopens sketch mode with mark 2 selected and keeps hold active. + if err := f.ed.CorrectSketchMark(2); err != nil { + t.Fatalf("CorrectSketchMark(2): %v", err) + } + if !f.ed.SketchActive() || f.ed.SelectedSketchMark() != 2 || !f.ed.SketchHoldActive() { + t.Fatalf("after CorrectSketchMark(2): active=%v sel=%d hold=%v", f.ed.SketchActive(), f.ed.SelectedSketchMark(), f.ed.SketchHoldActive()) + } + if res := call(t, cs, editormcp.ToolSceneEdit, editArgs); !res.IsError { + t.Fatalf("scene_edit while correcting mark succeeded, want hold error") + } + + // 5. User clicks Go ahead -> scene_edit succeeds and opens Sketch Review. + if err := f.ed.ApproveSketchReading(); err != nil { + t.Fatalf("ApproveSketchReading: %v", err) + } + mustOK(t, call(t, cs, editormcp.ToolSceneEdit, editArgs)) + if obj, _, _ := f.ed.FindObject("spikes_1"); obj == nil { + t.Fatal("scene_edit after Go ahead did not add spikes_1") + } + if !f.ed.SketchReviewOpen() || !f.ed.SketchReviewOverlayVisible() { + t.Fatalf("after approved scene_edit: reviewOpen=%v overlay=%v, want true/true", f.ed.SketchReviewOpen(), f.ed.SketchReviewOverlayVisible()) + } + + // 6. Revert undoes spikes_1 AND keeps all 3 sketch marks! + if err := f.ed.RevertSketchReview(); err != nil { + t.Fatalf("RevertSketchReview: %v", err) + } + if obj, _, _ := f.ed.FindObject("spikes_1"); obj != nil { + t.Fatal("RevertSketchReview did not remove spikes_1") + } + if f.ed.SketchMarkCount() != 3 { + t.Fatalf("RevertSketchReview cleared marks: got %d, want 3", f.ed.SketchMarkCount()) + } + // Scene YAML matches initial cleanly after Revert. + revertedYAML, err := f.ed.SaveYAML() + if err != nil { + t.Fatalf("SaveYAML after revert: %v", err) + } + if !bytes.Equal(initialYAML, revertedYAML) { + t.Fatalf("scene YAML after revert differs from initial:\n%s", string(revertedYAML)) + } + + // 7. Approve again, apply edit, Keep -> retains spikes_1 AND clears sketch layer; scene YAML never contains sketch data. + if err := f.ed.ApproveSketchReading(); err != nil { + t.Fatalf("ApproveSketchReading 2: %v", err) + } + mustOK(t, call(t, cs, editormcp.ToolSceneEdit, editArgs)) + if err := f.ed.KeepSketchReview(); err != nil { + t.Fatalf("KeepSketchReview: %v", err) + } + if obj, _, _ := f.ed.FindObject("spikes_1"); obj == nil { + t.Fatal("KeepSketchReview lost spikes_1") + } + if f.ed.SketchMarkCount() != 0 { + t.Fatalf("KeepSketchReview did not clear sketch marks: got %d", f.ed.SketchMarkCount()) + } + keptYAML, err := f.ed.SaveYAML() + if err != nil { + t.Fatalf("SaveYAML after keep: %v", err) + } + if strings.Contains(string(keptYAML), "locked until the lever") || strings.Contains(string(keptYAML), "sketch") { + t.Fatalf("kept scene YAML contains sketch data:\n%s", string(keptYAML)) + } +} diff --git a/packages/game/editor/editormcp/tiles.go b/packages/game/editor/editormcp/tiles.go index bb4df5fe2..69e06d4db 100644 --- a/packages/game/editor/editormcp/tiles.go +++ b/packages/game/editor/editormcp/tiles.go @@ -597,6 +597,9 @@ func tilePaint(ctx context.Context, c *Call) (*Result, error) { } var res editor.AgentTileEditResult if err := c.Editor(ctx, func(ed *editor.Editor) error { + if holdErr := sketchHoldEditError(ed, sceneName(ed, projectRoot(ed))); holdErr != nil { + return holdErr + } var err error res, err = ed.AgentPaintTiles(req) return err @@ -661,6 +664,9 @@ func tileAutotile(ctx context.Context, c *Call) (*Result, error) { } var res editor.AgentTileEditResult if err := c.Editor(ctx, func(ed *editor.Editor) error { + if holdErr := sketchHoldEditError(ed, sceneName(ed, projectRoot(ed))); holdErr != nil { + return holdErr + } var err error res, err = ed.AgentAutotile(req) return err @@ -721,6 +727,9 @@ func tileErase(ctx context.Context, c *Call) (*Result, error) { } var res editor.AgentTileEditResult if err := c.Editor(ctx, func(ed *editor.Editor) error { + if holdErr := sketchHoldEditError(ed, sceneName(ed, projectRoot(ed))); holdErr != nil { + return holdErr + } var err error res, err = ed.AgentEraseTiles(req) return err diff --git a/packages/game/editor/editormcp/tools.go b/packages/game/editor/editormcp/tools.go index 22807efb0..bb331052f 100644 --- a/packages/game/editor/editormcp/tools.go +++ b/packages/game/editor/editormcp/tools.go @@ -146,7 +146,7 @@ func builtinTools() []Tool { Target: tilesetEditTarget, Handler: tilesetEdit, }, - }, append(append(append(append(append(append(append(append(append(append(append(append(append(append(append(playtestTools(), mergeTools()...), refsTools()...), tileTools()...), inspectorTools()...), objectMenuTools()...), releaseTools()...), problemTools()...), playFrozenTools()...), agentTools()...), taskTools()...), contextTools()...), historyTools()...), youOnlyTools()...), reviewTools()...), dataTableReviewTools()...)...) + }, append(append(append(append(append(append(append(append(append(append(append(append(append(append(append(append(playtestTools(), mergeTools()...), refsTools()...), tileTools()...), inspectorTools()...), objectMenuTools()...), releaseTools()...), problemTools()...), playFrozenTools()...), agentTools()...), taskTools()...), contextTools()...), historyTools()...), youOnlyTools()...), reviewTools()...), dataTableReviewTools()...), sketchTools()...)...) } // projectRoot returns the absolute, symlink-free root of ed's project, or "" without one. diff --git a/packages/game/editor/locales/en.yaml b/packages/game/editor/locales/en.yaml index f710c64fe..1ba62a54c 100644 --- a/packages/game/editor/locales/en.yaml +++ b/packages/game/editor/locales/en.yaml @@ -233,6 +233,38 @@ strings: cmd.shortcutsSettings.label: 'Settings: Keyboard Shortcuts' cmd.shortcutsSheet.desc: Show the keyboard shortcuts reference sheet grouped by scope cmd.shortcutsSheet.label: Keyboard Shortcuts + cmd.sketchAddMark.desc: Place a numbered sketch mark at the current cursor or viewport center + cmd.sketchAddMark.label: 'Sketch: Add Mark at Cursor' + cmd.sketchApproveReading.desc: Approve the agent's sketch reading and release the scene_edit confirmation hold + cmd.sketchApproveReading.label: 'Sketch: Go Ahead' + cmd.sketchClear.desc: Clear all sketch marks from the viewport sketch layer + cmd.sketchClear.label: 'Sketch: Clear Marks' + cmd.sketchCorrectMark.desc: Reopen sketch mode with the targeted mark selected to correct it + cmd.sketchCorrectMark.label: 'Sketch: Correct a Mark' + cmd.sketchDone.desc: Leave sketch drawing mode while keeping drawn marks until sent or cleared + cmd.sketchDone.label: 'Sketch: Finish Sketch Mode' + cmd.sketchKeepReview.desc: Keep the agent's post-sketch scene edits and clear the viewport sketch layer + cmd.sketchKeepReview.label: 'Review: Keep Changes and Clear Sketch' + cmd.sketchRevertReview.desc: Revert the agent's post-sketch scene edits while keeping the sketch marks to send again + cmd.sketchRevertReview.label: 'Review: Revert Changes and Keep Sketch' + cmd.sketchReviewOverlay.desc: Lay the sent sketch faintly over the reviewed result in the 2D viewport + cmd.sketchReviewOverlay.label: 'Review: Toggle Sketch Overlay' + cmd.sketchSend.desc: Send the viewport sketch marks in scene coordinates and rendered PNG to the agent + cmd.sketchSend.label: 'Sketch: Send to Agent' + cmd.sketchToggle.desc: Toggle the session-only viewport sketch layer for the agent + cmd.sketchToggle.label: Sketch on Viewport + cmd.sketchToggleMarks.desc: Temporarily hide or show sketch marks on the viewport without clearing them + cmd.sketchToggleMarks.label: 'Sketch: Hide / Show Marks' + cmd.sketchToolArrow.desc: Draw a directed arrow mark on the viewport sketch layer + cmd.sketchToolArrow.label: 'Sketch Tool: Arrow' + cmd.sketchToolBox.desc: Draw a rectangular area mark on the viewport sketch layer + cmd.sketchToolBox.label: 'Sketch Tool: Box' + cmd.sketchToolPen.desc: Draw a freehand polyline mark on the viewport sketch layer + cmd.sketchToolPen.label: 'Sketch Tool: Pen' + cmd.sketchToolText.desc: Place a labelled text mark on the viewport sketch layer + cmd.sketchToolText.label: 'Sketch Tool: Text' + cmd.sketchUndoMark.desc: Undo the most recent change to the viewport sketch layer + cmd.sketchUndoMark.label: 'Sketch: Undo Last Mark' cmd.startScreen.desc: Show the Start Screen with recent projects, templates, and demo cmd.startScreen.label: Start Screen cmd.tasks.desc: Toggle the Agent background task list panel @@ -629,6 +661,7 @@ strings: menu.shadingWireframe: Wireframe menu.shortcutsSettings: Keyboard Shortcuts... menu.shortcutsSheet: Keyboard Shortcuts + menu.sketch: Sketch menu.startScreen: Start Screen menu.stop: Stop menu.tasks: Background Tasks @@ -857,6 +890,7 @@ strings: scope.play: Play scope.review: Review scope.sceneTree: Scene Tree + scope.sketch: Sketch scope.tile: Tile scope.viewport: Viewport scope.viewport2d: 2D Viewport @@ -1136,6 +1170,17 @@ strings: shortcutsSheet.subtitleMac: macOS keys. Rebind any command in Settings › Shortcuts. shortcutsSheet.subtitleOther: Windows and Linux keys. Rebind any command in Settings › Shortcuts. shortcutsSheet.title: Keyboard Shortcuts + sketch.clear: Clear + sketch.done: Done + sketch.hideMarks: Hide marks + sketch.showMarks: Show marks + sketch.statusHint: Esc finishes the sketch · marks stay until sent or cleared + sketch.tool.arrow: Arrow + sketch.tool.box: Box + sketch.tool.pen: Pen + sketch.tool.text: Text + sketch.toolbarLabel: Sketch tools + sketch.undoMark: Undo last mark snap.auto: Auto snap.autoLabel: Follow the active layer's tilemap tile size snap.grid: Grid diff --git a/packages/game/editor/locales/zh.yaml b/packages/game/editor/locales/zh.yaml index bcd4b9889..f5fee6589 100644 --- a/packages/game/editor/locales/zh.yaml +++ b/packages/game/editor/locales/zh.yaml @@ -233,6 +233,38 @@ strings: cmd.shortcutsSettings.label: 设置:键盘快捷键 cmd.shortcutsSheet.desc: 显示按作用域分组的键盘快捷键速查表 cmd.shortcutsSheet.label: 键盘快捷键 + cmd.sketchAddMark.desc: 在当前光标或视口中心放置一个编号草图标记 + cmd.sketchAddMark.label: 草图:在光标处添加标记 + cmd.sketchApproveReading.desc: 确认智能体的草图解读并解除 scene_edit 确认等待 + cmd.sketchApproveReading.label: 草图:继续执行 + cmd.sketchClear.desc: 清空视口草图层中的所有标记 + cmd.sketchClear.label: 草图:清空标记 + cmd.sketchCorrectMark.desc: 重新打开草图模式并选中目标标记以便修改 + cmd.sketchCorrectMark.label: 草图:修正标记 + cmd.sketchDone.desc: 退出草图绘制模式并保留已绘标记直到发送或清空 + cmd.sketchDone.label: 草图:完成草图模式 + cmd.sketchKeepReview.desc: 保留智能体基于草图的场景修改并清空视口草图层 + cmd.sketchKeepReview.label: 审查:保留修改并清空草图 + cmd.sketchRevertReview.desc: 撤销智能体基于草图的场景修改并保留草图标记以便再次发送 + cmd.sketchRevertReview.label: 审查:撤销修改并保留草图 + cmd.sketchReviewOverlay.desc: 在 2D 视口中将已发送的草图半透明叠加到审查结果上 + cmd.sketchReviewOverlay.label: 审查:切换草图叠加层 + cmd.sketchSend.desc: 将场景坐标中的视口草图标记与渲染 PNG 一并发送给智能体 + cmd.sketchSend.label: 草图:发送给智能体 + cmd.sketchToggle.desc: 切换面向智能体的会话级视口草图层 + cmd.sketchToggle.label: 在视口上绘制草图 + cmd.sketchToggleMarks.desc: 暂时隐藏或显示视口上的草图标记而不清空 + cmd.sketchToggleMarks.label: 草图:隐藏 / 显示标记 + cmd.sketchToolArrow.desc: 在视口草图层上绘制带方向的箭头标记 + cmd.sketchToolArrow.label: 草图工具:箭头 + cmd.sketchToolBox.desc: 在视口草图层上绘制矩形区域标记 + cmd.sketchToolBox.label: 草图工具:方框 + cmd.sketchToolPen.desc: 在视口草图层上绘制自由手绘折线标记 + cmd.sketchToolPen.label: 草图工具:画笔 + cmd.sketchToolText.desc: 在视口草图层上放置带标签的文本标记 + cmd.sketchToolText.label: 草图工具:文本 + cmd.sketchUndoMark.desc: 撤销视口草图层的上一次标记变更 + cmd.sketchUndoMark.label: 草图:撤销上一个标记 cmd.startScreen.desc: 显示包含最近项目、模板与演示的开始界面 cmd.startScreen.label: 开始界面 cmd.tasks.desc: 切换智能体后台任务列表面板 @@ -629,6 +661,7 @@ strings: menu.shadingWireframe: 线框 menu.shortcutsSettings: 键盘快捷键… menu.shortcutsSheet: 键盘快捷键 + menu.sketch: 草图 menu.startScreen: 开始界面 menu.stop: 停止 menu.tasks: 后台任务 @@ -857,6 +890,7 @@ strings: scope.play: 运行 scope.review: 审核 scope.sceneTree: 场景树 + scope.sketch: 草图 scope.tile: 瓦片 scope.viewport: 视口 scope.viewport2d: 2D 视口 @@ -1136,6 +1170,17 @@ strings: shortcutsSheet.subtitleMac: macOS 按键。可在“设置 › 快捷键”中重新绑定任意命令。 shortcutsSheet.subtitleOther: Windows 与 Linux 按键。可在“设置 › 快捷键”中重新绑定任意命令。 shortcutsSheet.title: 键盘快捷键 + sketch.clear: 清空 + sketch.done: 完成 + sketch.hideMarks: 隐藏标记 + sketch.showMarks: 显示标记 + sketch.statusHint: Esc 结束草图 · 标记会保留直到发送或清空 + sketch.tool.arrow: 箭头 + sketch.tool.box: 方框 + sketch.tool.pen: 画笔 + sketch.tool.text: 文本 + sketch.toolbarLabel: 草图工具 + sketch.undoMark: 撤销上一个标记 snap.auto: 自动 snap.autoLabel: 跟随当前图层的瓦片尺寸 snap.grid: 网格 diff --git a/packages/game/editor/menubar.go b/packages/game/editor/menubar.go index c9071e2bc..4e7d472bd 100644 --- a/packages/game/editor/menubar.go +++ b/packages/game/editor/menubar.go @@ -205,6 +205,31 @@ func (e *Editor) ApplicationMenu() []desktop.MenuItem { cmdItem(CmdToggleLightingPreview, e.T("menu.lightingPreview"), false), cmdItem(CmdToggleNavMesh2D, e.T("menu.navMesh2dOverlay"), false), {Label: e.T("menu.overlays"), Items: overlayMenuItems}, + { + Label: e.T("menu.sketch"), + Items: []desktop.MenuItem{ + cmdItem(CmdSketchToggle, "", false), + sep, + cmdItem(CmdSketchToolPen, "", true), + cmdItem(CmdSketchToolArrow, "", true), + cmdItem(CmdSketchToolBox, "", true), + cmdItem(CmdSketchToolText, "", true), + cmdItem(CmdSketchAddMarkAtCursor, "", false), + sep, + cmdItem(CmdSketchUndoMark, "", false), + cmdItem(CmdSketchToggleMarks, "", false), + cmdItem(CmdSketchClear, "", false), + cmdItem(CmdSketchDone, "", false), + sep, + cmdItem(CmdSketchSend, "", false), + cmdItem(CmdSketchApproveReading, "", false), + cmdItem(CmdSketchCorrectMark, "", false), + sep, + cmdItem(CmdSketchToggleReviewOverlay, "", false), + cmdItem(CmdSketchKeepReview, "", false), + cmdItem(CmdSketchRevertReview, "", false), + }, + }, sep, cmdItem(CmdNavMeshOverlay, e.T("menu.navMeshOverlay"), false), cmdItem(CmdNavMeshPanel, e.T("menu.navMeshPanel"), false), @@ -296,7 +321,7 @@ func (e *Editor) bindApplicationMenu(cx *core.Scope, rev *core.Signal[uint64]) { } } var b strings.Builder - fmt.Fprintf(&b, "%s|%v|%s|%v|%d|%v|%v|%v|%v|%v|%v|%v|%v|%s|%v|%v|%v|%v|%v|%v|%d|%v|%v|%v|%d|%d|%d|%d|%d|%s|%s|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%d|%d|%v|%v|%v|%d|%s|%v|%v|%v|%s|%v|%v|%d", + fmt.Fprintf(&b, "%s|%v|%s|%v|%d|%v|%v|%v|%v|%v|%v|%v|%v|%s|%v|%v|%v|%v|%v|%v|%d|%v|%v|%v|%d|%d|%d|%d|%d|%s|%s|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%v|%d|%d|%v|%v|%v|%d|%s|%v|%v|%v|%s|%v|%v|%d|%v|%s|%d|%v|%s|%v|%v", e.ResolvedLanguage(), e.SettingsOpen(), e.SettingsPage(), @@ -366,6 +391,13 @@ func (e *Editor) bindApplicationMenu(cx *core.Scope, rev *core.Signal[uint64]) { e.AskInPlaceOpen(), e.TasksPanelOpen(), e.FirstRunStage(), + e.SketchActive(), + e.SketchTool(), + e.SketchMarkCount(), + e.SketchMarksHidden(), + e.SketchHoldState(), + e.SketchReviewOpen(), + e.SketchReviewOverlayVisible(), ) for _, ov := range e.ViewportOverlays() { b.WriteByte('|') diff --git a/packages/game/editor/scenetree.go b/packages/game/editor/scenetree.go index 397abfe19..8bc6f80c1 100644 --- a/packages/game/editor/scenetree.go +++ b/packages/game/editor/scenetree.go @@ -443,6 +443,7 @@ func SceneTreeView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No FocusVisible: ed.SpecPalette(cx).FocusRing(-2), }, }}}, + sceneTreeSketchSectionView(cx, ed, rev), core.Text{ TestID: "scene-tree-hint", Content: ed.T("sceneTree.hint"), diff --git a/packages/game/editor/shortcuts.go b/packages/game/editor/shortcuts.go index 1a97d9dca..75efed681 100644 --- a/packages/game/editor/shortcuts.go +++ b/packages/game/editor/shortcuts.go @@ -19,6 +19,7 @@ const ( ScopeViewport3D = "viewport3d" ScopeSceneTree = "sceneTree" ScopeTile = "tile" + ScopeSketch = "sketch" ScopeAnimation = "animation" ScopePlay = "play" ScopeReview = "review" @@ -32,6 +33,7 @@ var scopeDisplayOrder = []string{ ScopeViewport2D, ScopeViewport3D, ScopeTile, + ScopeSketch, ScopeSceneTree, ScopeReview, ScopeAnimation, @@ -77,6 +79,8 @@ func (e *Editor) CommandScopeLabel(scope string) string { return e.T("scope.sceneTree") case ScopeTile: return e.T("scope.tile") + case ScopeSketch: + return e.T("scope.sketch") case ScopeAnimation: return e.T("scope.animation") case ScopePlay: @@ -107,6 +111,8 @@ func (e *Editor) commandScopeSearchTerms(scope string) []string { terms = append(terms, "scene tree", "scenetree", "tree") case ScopeTile: terms = append(terms, "tile", "tilemap") + case ScopeSketch: + terms = append(terms, "sketch", "draw", "annotate", "agent") case ScopeAnimation: terms = append(terms, "animation", "timeline") case ScopePlay: @@ -496,6 +502,11 @@ func (e *Editor) shortcutScopePriority(scope string) int { return 3 } return 0 + case ScopeSketch: + if e.ViewMode == ViewMode2D && !e.Playing() && e.SketchActive() && !e.ReviewOpen() && !e.SettingsOpen() { + return 5 + } + return 0 case ScopeViewport3D: if e.ViewMode == ViewMode3D { return 4 diff --git a/packages/game/editor/sketch.go b/packages/game/editor/sketch.go new file mode 100644 index 000000000..7e4866ba8 --- /dev/null +++ b/packages/game/editor/sketch.go @@ -0,0 +1,1742 @@ +package editor + +import ( + "errors" + "fmt" + "math" + "slices" + "strconv" + "strings" + "time" + + "github.com/nsgo-dev/game/packages/game/math2d" + gamemcp "github.com/nsgo-dev/game/packages/game/mcp" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/ui" +) + +// SketchTool selects one of the four viewport sketch drawing tools. +type SketchTool string + +const ( + // SketchToolPen draws a freehand polyline in scene coordinates. + SketchToolPen SketchTool = "pen" + // SketchToolArrow draws a directed arrow from start to end in scene coordinates. + SketchToolArrow SketchTool = "arrow" + // SketchToolBox draws a rectangular region in scene coordinates. + SketchToolBox SketchTool = "box" + // SketchToolText places a labelled anchor point in scene coordinates. + SketchToolText SketchTool = "text" +) + +// Valid reports whether t is one of the four built-in sketch tools. +func (t SketchTool) Valid() bool { + switch t { + case SketchToolPen, SketchToolArrow, SketchToolBox, SketchToolText: + return true + default: + return false + } +} + +// String returns the human-readable tool label. +func (t SketchTool) String() string { + switch t { + case SketchToolPen: + return "Pen" + case SketchToolArrow: + return "Arrow" + case SketchToolBox: + return "Box" + case SketchToolText: + return "Text" + default: + return "Arrow" + } +} + +// Hint returns the short status hint displayed below the floating sketch toolbar. +func (t SketchTool) Hint() string { + switch t { + case SketchToolPen: + return "Pen · drag to draw a free line" + case SketchToolArrow: + return "Arrow · drag from where to where" + case SketchToolBox: + return "Box · drag to mark an area" + case SketchToolText: + return "Text · click to write a short label" + default: + return "Arrow · drag from where to where" + } +} + +// SketchHoldState describes the confirmation hold lifecycle for a sent viewport sketch. +type SketchHoldState string + +const ( + // SketchHoldNone means no sent sketch is currently awaiting confirmation or editing. + SketchHoldNone SketchHoldState = "none" + // SketchHoldPending means a sketch was sent to the agent; mutating scene MCP tools hold until confirmed. + SketchHoldPending SketchHoldState = "pending" + // SketchHoldReading means the agent posted its restatement card; mutating scene MCP tools still hold until Go ahead or a reply. + SketchHoldReading SketchHoldState = "reading" + // SketchHoldApproved means the user answered Go ahead (or replied approvingly) and the agent may now edit the scene. + SketchHoldApproved SketchHoldState = "approved" +) + +// SketchPoint is a 2D point stored strictly in scene (world) coordinates. +type SketchPoint struct { + X float32 `json:"x"` + Y float32 `json:"y"` +} + +// SketchRect is an axis-aligned rectangle stored strictly in scene (world) coordinates. +type SketchRect struct { + X float32 `json:"x"` + Y float32 `json:"y"` + Width float32 `json:"width"` + Height float32 `json:"height"` +} + +// SketchMark is one numbered annotation drawn on the viewport sketch layer in scene coordinates. +// Sketch marks live solely in editor session state and are never written into SceneDoc or *.scene.yaml. +type SketchMark struct { + ID string `json:"id"` + Number int `json:"number"` + Kind SketchTool `json:"kind"` + Label string `json:"label,omitempty"` + Points []SketchPoint `json:"points,omitempty"` + Start *SketchPoint `json:"start,omitempty"` + End *SketchPoint `json:"end,omitempty"` + Rect *SketchRect `json:"rect,omitempty"` + At *SketchPoint `json:"at,omitempty"` +} + +// Clone returns a deep copy of m. +func (m SketchMark) Clone() SketchMark { + out := m + if len(m.Points) > 0 { + out.Points = slices.Clone(m.Points) + } + if m.Start != nil { + p := *m.Start + out.Start = &p + } + if m.End != nil { + p := *m.End + out.End = &p + } + if m.Rect != nil { + r := *m.Rect + out.Rect = &r + } + if m.At != nil { + p := *m.At + out.At = &p + } + return out +} + +// AnchorScenePoint returns the primary anchor point of m in scene coordinates, +// where its numbered badge attaches. +func (m SketchMark) AnchorScenePoint() SketchPoint { + switch m.Kind { + case SketchToolBox: + if m.Rect != nil { + return SketchPoint{X: m.Rect.X, Y: m.Rect.Y} + } + case SketchToolArrow: + if m.Start != nil { + return *m.Start + } + case SketchToolPen: + if len(m.Points) > 0 { + return m.Points[0] + } + case SketchToolText: + if m.At != nil { + return *m.At + } + } + return SketchPoint{} +} + +// GeometrySummary formats m's geometry concisely in scene coordinates for the preview popover and reading card. +func (m SketchMark) GeometrySummary() string { + ri := func(v float32) int { return int(math.Round(float64(v))) } + switch m.Kind { + case SketchToolBox: + if m.Rect != nil { + return fmt.Sprintf("rect %d,%d %d×%d", ri(m.Rect.X), ri(m.Rect.Y), ri(m.Rect.Width), ri(m.Rect.Height)) + } + return "rect 0,0 0×0" + case SketchToolPen: + if len(m.Points) >= 2 { + first := m.Points[0] + last := m.Points[len(m.Points)-1] + return fmt.Sprintf("path %d,%d → %d,%d · %d points", ri(first.X), ri(first.Y), ri(last.X), ri(last.Y), len(m.Points)) + } + if len(m.Points) == 1 { + return fmt.Sprintf("path %d,%d · 1 point", ri(m.Points[0].X), ri(m.Points[0].Y)) + } + return "path 0 points" + case SketchToolArrow: + if m.Start != nil && m.End != nil { + return fmt.Sprintf("arrow %d,%d → %d,%d", ri(m.Start.X), ri(m.Start.Y), ri(m.End.X), ri(m.End.Y)) + } + return "arrow" + case SketchToolText: + if m.At != nil { + return fmt.Sprintf("text %d,%d", ri(m.At.X), ri(m.At.Y)) + } + return "text" + default: + return string(m.Kind) + } +} + +// ReadingHeading formats the compact mark caption shown above an agent restatement row +// (for example `Box · “3 spikes”`). +func (m SketchMark) ReadingHeading() string { + kind := m.Kind.String() + if m.Kind == SketchToolPen { + kind = "Line" + } + if strings.TrimSpace(m.Label) != "" { + return fmt.Sprintf("%s · “%s”", kind, strings.TrimSpace(m.Label)) + } + return kind +} + +// SketchAgentRequest is the structured payload sent to the agent when the author sends a viewport sketch. +type SketchAgentRequest struct { + Scene string `json:"scene"` + ChipLabel string `json:"chipLabel"` + Prompt string `json:"prompt,omitempty"` + View View2D `json:"view"` + Marks []SketchMark `json:"marks"` + PNG []byte `json:"-"` + Width int `json:"width,omitempty"` + Height int `json:"height,omitempty"` +} + +// SketchReadingItem is the agent's restatement of one numbered sketch mark before editing. +type SketchReadingItem struct { + Number int `json:"number"` + Mark string `json:"mark,omitempty"` + Text string `json:"text"` +} + +// SketchReading is the reading card posted by the agent via MCP before scene_edit is allowed. +type SketchReading struct { + Summary string `json:"summary,omitempty"` + Items []SketchReadingItem `json:"items"` + Assumptions []string `json:"assumptions,omitempty"` + PostedAt time.Time `json:"postedAt,omitempty"` +} + +// Clone returns a deep copy of r. +func (r *SketchReading) Clone() *SketchReading { + if r == nil { + return nil + } + out := *r + out.Items = slices.Clone(r.Items) + out.Assumptions = slices.Clone(r.Assumptions) + return &out +} + +// SketchReadingReply describes the user's answer to an agent sketch reading card. +type SketchReadingReply struct { + Action string `json:"action"` // "approve", "correct", or "reply" + MarkNumber int `json:"markNumber,omitempty"` + Message string `json:"message,omitempty"` +} + +// SketchReviewChangeKind classifies one scene edit tracked by a post-sketch review. +type SketchReviewChangeKind string + +const ( + SketchChangeAdded SketchReviewChangeKind = "added" + SketchChangeChanged SketchReviewChangeKind = "changed" + SketchChangeRemoved SketchReviewChangeKind = "removed" +) + +// SketchReviewChange describes one object added, changed, or removed by the agent after approving a sketch. +type SketchReviewChange struct { + Kind SketchReviewChangeKind `json:"kind"` + ID string `json:"id"` + Detail string `json:"detail,omitempty"` +} + +type sketchDraftDrag struct { + tool SketchTool + startWorld SketchPoint + endWorld SketchPoint + points []SketchPoint + moved bool + hitMark int +} + +type sketchReviewState struct { + open bool + overlayVisible bool + baseYAML []byte + historyStart int + changes []SketchReviewChange + undoLabels []string +} + +type sketchState struct { + active bool + panelOpen bool + tool SketchTool + marks []SketchMark + undoStack [][]SketchMark + nextSeq uint64 + selectedMark int + marksHidden bool + attached bool + previewOpen bool + promptDraft string + hold SketchHoldState + reading *SketchReading + lastRequest *SketchAgentRequest + draft *sketchDraftDrag + review *sketchReviewState + forcePNGMarks bool +} + +const ( + maxSketchMarks = 200 + maxSketchUndoDepth = 64 + maxSketchPenPoints = 2048 + sketchBadgeRadiusPt = 9.0 + sketchDragMinDistPt = 3.0 + sketchPenStepMinPt = 3.0 + sketchDefaultBoxW = 96.0 + sketchDefaultBoxH = 40.0 + sketchDefaultArrowDX = 84.0 + sketchDefaultArrowDY = 36.0 +) + +var ( + // ErrSketchEmpty is returned when sending or reading a sketch with no marks. + ErrSketchEmpty = errors.New("editor: no sketch marks on the viewport") + // ErrSketchHoldActive is returned when a mutating agent edit runs while a sent sketch awaits confirmation. + ErrSketchHoldActive = errors.New("editor: sent sketch is waiting for confirmation (Go ahead or Correct a mark)") + // ErrNoSketchReview is returned when Keep or Revert is invoked without an open sketch review. + ErrNoSketchReview = errors.New("editor: no sketch review is open") +) + +func cloneSketchMarks(marks []SketchMark) []SketchMark { + if len(marks) == 0 { + return nil + } + out := make([]SketchMark, len(marks)) + for i, m := range marks { + out[i] = m.Clone() + } + return out +} + +func cloneSketchState(src sketchState) sketchState { + dst := src + dst.marks = cloneSketchMarks(src.marks) + if len(src.undoStack) > 0 { + dst.undoStack = make([][]SketchMark, len(src.undoStack)) + for i, snap := range src.undoStack { + dst.undoStack[i] = cloneSketchMarks(snap) + } + } + dst.reading = src.reading.Clone() + if src.lastRequest != nil { + req := *src.lastRequest + req.Marks = cloneSketchMarks(src.lastRequest.Marks) + req.PNG = slices.Clone(src.lastRequest.PNG) + dst.lastRequest = &req + } + dst.draft = nil + if src.review != nil { + rv := *src.review + rv.baseYAML = slices.Clone(src.review.baseYAML) + rv.changes = slices.Clone(src.review.changes) + rv.undoLabels = slices.Clone(src.review.undoLabels) + dst.review = &rv + } + return dst +} + +func (e *Editor) ensureSketchTool() SketchTool { + if !e.sketch.tool.Valid() { + e.sketch.tool = SketchToolArrow + } + return e.sketch.tool +} + +func (e *Editor) pushSketchUndo() { + snap := cloneSketchMarks(e.sketch.marks) + e.sketch.undoStack = append(e.sketch.undoStack, snap) + if len(e.sketch.undoStack) > maxSketchUndoDepth { + e.sketch.undoStack = e.sketch.undoStack[len(e.sketch.undoStack)-maxSketchUndoDepth:] + } +} + +func (e *Editor) renumberSketchMarks() { + for i := range e.sketch.marks { + e.sketch.marks[i].Number = i + 1 + } + if e.sketch.selectedMark > len(e.sketch.marks) { + e.sketch.selectedMark = len(e.sketch.marks) + } + if len(e.sketch.marks) == 0 { + e.sketch.selectedMark = 0 + e.sketch.attached = false + e.sketch.previewOpen = false + } +} + +// SketchActive reports whether viewport sketch drawing mode is currently active. +func (e *Editor) SketchActive() bool { + return e != nil && e.sketch.active && e.ViewMode == ViewMode2D && !e.playing +} + +// SetSketchActive turns viewport sketch drawing mode on or off. +// Turning sketch mode off keeps existing marks on the layer until sent, cleared, or kept. +func (e *Editor) SetSketchActive(on bool) { + if e == nil || e.playing { + return + } + if on && e.ViewMode != ViewMode2D { + e.SetViewMode(ViewMode2D) + } + if on { + e.ensureSketchTool() + e.cancelActiveObjectDrags() + e.sketch.active = true + e.sketch.panelOpen = true + e.sketch.marksHidden = false + if len(e.sketch.marks) > 0 { + e.sketch.attached = true + } + e.Status = "Sketch layer · " + e.sketch.tool.String() + } else { + e.sketch.active = false + e.sketch.draft = nil + if len(e.sketch.marks) > 0 { + e.Status = fmt.Sprintf("Sketch finished · %s", e.SketchBarCountLabel()) + } + } + e.notify() +} + +// StartSketch activates viewport sketch mode and opens the Sketch/Agent panel. +func (e *Editor) StartSketch() { + e.SetSketchActive(true) +} + +// FinishSketch exits sketch drawing mode (Done / Esc) while keeping all drawn marks on the viewport +// until they are sent, cleared, or kept. +func (e *Editor) FinishSketch() { + e.SetSketchActive(false) +} + +// ToggleSketch toggles viewport sketch drawing mode on or off. +func (e *Editor) ToggleSketch() { + if e == nil { + return + } + e.SetSketchActive(!e.SketchActive()) +} + +// SketchPanelOpen reports whether the right-side Sketch / Agent panel should be shown. +func (e *Editor) SketchPanelOpen() bool { + if e == nil || e.playing || e.ViewMode != ViewMode2D { + return false + } + return e.sketch.panelOpen || e.sketch.active || e.sketch.reading != nil || e.SketchReviewOpen() +} + +// SetSketchPanelOpen shows or hides the right-side Sketch / Agent panel. +func (e *Editor) SetSketchPanelOpen(open bool) { + if e == nil { + return + } + if !open { + e.sketch.active = false + e.sketch.draft = nil + } + e.sketch.panelOpen = open + e.notify() +} + +// SketchTool returns the active sketch drawing tool (Pen, Arrow, Box, or Text). +func (e *Editor) SketchTool() SketchTool { + if e == nil { + return SketchToolArrow + } + return e.ensureSketchTool() +} + +// SetSketchTool switches the active sketch tool and ensures sketch mode is active. +func (e *Editor) SetSketchTool(tool SketchTool) { + if e == nil || !tool.Valid() || e.playing { + return + } + e.sketch.tool = tool + if !e.sketch.active { + e.SetSketchActive(true) + return + } + e.sketch.draft = nil + e.Status = "Sketch layer · " + tool.String() + e.notify() +} + +// SketchMarks returns a deep copy of all marks currently on the viewport sketch layer, in sequential badge order. +func (e *Editor) SketchMarks() []SketchMark { + if e == nil { + return nil + } + return cloneSketchMarks(e.sketch.marks) +} + +// SketchMarkCount returns the number of marks currently on the viewport sketch layer. +func (e *Editor) SketchMarkCount() int { + if e == nil { + return 0 + } + return len(e.sketch.marks) +} + +// SketchMarkByNumber returns the 1-based numbered sketch mark, if present. +func (e *Editor) SketchMarkByNumber(number int) (SketchMark, bool) { + if e == nil || number < 1 || number > len(e.sketch.marks) { + return SketchMark{}, false + } + return e.sketch.marks[number-1].Clone(), true +} + +// SelectedSketchMark returns the 1-based number of the currently selected sketch mark, or 0 when none is selected. +func (e *Editor) SelectedSketchMark() int { + if e == nil || e.sketch.selectedMark < 1 || e.sketch.selectedMark > len(e.sketch.marks) { + return 0 + } + return e.sketch.selectedMark +} + +// SelectSketchMark selects the 1-based mark number (or clears mark selection when number <= 0). +func (e *Editor) SelectSketchMark(number int) { + if e == nil { + return + } + if number < 1 || number > len(e.sketch.marks) { + if e.sketch.selectedMark != 0 { + e.sketch.selectedMark = 0 + e.notify() + } + return + } + if e.sketch.selectedMark != number { + e.sketch.selectedMark = number + e.notify() + } +} + +// SketchMarksHidden reports whether the sketch layer marks are temporarily hidden via the eye button. +func (e *Editor) SketchMarksHidden() bool { + return e != nil && e.sketch.marksHidden +} + +// SetSketchMarksHidden hides or shows sketch marks on the viewport without clearing them. +func (e *Editor) SetSketchMarksHidden(hidden bool) { + if e == nil || e.sketch.marksHidden == hidden { + return + } + e.sketch.marksHidden = hidden + e.notify() +} + +// ToggleSketchMarksHidden flips whether sketch marks are temporarily hidden on the viewport. +func (e *Editor) ToggleSketchMarksHidden() { + if e == nil { + return + } + e.SetSketchMarksHidden(!e.sketch.marksHidden) +} + +// SketchAttached reports whether the active sketch marks are attached to the next agent request chip. +func (e *Editor) SketchAttached() bool { + return e != nil && e.sketch.attached && len(e.sketch.marks) > 0 +} + +// SetSketchAttached attaches or detaches the sketch chip from the agent composer without erasing marks. +func (e *Editor) SetSketchAttached(attached bool) { + if e == nil { + return + } + want := attached && len(e.sketch.marks) > 0 + if e.sketch.attached == want { + return + } + e.sketch.attached = want + if !want { + e.sketch.previewOpen = false + } + e.notify() +} + +// SketchPreviewOpen reports whether the "Sent with this request" sketch preview card is open. +func (e *Editor) SketchPreviewOpen() bool { + return e != nil && e.sketch.previewOpen && e.SketchAttached() +} + +// SetSketchPreviewOpen opens or closes the "Sent with this request" preview card. +func (e *Editor) SetSketchPreviewOpen(open bool) { + if e == nil { + return + } + want := open && e.SketchAttached() + if e.sketch.previewOpen == want { + return + } + e.sketch.previewOpen = want + e.notify() +} + +// ToggleSketchPreview toggles the "Sent with this request" preview card. +func (e *Editor) ToggleSketchPreview() { + if e == nil { + return + } + e.SetSketchPreviewOpen(!e.SketchPreviewOpen()) +} + +// SketchPromptDraft returns the current text in the Sketch/Agent composer field. +func (e *Editor) SketchPromptDraft() string { + if e == nil { + return "" + } + return e.sketch.promptDraft +} + +// SetSketchPromptDraft updates the Sketch/Agent composer draft text. +func (e *Editor) SetSketchPromptDraft(text string) { + if e == nil || e.sketch.promptDraft == text { + return + } + e.sketch.promptDraft = text + e.notify() +} + +// SketchChipLabel returns the composer context chip label, e.g. "Sketch · 3 marks". +func (e *Editor) SketchChipLabel() string { + n := e.SketchMarkCount() + if n == 1 { + return "Sketch · 1 mark" + } + return fmt.Sprintf("Sketch · %d marks", n) +} + +// SketchBarCountLabel returns the sketch toolbar count text, e.g. "3 marks not saved". +func (e *Editor) SketchBarCountLabel() string { + n := e.SketchMarkCount() + if n == 1 { + return "1 mark not saved" + } + return fmt.Sprintf("%d marks not saved", n) +} + +// SketchStatusSceneCoords returns the live scene coordinates shown in the status bar while sketching +// (the pointer position in scene space when hovering the viewport, otherwise the selected/last mark or view center). +func (e *Editor) SketchStatusSceneCoords() (float32, float32) { + if e == nil { + return 0, 0 + } + if e.hasPointer2D { + return e.CanvasToWorld(e.pointer2D.X, e.pointer2D.Y) + } + if sel := e.SelectedSketchMark(); sel > 0 { + p := e.sketch.marks[sel-1].AnchorScenePoint() + return p.X, p.Y + } + if n := len(e.sketch.marks); n > 0 { + p := e.sketch.marks[n-1].AnchorScenePoint() + return p.X, p.Y + } + v := e.View2D() + return v.X, v.Y +} + +// SketchDragging reports whether a sketch mark drag is currently in progress on the viewport. +func (e *Editor) SketchDragging() bool { + return e != nil && e.sketch.draft != nil +} + +func (e *Editor) appendSketchMark(m SketchMark) SketchMark { + e.pushSketchUndo() + e.sketch.nextSeq++ + if m.ID == "" { + m.ID = fmt.Sprintf("mark_%d", e.sketch.nextSeq) + } + m.Number = len(e.sketch.marks) + 1 + if len(e.sketch.marks) >= maxSketchMarks { + e.sketch.marks = e.sketch.marks[1:] + } + e.sketch.marks = append(e.sketch.marks, m.Clone()) + e.renumberSketchMarks() + added := e.sketch.marks[len(e.sketch.marks)-1] + e.sketch.selectedMark = added.Number + e.sketch.attached = true + e.sketch.marksHidden = false + e.sketch.panelOpen = true + e.notify() + return added.Clone() +} + +// AddSketchBox adds a numbered Box mark strictly in scene coordinates without mutating SceneDoc or History. +func (e *Editor) AddSketchBox(x, y, width, height float32, label string) SketchMark { + if e == nil { + return SketchMark{} + } + if width < 0 { + x += width + width = -width + } + if height < 0 { + y += height + height = -height + } + r := SketchRect{X: x, Y: y, Width: width, Height: height} + return e.appendSketchMark(SketchMark{ + Kind: SketchToolBox, + Label: strings.TrimSpace(label), + Rect: &r, + }) +} + +// AddSketchArrow adds a numbered Arrow mark strictly in scene coordinates without mutating SceneDoc or History. +func (e *Editor) AddSketchArrow(x0, y0, x1, y1 float32, label string) SketchMark { + if e == nil { + return SketchMark{} + } + s := SketchPoint{X: x0, Y: y0} + t := SketchPoint{X: x1, Y: y1} + return e.appendSketchMark(SketchMark{ + Kind: SketchToolArrow, + Label: strings.TrimSpace(label), + Start: &s, + End: &t, + }) +} + +// AddSketchPen adds a numbered Pen polyline mark strictly in scene coordinates without mutating SceneDoc or History. +func (e *Editor) AddSketchPen(points []SketchPoint, label string) SketchMark { + if e == nil || len(points) == 0 { + return SketchMark{} + } + clean := make([]SketchPoint, 0, min(len(points), maxSketchPenPoints)) + for _, pt := range points { + if isFiniteFloat32(pt.X) && isFiniteFloat32(pt.Y) { + clean = append(clean, pt) + if len(clean) >= maxSketchPenPoints { + break + } + } + } + if len(clean) == 0 { + return SketchMark{} + } + return e.appendSketchMark(SketchMark{ + Kind: SketchToolPen, + Label: strings.TrimSpace(label), + Points: clean, + }) +} + +// AddSketchText adds a numbered Text mark strictly in scene coordinates without mutating SceneDoc or History. +func (e *Editor) AddSketchText(x, y float32, label string) SketchMark { + if e == nil { + return SketchMark{} + } + at := SketchPoint{X: x, Y: y} + return e.appendSketchMark(SketchMark{ + Kind: SketchToolText, + Label: strings.TrimSpace(label), + At: &at, + }) +} + +// AddSketchMarkAtCursor places a new mark using the active sketch tool at the current pointer or view center +// in scene coordinates, providing a full keyboard path for creating marks without pointer dragging. +func (e *Editor) AddSketchMarkAtCursor(label string) SketchMark { + if e == nil || e.playing { + return SketchMark{} + } + tool := e.ensureSketchTool() + wx, wy := e.SketchStatusSceneCoords() + switch tool { + case SketchToolBox: + return e.AddSketchBox(wx-sketchDefaultBoxW*0.5, wy-sketchDefaultBoxH*0.5, sketchDefaultBoxW, sketchDefaultBoxH, label) + case SketchToolArrow: + return e.AddSketchArrow(wx-sketchDefaultArrowDX*0.5, wy-sketchDefaultArrowDY*0.5, wx+sketchDefaultArrowDX*0.5, wy+sketchDefaultArrowDY*0.5, label) + case SketchToolPen: + return e.AddSketchPen([]SketchPoint{ + {X: wx - 40, Y: wy}, + {X: wx, Y: wy - 12}, + {X: wx + 40, Y: wy}, + }, label) + case SketchToolText: + return e.AddSketchText(wx, wy, label) + default: + return e.AddSketchBox(wx-sketchDefaultBoxW*0.5, wy-sketchDefaultBoxH*0.5, sketchDefaultBoxW, sketchDefaultBoxH, label) + } +} + +// SetSketchMarkLabel updates the optional text label on the 1-based sketch mark. +func (e *Editor) SetSketchMarkLabel(number int, label string) bool { + if e == nil || number < 1 || number > len(e.sketch.marks) { + return false + } + clean := strings.TrimSpace(label) + if e.sketch.marks[number-1].Label == clean { + return true + } + e.sketch.marks[number-1].Label = clean + e.notify() + return true +} + +// NudgeSelectedSketchMark translates the selected sketch mark by (dx, dy) in scene coordinates. +func (e *Editor) NudgeSelectedSketchMark(dx, dy float32) bool { + if e == nil || !isFiniteFloat32(dx) || !isFiniteFloat32(dy) || (dx == 0 && dy == 0) { + return false + } + sel := e.SelectedSketchMark() + if sel == 0 { + return false + } + m := &e.sketch.marks[sel-1] + switch m.Kind { + case SketchToolBox: + if m.Rect != nil { + m.Rect.X += dx + m.Rect.Y += dy + } + case SketchToolArrow: + if m.Start != nil { + m.Start.X += dx + m.Start.Y += dy + } + if m.End != nil { + m.End.X += dx + m.End.Y += dy + } + case SketchToolPen: + for i := range m.Points { + m.Points[i].X += dx + m.Points[i].Y += dy + } + case SketchToolText: + if m.At != nil { + m.At.X += dx + m.At.Y += dy + } + } + e.notify() + return true +} + +// DeleteSketchMark removes the 1-based mark and renumbers remaining marks sequentially. +func (e *Editor) DeleteSketchMark(number int) bool { + if e == nil || number < 1 || number > len(e.sketch.marks) { + return false + } + e.pushSketchUndo() + e.sketch.marks = slices.Delete(e.sketch.marks, number-1, number) + e.renumberSketchMarks() + e.notify() + return true +} + +// CanUndoSketchMark reports whether the sketch layer has a previous mark state to undo. +func (e *Editor) CanUndoSketchMark() bool { + return e != nil && len(e.sketch.undoStack) > 0 +} + +// UndoLastSketchMark restores the previous sketch mark list without touching SceneDoc or Editor.History. +func (e *Editor) UndoLastSketchMark() bool { + if e == nil || len(e.sketch.undoStack) == 0 { + return false + } + prev := e.sketch.undoStack[len(e.sketch.undoStack)-1] + e.sketch.undoStack = e.sketch.undoStack[:len(e.sketch.undoStack)-1] + e.sketch.marks = prev + e.renumberSketchMarks() + e.notify() + return true +} + +// ClearSketch clears all sketch marks, any pending reading card, and any active confirmation hold. +// It never modifies SceneDoc or Editor.History. +func (e *Editor) ClearSketch() { + if e == nil { + return + } + if len(e.sketch.marks) > 0 { + e.pushSketchUndo() + } + e.sketch.marks = nil + e.sketch.selectedMark = 0 + e.sketch.attached = false + e.sketch.previewOpen = false + e.sketch.draft = nil + e.sketch.hold = SketchHoldNone + e.sketch.reading = nil + e.sketch.lastRequest = nil + e.Status = "Sketch layer cleared" + e.notify() +} + +// HitTestSketchMark returns the 1-based mark number whose badge or geometry lies under (canvasX, canvasY), +// or 0 if none is hit. +func (e *Editor) HitTestSketchMark(canvasX, canvasY float32) int { + if e == nil || !isFiniteFloat32(canvasX) || !isFiniteFloat32(canvasY) || len(e.sketch.marks) == 0 { + return 0 + } + const badgeHitR = sketchBadgeRadiusPt + 5 + for i := len(e.sketch.marks) - 1; i >= 0; i-- { + m := e.sketch.marks[i] + bx, by := e.sketchBadgeCanvasPos(m) + if math.Hypot(float64(canvasX-bx), float64(canvasY-by)) <= badgeHitR { + return m.Number + } + } + return 0 +} + +func (e *Editor) sketchBadgeCanvasPos(m SketchMark) (float32, float32) { + if m.Kind == SketchToolPen && len(m.Points) > 0 { + minX, minY := e.WorldToCanvas(m.Points[0].X, m.Points[0].Y) + for _, pt := range m.Points[1:] { + cx, cy := e.WorldToCanvas(pt.X, pt.Y) + if cx < minX { + minX = cx + } + if cy < minY { + minY = cy + } + } + return minX - 6, minY - 14 + } + a := m.AnchorScenePoint() + cx, cy := e.WorldToCanvas(a.X, a.Y) + return cx - 10, cy - 12 +} + +// BeginSketchDrag starts drawing a sketch mark from canvas point (canvasX, canvasY) using the active sketch tool. +// Coordinates are converted immediately via CanvasToWorld so all stored geometry is in scene coordinates. +func (e *Editor) BeginSketchDrag(canvasX, canvasY float32) bool { + if e == nil || !e.SketchActive() || !isFiniteFloat32(canvasX) || !isFiniteFloat32(canvasY) { + return false + } + tool := e.ensureSketchTool() + hit := e.HitTestSketchMark(canvasX, canvasY) + wx, wy := e.CanvasToWorld(canvasX, canvasY) + start := SketchPoint{X: wx, Y: wy} + e.sketch.draft = &sketchDraftDrag{ + tool: tool, + startWorld: start, + endWorld: start, + points: []SketchPoint{start}, + hitMark: hit, + } + e.notify() + return true +} + +// UpdateSketchDrag extends the in-progress sketch mark to canvas point (canvasX, canvasY). +func (e *Editor) UpdateSketchDrag(canvasX, canvasY float32) bool { + if e == nil || e.sketch.draft == nil || !isFiniteFloat32(canvasX) || !isFiniteFloat32(canvasY) { + return false + } + dr := e.sketch.draft + wx, wy := e.CanvasToWorld(canvasX, canvasY) + pt := SketchPoint{X: wx, Y: wy} + sx, sy := e.WorldToCanvas(dr.startWorld.X, dr.startWorld.Y) + if math.Hypot(float64(canvasX-sx), float64(canvasY-sy)) >= sketchDragMinDistPt { + dr.moved = true + } + dr.endWorld = pt + if dr.tool == SketchToolPen && len(dr.points) < maxSketchPenPoints { + last := dr.points[len(dr.points)-1] + lx, ly := e.WorldToCanvas(last.X, last.Y) + if math.Hypot(float64(canvasX-lx), float64(canvasY-ly)) >= sketchPenStepMinPt { + dr.points = append(dr.points, pt) + } + } + e.notify() + return true +} + +// EndSketchDrag commits the in-progress sketch drag as a numbered mark in scene coordinates, +// or selects the clicked badge when no drag occurred. +func (e *Editor) EndSketchDrag() (SketchMark, bool) { + if e == nil || e.sketch.draft == nil { + return SketchMark{}, false + } + dr := e.sketch.draft + e.sketch.draft = nil + + if !dr.moved && dr.hitMark > 0 { + e.sketch.selectedMark = dr.hitMark + e.notify() + return e.sketch.marks[dr.hitMark-1].Clone(), false + } + + switch dr.tool { + case SketchToolText: + return e.AddSketchText(dr.startWorld.X, dr.startWorld.Y, ""), true + case SketchToolBox: + if !dr.moved { + e.notify() + return SketchMark{}, false + } + x0 := min(dr.startWorld.X, dr.endWorld.X) + y0 := min(dr.startWorld.Y, dr.endWorld.Y) + w := float32(math.Abs(float64(dr.endWorld.X - dr.startWorld.X))) + h := float32(math.Abs(float64(dr.endWorld.Y - dr.startWorld.Y))) + return e.AddSketchBox(x0, y0, w, h, ""), true + case SketchToolArrow: + if !dr.moved { + e.notify() + return SketchMark{}, false + } + return e.AddSketchArrow(dr.startWorld.X, dr.startWorld.Y, dr.endWorld.X, dr.endWorld.Y, ""), true + case SketchToolPen: + if !dr.moved { + e.notify() + return SketchMark{}, false + } + pts := dr.points + if len(pts) == 0 || pts[len(pts)-1] != dr.endWorld { + pts = append(pts, dr.endWorld) + } + return e.AddSketchPen(pts, ""), true + default: + e.notify() + return SketchMark{}, false + } +} + +// CancelSketchDrag cancels an in-progress sketch mark drag without creating a mark. +func (e *Editor) CancelSketchDrag() { + if e == nil || e.sketch.draft == nil { + return + } + e.sketch.draft = nil + e.notify() +} + +// RenderSketchViewportPNG renders the 2D viewport with the numbered sketch marks overlaid +// as a PNG image at scale pixels per point (defaulting to 1 when scale <= 0). +func (e *Editor) RenderSketchViewportPNG(scale float32) ([]byte, int, int, error) { + if e == nil { + return nil, 0, 0, errors.New("editor: nil editor") + } + if scale <= 0 { + scale = 1 + } + if !(scale >= 0.25 && scale <= 4) || !isFiniteFloat32(scale) { + return nil, 0, 0, fmt.Errorf("editor: sketch render scale %v must be between 0.25 and 4", scale) + } + w, h := e.CanvasSize() + var d core.Drawing + d.Scale(scale, scale) + size := core.Size{Width: core.Points(w), Height: core.Points(h)} + + prevForce := e.sketch.forcePNGMarks + e.sketch.forcePNGMarks = true + e.DrawViewport(&d, size) + e.sketch.forcePNGMarks = prevForce + + pw := max(int(math.Round(float64(w*scale))), 1) + ph := max(int(math.Round(float64(h*scale))), 1) + res, err := gamemcp.RenderPNG(d.Ops, pw, ph, e.SpecPalette(nil).Viewport) + if err != nil { + return nil, 0, 0, err + } + pngBytes := res.PNG + if rendered, ok := renderSketchOverlayTextPNG(pngBytes, d.Ops); ok { + pngBytes = rendered + } + return pngBytes, res.Width, res.Height, nil +} + +// SendSketch packages the active sketch marks (in exact scene coordinates), the rendered viewport PNG +// with numbered marks overlaid, and prompt into a SketchAgentRequest, arms the confirmation hold gate +// so scene_edit refuses mutations until the person confirms, and invokes Editor.OnSendSketch if set. +func (e *Editor) SendSketch(prompt string) (SketchAgentRequest, error) { + if e == nil { + return SketchAgentRequest{}, errors.New("editor: nil editor") + } + if len(e.sketch.marks) == 0 { + return SketchAgentRequest{}, ErrSketchEmpty + } + if strings.TrimSpace(prompt) == "" { + prompt = strings.TrimSpace(e.sketch.promptDraft) + } else { + prompt = strings.TrimSpace(prompt) + } + pngBytes, pw, ph, err := e.RenderSketchViewportPNG(1) + if err != nil { + return SketchAgentRequest{}, err + } + sceneName := e.ScenePath + if sceneName == "" && e.Doc != nil { + sceneName = e.Doc.Name + } + if sceneName == "" { + sceneName = "the open scene" + } + req := SketchAgentRequest{ + Scene: sceneName, + ChipLabel: e.SketchChipLabel(), + Prompt: prompt, + View: e.View2D(), + Marks: e.SketchMarks(), + PNG: pngBytes, + Width: pw, + Height: ph, + } + stored := req + stored.Marks = cloneSketchMarks(req.Marks) + stored.PNG = slices.Clone(req.PNG) + e.sketch.lastRequest = &stored + e.sketch.active = false + e.sketch.draft = nil + e.sketch.previewOpen = false + e.sketch.panelOpen = true + e.sketch.hold = SketchHoldPending + e.sketch.reading = nil + e.sketch.promptDraft = "" + e.Status = fmt.Sprintf("Sent %s · waiting for agent reading", req.ChipLabel) + e.notify() + + if e.OnSendSketch != nil { + e.OnSendSketch(req) + } + return req, nil +} + +// LastSketchRequest returns the most recent SketchAgentRequest sent via SendSketch. +func (e *Editor) LastSketchRequest() (SketchAgentRequest, bool) { + if e == nil || e.sketch.lastRequest == nil { + return SketchAgentRequest{}, false + } + req := *e.sketch.lastRequest + req.Marks = cloneSketchMarks(e.sketch.lastRequest.Marks) + req.PNG = slices.Clone(e.sketch.lastRequest.PNG) + return req, true +} + +// SketchHoldState returns the current confirmation hold state of the sketch layer. +func (e *Editor) SketchHoldState() SketchHoldState { + if e == nil || e.sketch.hold == "" { + return SketchHoldNone + } + return e.sketch.hold +} + +// SketchHoldActive reports whether mutating scene MCP edits must hold until the user confirms the sent sketch. +func (e *Editor) SketchHoldActive() bool { + if e == nil { + return false + } + return e.sketch.hold == SketchHoldPending || e.sketch.hold == SketchHoldReading +} + +// SketchApproved reports whether the user clicked Go ahead on the active sketch and allowed agent edits. +func (e *Editor) SketchApproved() bool { + return e != nil && e.sketch.hold == SketchHoldApproved +} + +// SketchReading returns a copy of the agent's posted sketch reading card, or nil when none is open. +func (e *Editor) SketchReading() *SketchReading { + if e == nil { + return nil + } + return e.sketch.reading.Clone() +} + +// PostSketchReading records the agent's restatement of the active sketch marks and assumptions, +// opening the reading card in the Sketch/Agent panel while keeping the scene_edit hold gate active +// until the user answers Go ahead, Correct a mark, or replies in words. +func (e *Editor) PostSketchReading(reading SketchReading) error { + if e == nil { + return errors.New("editor: nil editor") + } + if len(e.sketch.marks) == 0 { + return ErrSketchEmpty + } + if len(reading.Items) == 0 { + return errors.New("editor: sketch reading must include at least one item") + } + if strings.TrimSpace(reading.Summary) == "" { + reading.Summary = "I read your sketch as:" + } + items := make([]SketchReadingItem, len(reading.Items)) + for i, it := range reading.Items { + if it.Number < 1 || it.Number > len(e.sketch.marks) { + return fmt.Errorf("editor: sketch reading item number %d out of range (1..%d)", it.Number, len(e.sketch.marks)) + } + if strings.TrimSpace(it.Text) == "" { + return fmt.Errorf("editor: sketch reading item %d has empty text", it.Number) + } + if strings.TrimSpace(it.Mark) == "" { + it.Mark = e.sketch.marks[it.Number-1].ReadingHeading() + } + items[i] = it + } + assumptions := make([]string, 0, len(reading.Assumptions)) + for _, a := range reading.Assumptions { + if s := strings.TrimSpace(a); s != "" { + assumptions = append(assumptions, s) + } + } + now := time.Now() + if e.Now != nil { + now = e.Now() + } + e.sketch.reading = &SketchReading{ + Summary: strings.TrimSpace(reading.Summary), + Items: items, + Assumptions: assumptions, + PostedAt: now, + } + e.sketch.hold = SketchHoldReading + e.sketch.panelOpen = true + e.Status = "Agent posted sketch reading · choose Go ahead or Correct a mark" + e.notify() + return nil +} + +// ApproveSketchReading answers "Go ahead" on the active sketch reading, releasing the hold gate +// so scene_edit can proceed and preparing a pre-edit review snapshot for Keep / Revert. +func (e *Editor) ApproveSketchReading() error { + if e == nil { + return errors.New("editor: nil editor") + } + if len(e.sketch.marks) == 0 { + return ErrSketchEmpty + } + baseYAML, err := e.SaveYAML() + if err != nil { + return err + } + histStart := 0 + if e.History != nil { + histStart = e.History.cursor + } + e.sketch.hold = SketchHoldApproved + e.sketch.active = false + e.sketch.draft = nil + e.sketch.panelOpen = true + e.sketch.review = &sketchReviewState{ + open: false, + overlayVisible: true, + baseYAML: baseYAML, + historyStart: histStart, + } + e.Status = "Sketch approved · agent may edit the scene" + e.notify() + + if e.OnReplySketchReading != nil { + e.OnReplySketchReading(SketchReadingReply{Action: "approve"}) + } + return nil +} + +// CorrectSketchMark answers "Correct a mark" on the active sketch reading, reopening sketch mode +// with that exact mark selected (defaulting to mark 1 if number <= 0) while keeping the hold gate active. +func (e *Editor) CorrectSketchMark(number int) error { + if e == nil { + return errors.New("editor: nil editor") + } + if len(e.sketch.marks) == 0 { + return ErrSketchEmpty + } + if number <= 0 { + number = 1 + } + if number > len(e.sketch.marks) { + return fmt.Errorf("editor: sketch mark %d out of range (1..%d)", number, len(e.sketch.marks)) + } + e.sketch.selectedMark = number + e.sketch.tool = e.sketch.marks[number-1].Kind + e.sketch.active = true + e.sketch.panelOpen = true + e.sketch.marksHidden = false + e.sketch.attached = true + e.sketch.hold = SketchHoldPending + e.Status = fmt.Sprintf("Correcting mark %d · edit or redraw, then send again", number) + e.notify() + + if e.OnReplySketchReading != nil { + e.OnReplySketchReading(SketchReadingReply{Action: "correct", MarkNumber: number}) + } + return nil +} + +// ReplyToSketchReading answers an agent sketch reading in words. It forwards the message through +// Editor.OnReplySketchReading and releases the hold gate so the agent can apply the clarified edits. +func (e *Editor) ReplyToSketchReading(message string) error { + if e == nil { + return errors.New("editor: nil editor") + } + msg := strings.TrimSpace(message) + if msg == "" { + return errors.New("editor: reply message cannot be empty") + } + if len(e.sketch.marks) == 0 { + return ErrSketchEmpty + } + baseYAML, err := e.SaveYAML() + if err != nil { + return err + } + histStart := 0 + if e.History != nil { + histStart = e.History.cursor + } + e.sketch.hold = SketchHoldApproved + e.sketch.promptDraft = "" + e.sketch.panelOpen = true + if e.sketch.review == nil { + e.sketch.review = &sketchReviewState{ + open: false, + overlayVisible: true, + baseYAML: baseYAML, + historyStart: histStart, + } + } + e.Status = "Replied to agent reading" + e.notify() + + if e.OnReplySketchReading != nil { + e.OnReplySketchReading(SketchReadingReply{Action: "reply", Message: msg}) + } + return nil +} + +// SketchReviewOpen reports whether a post-sketch agent edit review is open. +func (e *Editor) SketchReviewOpen() bool { + return e != nil && e.sketch.review != nil && e.sketch.review.open +} + +// SketchReviewOverlayVisible reports whether the Sketch overlay toggle is enabled during review. +func (e *Editor) SketchReviewOverlayVisible() bool { + if e == nil { + return false + } + if e.sketch.review != nil { + return e.sketch.review.overlayVisible + } + return !e.sketch.marksHidden +} + +// SetSketchReviewOverlayVisible toggles the Sketch overlay in review (laying the faint dotted sketch over the result). +func (e *Editor) SetSketchReviewOverlayVisible(on bool) { + if e == nil { + return + } + if e.sketch.review == nil { + e.sketch.marksHidden = !on + e.notify() + return + } + if e.sketch.review.overlayVisible == on { + return + } + e.sketch.review.overlayVisible = on + e.notify() +} + +// ToggleSketchReviewOverlay flips the Sketch overlay visibility during review. +func (e *Editor) ToggleSketchReviewOverlay() { + if e == nil { + return + } + e.SetSketchReviewOverlayVisible(!e.SketchReviewOverlayVisible()) +} + +// SketchReviewChanges returns the changes recorded in the active post-sketch review. +func (e *Editor) SketchReviewChanges() []SketchReviewChange { + if e == nil || e.sketch.review == nil { + return nil + } + return slices.Clone(e.sketch.review.changes) +} + +// RecordSketchReviewEdits records scene edits performed by the agent after the user approved a sketch, +// opening the review card with the Sketch overlay toggle enabled so the person can Keep or Revert. +func (e *Editor) RecordSketchReviewEdits(label string, addedIDs, changedIDs, removedIDs []string) { + if e == nil || !e.SketchApproved() { + return + } + if e.sketch.review == nil { + e.sketch.review = &sketchReviewState{overlayVisible: true} + } + rv := e.sketch.review + rv.open = true + if label != "" { + rv.undoLabels = append(rv.undoLabels, label) + } + addChange := func(kind SketchReviewChangeKind, id, detail string) { + if id == "" { + return + } + for i := range rv.changes { + if rv.changes[i].ID == id && rv.changes[i].Kind == kind { + if detail != "" { + rv.changes[i].Detail = detail + } + return + } + } + rv.changes = append(rv.changes, SketchReviewChange{Kind: kind, ID: id, Detail: detail}) + } + for _, id := range addedIDs { + addChange(SketchChangeAdded, id, label) + } + for _, id := range changedIDs { + addChange(SketchChangeChanged, id, label) + } + for _, id := range removedIDs { + addChange(SketchChangeRemoved, id, label) + } + if len(rv.changes) == 0 && label != "" { + rv.changes = append(rv.changes, SketchReviewChange{Kind: SketchChangeChanged, ID: label}) + } + e.sketch.panelOpen = true + e.notify() +} + +// KeepSketchReview keeps the agent's scene edits from the active sketch review, closes the review, +// and clears the sketch layer (marks, reading card, and hold). +func (e *Editor) KeepSketchReview() error { + if e == nil { + return errors.New("editor: nil editor") + } + if e.playing { + return ErrPlaying + } + if !e.SketchReviewOpen() { + return ErrNoSketchReview + } + count := len(e.sketch.review.changes) + e.sketch.review = nil + e.clearSketchOnReviewKeep() + e.Status = fmt.Sprintf("Kept %d agent changes · sketch cleared", count) + e.notify() + return nil +} + +// RevertSketchReview reverts the agent's scene edits back to the pre-approval scene snapshot, +// closes the review, and KEEPS the sketch marks intact so the user can send them again. +func (e *Editor) RevertSketchReview() error { + if e == nil { + return errors.New("editor: nil editor") + } + if e.playing { + return ErrPlaying + } + if !e.SketchReviewOpen() { + return ErrNoSketchReview + } + rv := e.sketch.review + e.sketch.review = nil + + if len(rv.baseYAML) > 0 { + doc, err := sceneformat.ParseWith(rv.baseYAML, sceneformat.ParseOptions{Components: e.ComponentRegistry()}) + if err != nil { + return fmt.Errorf("editor: revert sketch review: %w", err) + } + e.Doc = doc + if e.History != nil && rv.historyStart >= 0 && rv.historyStart <= len(e.History.commands) { + clear(e.History.commands[rv.historyStart:]) + e.History.commands = e.History.commands[:rv.historyStart] + e.History.cursor = rv.historyStart + } + e.Rebuild() + } + e.keepSketchOnReviewRevert() + e.Status = "Reverted agent changes · sketch kept to send again" + e.notify() + return nil +} + +// clearSketchOnReviewKeep clears the sketch layer when any agent review (sketch review or tile review) is Kept. +func (e *Editor) clearSketchOnReviewKeep() { + if e == nil { + return + } + e.sketch.active = false + e.sketch.marks = nil + e.sketch.undoStack = nil + e.sketch.selectedMark = 0 + e.sketch.attached = false + e.sketch.previewOpen = false + e.sketch.draft = nil + e.sketch.hold = SketchHoldNone + e.sketch.reading = nil + e.sketch.lastRequest = nil + e.sketch.panelOpen = false +} + +// keepSketchOnReviewRevert preserves the sketch marks ready to send again when an agent review is Reverted. +func (e *Editor) keepSketchOnReviewRevert() { + if e == nil { + return + } + e.sketch.active = false + e.sketch.draft = nil + e.sketch.hold = SketchHoldNone + e.sketch.reading = nil + if len(e.sketch.marks) > 0 { + e.sketch.attached = true + e.sketch.marksHidden = false + e.sketch.panelOpen = true + } +} + +// drawSketchOverlay renders the viewport sketch layer (strokes, numbered badges, labels, in-progress drag preview, +// and review comparison outlines) in canvas coordinates projected from scene coordinates via WorldToCanvas. +func (e *Editor) drawSketchOverlay(d *core.Drawing) { + if e == nil || d == nil || e.playing || e.ViewMode != ViewMode2D { + return + } + spec := e.SpecPalette(nil) + + inReview := e.SketchReviewOpen() || e.TileReviewOpen() + if e.SketchReviewOpen() { + e.drawSketchReviewChangeOutlines(d, spec) + } + + hasMarks := len(e.sketch.marks) > 0 || e.sketch.draft != nil + if !hasMarks { + return + } + if !e.sketch.forcePNGMarks { + if inReview { + if !e.SketchReviewOverlayVisible() { + return + } + } else if e.sketch.marksHidden { + return + } + } + + reviewDotted := inReview && !e.sketch.forcePNGMarks && !e.sketch.active + alpha := float32(1.0) + if !e.sketch.active && !e.sketch.forcePNGMarks { + if reviewDotted { + alpha = 0.45 + } else { + alpha = 0.65 + } + } + + d.Save() + for _, m := range e.sketch.marks { + selected := e.sketch.active && m.Number == e.sketch.selectedMark && !e.sketch.forcePNGMarks + e.drawSketchMark(d, spec, m, selected, reviewDotted, alpha) + } + if e.sketch.draft != nil && !e.sketch.forcePNGMarks { + e.drawSketchDraft(d, spec, e.sketch.draft) + } + d.Restore() +} + +func (e *Editor) drawSketchReviewChangeOutlines(d *core.Drawing, spec SpecPalette) { + scene := e.ActiveScene() + if scene == nil || e.sketch.review == nil { + return + } + d.Save() + d.SetLineWidth(2) + d.SetLineDash(6, 4) + for _, ch := range e.sketch.review.changes { + bo := scene.Object(ch.ID) + if bo == nil || bo.Doc == nil { + continue + } + space := sceneformat.SpaceWorld + var px, py float32 = 1, 1 + if layer := scene.Layer(bo.Layer); layer != nil { + space, px, py = layer.Space, layer.ParallaxX, layer.ParallaxY + } + m := e.layerAffineFor(space, px, py).Mul(bo.World) + rx, ry, rw, rh := objectOutline(bo) + pts := [4]struct{ x, y float32 }{ + {rx - 4, ry - 4}, + {rx + rw + 4, ry - 4}, + {rx + rw + 4, ry + rh + 4}, + {rx - 4, ry + rh + 4}, + } + var cpts [4]struct{ x, y float32 } + for i, pt := range pts { + v := m.TransformPoint(math2d.Vec2{X: pt.x, Y: pt.y}) + cpts[i] = struct{ x, y float32 }{v.X, v.Y} + } + col := spec.Changed.Edge + fill := ui.Alpha(spec.Changed.Fg, 0.14) + if ch.Kind == SketchChangeAdded { + col = spec.Added.Edge + fill = ui.Alpha(spec.Added.Fg, 0.16) + } else if ch.Kind == SketchChangeRemoved { + col = spec.Removed.Edge + fill = ui.Alpha(spec.Removed.Fg, 0.16) + } + d.SetFillColor(fill) + d.BeginPath().MoveTo(cpts[0].x, cpts[0].y).LineTo(cpts[1].x, cpts[1].y).LineTo(cpts[2].x, cpts[2].y).LineTo(cpts[3].x, cpts[3].y).ClosePath().Fill() + d.SetStrokeColor(col) + d.BeginPath().MoveTo(cpts[0].x, cpts[0].y).LineTo(cpts[1].x, cpts[1].y).LineTo(cpts[2].x, cpts[2].y).LineTo(cpts[3].x, cpts[3].y).ClosePath().Stroke() + } + d.SetLineDash() + d.Restore() +} + +func (e *Editor) drawSketchDraft(d *core.Drawing, spec SpecPalette, dr *sketchDraftDrag) { + if !dr.moved { + return + } + preview := SketchMark{Number: len(e.sketch.marks) + 1, Kind: dr.tool} + switch dr.tool { + case SketchToolBox: + r := SketchRect{ + X: min(dr.startWorld.X, dr.endWorld.X), + Y: min(dr.startWorld.Y, dr.endWorld.Y), + Width: float32(math.Abs(float64(dr.endWorld.X - dr.startWorld.X))), + Height: float32(math.Abs(float64(dr.endWorld.Y - dr.startWorld.Y))), + } + preview.Rect = &r + case SketchToolArrow: + s, t := dr.startWorld, dr.endWorld + preview.Start, preview.End = &s, &t + case SketchToolPen: + pts := slices.Clone(dr.points) + pts = append(pts, dr.endWorld) + preview.Points = pts + default: + return + } + e.drawSketchMark(d, spec, preview, true, false, 0.9) +} + +func (e *Editor) drawSketchMark(d *core.Drawing, spec SpecPalette, m SketchMark, selected, reviewDotted bool, alpha float32) { + haloColor := core.RGBA(0x000000, 0.55*alpha) + haloWidth := float32(5) + if selected { + haloColor = ui.Alpha(spec.Accent.Edge, 0.75) + haloWidth = 6 + } + strokeColor := ui.Alpha(spec.TextPrimary, alpha) + strokeWidth := float32(2) + if reviewDotted { + strokeWidth = 2.5 + } + + strokeGeometry := func(col core.Color, width float32, dotted bool) { + d.SetStrokeColor(col).SetLineWidth(width) + if dotted { + d.SetLineDash(2, 6) + } else { + d.SetLineDash() + } + switch m.Kind { + case SketchToolBox: + if m.Rect == nil { + return + } + pts := worldRectCanvasCorners(e, m.Rect.X, m.Rect.Y, m.Rect.Width, m.Rect.Height) + strokePolygon(d, pts) + case SketchToolPen: + if len(m.Points) < 2 { + return + } + x0, y0 := e.WorldToCanvas(m.Points[0].X, m.Points[0].Y) + d.BeginPath().MoveTo(x0, y0) + for _, pt := range m.Points[1:] { + cx, cy := e.WorldToCanvas(pt.X, pt.Y) + d.LineTo(cx, cy) + } + d.Stroke() + case SketchToolArrow: + if m.Start == nil || m.End == nil { + return + } + x0, y0 := e.WorldToCanvas(m.Start.X, m.Start.Y) + x1, y1 := e.WorldToCanvas(m.End.X, m.End.Y) + d.BeginPath().MoveTo(x0, y0).LineTo(x1, y1).Stroke() + dx, dy := x1-x0, y1-y0 + dist := float32(math.Hypot(float64(dx), float64(dy))) + if dist > 4 { + ux, uy := dx/dist, dy/dist + const headLen float32 = 11 + const headHalfW float32 = 6 + bx, by := x1-ux*headLen, y1-uy*headLen + px, py := -uy*headHalfW, ux*headHalfW + d.BeginPath().MoveTo(bx+px, by+py).LineTo(x1, y1).LineTo(bx-px, by-py).Stroke() + } + case SketchToolText: + if m.At == nil { + return + } + cx, cy := e.WorldToCanvas(m.At.X, m.At.Y) + d.SetFillColor(col) + d.BeginPath().Arc(cx, cy, 4, 0, float32(2*math.Pi), false).Fill() + } + } + + if !reviewDotted { + strokeGeometry(haloColor, haloWidth, false) + } + strokeGeometry(strokeColor, strokeWidth, reviewDotted) + d.SetLineDash() + + if reviewDotted { + return + } + + // Draw sequential numbered badge ("1", "2", "3", ...). + bx, by := e.sketchBadgeCanvasPos(m) + badgeFill := ui.Alpha(spec.TextPrimary, alpha) + badgeInk := spec.OnTextPrimary + if selected { + badgeFill = spec.Accent.Fg + badgeInk = spec.Accent.OnFill + d.SetStrokeColor(spec.TextPrimary).SetLineWidth(1.5) + d.BeginPath().Arc(bx, by, sketchBadgeRadiusPt+2.5, 0, float32(2*math.Pi), false).Stroke() + } + d.SetFillColor(badgeFill) + d.BeginPath().Arc(bx, by, sketchBadgeRadiusPt, 0, float32(2*math.Pi), false).Fill() + numStr := strconv.Itoa(m.Number) + badgeFont := core.Font{Size: 11, Weight: 600} + tx := bx - float32(len(numStr))*3.2 + ty := by + 3.5 + d.SetFillColor(badgeInk).FillText(numStr, tx, ty, badgeFont) + + // Draw optional label pill next to the badge. + if label := strings.TrimSpace(m.Label); label != "" { + lx := bx + sketchBadgeRadiusPt + 6 + ly := by - 9 + pw := float32(len([]rune(label)))*5.8 + 14 + const ph float32 = 18 + d.SetFillColor(ui.Alpha(spec.PillBg, 0.88*alpha)) + d.BeginPath().Rect(lx, ly, pw, ph).Fill() + d.SetFillColor(ui.Alpha(spec.TextPrimary, alpha)).FillText(label, lx+6, ly+12.5, core.Font{Size: 11.5, Weight: 500}) + } +} diff --git a/packages/game/editor/sketch_png.go b/packages/game/editor/sketch_png.go new file mode 100644 index 000000000..6f31ff8f2 --- /dev/null +++ b/packages/game/editor/sketch_png.go @@ -0,0 +1,275 @@ +package editor + +import ( + "bytes" + "image" + "image/draw" + "image/png" + "math" + + "github.com/nsgo-dev/nsgo/core" +) + +const maxSketchTextPixScale = 16 + +// sketchBitmapGlyph5x7 holds a compact 5x7 pixel font (rows top-to-bottom, 5 bits wide MSB-first) +// used by RenderSketchViewportPNG to rasterize numbered mark badges and labels onto software PNGs. +var sketchBitmapGlyph5x7 = map[rune][7]uint8{ + ' ': {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + '!': {0x04, 0x04, 0x04, 0x04, 0x04, 0x00, 0x04}, + '"': {0x0A, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00}, + '#': {0x0A, 0x1F, 0x0A, 0x0A, 0x1F, 0x0A, 0x00}, + '$': {0x04, 0x0F, 0x14, 0x0E, 0x05, 0x1E, 0x04}, + '%': {0x18, 0x19, 0x02, 0x04, 0x08, 0x13, 0x03}, + '&': {0x08, 0x14, 0x14, 0x08, 0x15, 0x12, 0x0D}, + '\'': {0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00}, + '(': {0x02, 0x04, 0x08, 0x08, 0x08, 0x04, 0x02}, + ')': {0x08, 0x04, 0x02, 0x02, 0x02, 0x04, 0x08}, + '*': {0x00, 0x04, 0x15, 0x0E, 0x15, 0x04, 0x00}, + '+': {0x00, 0x04, 0x04, 0x1F, 0x04, 0x04, 0x00}, + ',': {0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x08}, + '-': {0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00}, + '.': {0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C}, + '/': {0x01, 0x01, 0x02, 0x04, 0x08, 0x10, 0x10}, + '0': {0x0E, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0E}, + '1': {0x04, 0x0C, 0x04, 0x04, 0x04, 0x04, 0x0E}, + '2': {0x0E, 0x11, 0x01, 0x02, 0x04, 0x08, 0x1F}, + '3': {0x1F, 0x02, 0x04, 0x02, 0x01, 0x11, 0x0E}, + '4': {0x02, 0x06, 0x0A, 0x12, 0x1F, 0x02, 0x02}, + '5': {0x1F, 0x10, 0x1E, 0x01, 0x01, 0x11, 0x0E}, + '6': {0x06, 0x08, 0x10, 0x1E, 0x11, 0x11, 0x0E}, + '7': {0x1F, 0x01, 0x02, 0x04, 0x08, 0x08, 0x08}, + '8': {0x0E, 0x11, 0x11, 0x0E, 0x11, 0x11, 0x0E}, + '9': {0x0E, 0x11, 0x11, 0x0F, 0x01, 0x02, 0x0C}, + ':': {0x00, 0x04, 0x04, 0x00, 0x04, 0x04, 0x00}, + ';': {0x00, 0x04, 0x04, 0x00, 0x04, 0x04, 0x08}, + '<': {0x02, 0x04, 0x08, 0x10, 0x08, 0x04, 0x02}, + '=': {0x00, 0x00, 0x1F, 0x00, 0x1F, 0x00, 0x00}, + '>': {0x08, 0x04, 0x02, 0x01, 0x02, 0x04, 0x08}, + '?': {0x0E, 0x11, 0x01, 0x02, 0x04, 0x00, 0x04}, + '@': {0x0E, 0x11, 0x17, 0x15, 0x17, 0x10, 0x0E}, + 'A': {0x0E, 0x11, 0x11, 0x1F, 0x11, 0x11, 0x11}, + 'B': {0x1E, 0x11, 0x11, 0x1E, 0x11, 0x11, 0x1E}, + 'C': {0x0E, 0x11, 0x10, 0x10, 0x10, 0x11, 0x0E}, + 'D': {0x1E, 0x11, 0x11, 0x11, 0x11, 0x11, 0x1E}, + 'E': {0x1F, 0x10, 0x10, 0x1E, 0x10, 0x10, 0x1F}, + 'F': {0x1F, 0x10, 0x10, 0x1E, 0x10, 0x10, 0x10}, + 'G': {0x0E, 0x11, 0x10, 0x17, 0x11, 0x11, 0x0F}, + 'H': {0x11, 0x11, 0x11, 0x1F, 0x11, 0x11, 0x11}, + 'I': {0x0E, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0E}, + 'J': {0x07, 0x02, 0x02, 0x02, 0x02, 0x12, 0x0C}, + 'K': {0x11, 0x12, 0x14, 0x18, 0x14, 0x12, 0x11}, + 'L': {0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1F}, + 'M': {0x11, 0x1B, 0x15, 0x15, 0x11, 0x11, 0x11}, + 'N': {0x11, 0x19, 0x15, 0x13, 0x11, 0x11, 0x11}, + 'O': {0x0E, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0E}, + 'P': {0x1E, 0x11, 0x11, 0x1E, 0x10, 0x10, 0x10}, + 'Q': {0x0E, 0x11, 0x11, 0x11, 0x15, 0x12, 0x0D}, + 'R': {0x1E, 0x11, 0x11, 0x1E, 0x14, 0x12, 0x11}, + 'S': {0x0F, 0x10, 0x10, 0x0E, 0x01, 0x01, 0x1E}, + 'T': {0x1F, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04}, + 'U': {0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0E}, + 'V': {0x11, 0x11, 0x11, 0x11, 0x11, 0x0A, 0x04}, + 'W': {0x11, 0x11, 0x11, 0x15, 0x15, 0x1B, 0x11}, + 'X': {0x11, 0x11, 0x0A, 0x04, 0x0A, 0x11, 0x11}, + 'Y': {0x11, 0x11, 0x0A, 0x04, 0x04, 0x04, 0x04}, + 'Z': {0x1F, 0x01, 0x02, 0x04, 0x08, 0x10, 0x1F}, + '[': {0x0E, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0E}, + '\\': {0x10, 0x10, 0x08, 0x04, 0x02, 0x01, 0x01}, + ']': {0x0E, 0x02, 0x02, 0x02, 0x02, 0x02, 0x0E}, + '^': {0x04, 0x0A, 0x11, 0x00, 0x00, 0x00, 0x00}, + '_': {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F}, + 'a': {0x00, 0x00, 0x0E, 0x01, 0x0F, 0x11, 0x0F}, + 'b': {0x10, 0x10, 0x1E, 0x11, 0x11, 0x11, 0x1E}, + 'c': {0x00, 0x00, 0x0E, 0x10, 0x10, 0x11, 0x0E}, + 'd': {0x01, 0x01, 0x0F, 0x11, 0x11, 0x11, 0x0F}, + 'e': {0x00, 0x00, 0x0E, 0x11, 0x1F, 0x10, 0x0E}, + 'f': {0x06, 0x08, 0x1E, 0x08, 0x08, 0x08, 0x08}, + 'g': {0x00, 0x00, 0x0F, 0x11, 0x0F, 0x01, 0x0E}, + 'h': {0x10, 0x10, 0x1E, 0x11, 0x11, 0x11, 0x11}, + 'i': {0x04, 0x00, 0x0C, 0x04, 0x04, 0x04, 0x0E}, + 'j': {0x02, 0x00, 0x06, 0x02, 0x02, 0x12, 0x0C}, + 'k': {0x10, 0x10, 0x12, 0x14, 0x18, 0x14, 0x12}, + 'l': {0x0C, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0E}, + 'm': {0x00, 0x00, 0x1A, 0x15, 0x15, 0x15, 0x15}, + 'n': {0x00, 0x00, 0x1E, 0x11, 0x11, 0x11, 0x11}, + 'o': {0x00, 0x00, 0x0E, 0x11, 0x11, 0x11, 0x0E}, + 'p': {0x00, 0x00, 0x1E, 0x11, 0x1E, 0x10, 0x10}, + 'q': {0x00, 0x00, 0x0F, 0x11, 0x0F, 0x01, 0x01}, + 'r': {0x00, 0x00, 0x16, 0x19, 0x10, 0x10, 0x10}, + 's': {0x00, 0x00, 0x0F, 0x10, 0x0E, 0x01, 0x1E}, + 't': {0x08, 0x08, 0x1E, 0x08, 0x08, 0x09, 0x06}, + 'u': {0x00, 0x00, 0x11, 0x11, 0x11, 0x13, 0x0D}, + 'v': {0x00, 0x00, 0x11, 0x11, 0x11, 0x0A, 0x04}, + 'w': {0x00, 0x00, 0x11, 0x11, 0x15, 0x15, 0x0A}, + 'x': {0x00, 0x00, 0x11, 0x0A, 0x04, 0x0A, 0x11}, + 'y': {0x00, 0x00, 0x11, 0x11, 0x0F, 0x01, 0x0E}, + 'z': {0x00, 0x00, 0x1F, 0x02, 0x04, 0x08, 0x1F}, + '→': {0x00, 0x04, 0x02, 0x1F, 0x02, 0x04, 0x00}, + '×': {0x00, 0x11, 0x0A, 0x04, 0x0A, 0x11, 0x00}, + '·': {0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00}, +} + +type sketchTextAffine struct { + a, b, c, d, e, f float64 +} + +func (m sketchTextAffine) mul(n sketchTextAffine) sketchTextAffine { + return sketchTextAffine{ + a: m.a*n.a + m.c*n.b, + b: m.b*n.a + m.d*n.b, + c: m.a*n.c + m.c*n.d, + d: m.b*n.c + m.d*n.d, + e: m.a*n.e + m.c*n.f + m.e, + f: m.b*n.e + m.d*n.f + m.f, + } +} + +func (m sketchTextAffine) apply(x, y float64) (float64, float64) { + return m.a*x + m.c*y + m.e, m.b*x + m.d*y + m.f +} + +// renderSketchOverlayTextPNG replays DrawFillText operations from ops onto pngBytes so +// numbered sketch badges and labels appear clearly in PNGs sent to the agent. +func renderSketchOverlayTextPNG(pngBytes []byte, ops []core.DrawOp) ([]byte, bool) { + src, err := png.Decode(bytes.NewReader(pngBytes)) + if err != nil { + return pngBytes, false + } + b := src.Bounds() + dst := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy())) + draw.Draw(dst, dst.Bounds(), src, b.Min, draw.Src) + + type state struct { + m sketchTextAffine + color core.Color + alpha float64 + } + cur := state{ + m: sketchTextAffine{a: 1, d: 1}, + color: core.RGB(0xFFFFFF), + alpha: 1, + } + var stack []state + drewAny := false + + for _, op := range ops { + switch op.Kind { + case core.DrawSave: + stack = append(stack, cur) + case core.DrawRestore: + if n := len(stack); n > 0 { + cur = stack[n-1] + stack = stack[:n-1] + } + case core.DrawTranslate: + cur.m = cur.m.mul(sketchTextAffine{a: 1, d: 1, e: float64(op.X), f: float64(op.Y)}) + case core.DrawScale: + cur.m = cur.m.mul(sketchTextAffine{a: float64(op.X), d: float64(op.Y)}) + case core.DrawRotate: + sn, cs := math.Sincos(float64(op.A)) + cur.m = cur.m.mul(sketchTextAffine{a: cs, b: sn, c: -sn, d: cs}) + case core.DrawTransform: + cur.m = cur.m.mul(sketchTextAffine{ + a: float64(op.X1), b: float64(op.Y1), + c: float64(op.X2), d: float64(op.Y2), + e: float64(op.X), f: float64(op.Y), + }) + case core.DrawSetTransform: + cur.m = sketchTextAffine{ + a: float64(op.X1), b: float64(op.Y1), + c: float64(op.X2), d: float64(op.Y2), + e: float64(op.X), f: float64(op.Y), + } + case core.DrawFillColor: + cur.color = op.Color + case core.DrawAlpha: + cur.alpha = min(max(float64(op.A), 0), 1) + case core.DrawFillText: + if op.Text == "" { + continue + } + px, py := cur.m.apply(float64(op.X), float64(op.Y)) + scale := math.Sqrt(math.Hypot(cur.m.a, cur.m.b) * math.Hypot(cur.m.c, cur.m.d)) + if math.IsNaN(px) || math.IsInf(px, 0) || math.IsNaN(py) || math.IsInf(py, 0) || math.IsNaN(scale) || math.IsInf(scale, 0) { + continue + } + if math.Abs(px) > 1e7 || math.Abs(py) > 1e7 { + continue + } + if scale < 1 { + scale = 1 + } else if scale > maxSketchTextPixScale { + scale = maxSketchTextPixScale + } + pixScale := int(math.Round(scale)) + ox := int(math.Round(px)) + oy := int(math.Round(py)) - 7*pixScale + drawSketchBitmapString(dst, ox, oy, op.Text, cur.color, cur.alpha, pixScale) + drewAny = true + } + } + if !drewAny { + return pngBytes, false + } + var out bytes.Buffer + if err := png.Encode(&out, dst); err != nil { + return pngBytes, false + } + return out.Bytes(), true +} + +func drawSketchBitmapString(dst *image.RGBA, x, y int, text string, col core.Color, alpha float64, scale int) { + a := float64(col&0xFF) / 255.0 * alpha + if a <= 0 { + return + } + r := float64((col>>24)&0xFF) / 255.0 + g := float64((col>>16)&0xFF) / 255.0 + b := float64((col>>8)&0xFF) / 255.0 + sr, sg, sb, sa := r*a, g*a, b*a, a + + bounds := dst.Bounds() + cx := x + for _, ch := range text { + glyph, ok := sketchBitmapGlyph5x7[ch] + if !ok { + if ch >= 'a' && ch <= 'z' { + glyph = sketchBitmapGlyph5x7[ch-'a'+'A'] + } else { + glyph = sketchBitmapGlyph5x7[' '] + } + } + for row := range 7 { + bits := glyph[row] + for colIdx := range 5 { + if bits&(1<<(4-colIdx)) == 0 { + continue + } + for sy := range scale { + py := y + row*scale + sy + if py < bounds.Min.Y || py >= bounds.Max.Y { + continue + } + for sx := range scale { + px := cx + colIdx*scale + sx + if px < bounds.Min.X || px >= bounds.Max.X { + continue + } + off := (py-bounds.Min.Y)*dst.Stride + (px-bounds.Min.X)*4 + inv := 1 - sa + dr := float64(dst.Pix[off])/255.0*inv + sr + dg := float64(dst.Pix[off+1])/255.0*inv + sg + db := float64(dst.Pix[off+2])/255.0*inv + sb + da := float64(dst.Pix[off+3])/255.0*inv + sa + dst.Pix[off] = uint8(min(max(math.Round(dr*255), 0), 255)) + dst.Pix[off+1] = uint8(min(max(math.Round(dg*255), 0), 255)) + dst.Pix[off+2] = uint8(min(max(math.Round(db*255), 0), 255)) + dst.Pix[off+3] = uint8(min(max(math.Round(da*255), 0), 255)) + } + } + } + } + cx += 6 * scale + } +} diff --git a/packages/game/editor/sketch_test.go b/packages/game/editor/sketch_test.go new file mode 100644 index 000000000..bcb400c77 --- /dev/null +++ b/packages/game/editor/sketch_test.go @@ -0,0 +1,524 @@ +package editor_test + +import ( + "bytes" + "image/png" + "math" + "strings" + "testing" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func newSketchTestEditor(t *testing.T) *editor.Editor { + t.Helper() + doc := &sceneformat.SceneDoc{ + Version: sceneformat.CurrentVersion, + Name: "level_01", + VirtualWidth: 640, + VirtualHeight: 360, + BackgroundColor: "#15181D", + Camera: &sceneformat.CameraDoc{ + X: 320, + Y: 180, + }, + Layers: []sceneformat.LayerDoc{ + { + Name: "World", + Space: sceneformat.SpaceWorld, + Objects: []sceneformat.ObjectDoc{ + {ID: "floor", Name: "Floor", X: 320, Y: 320}, + {ID: "ledge_02", Name: "ledge_02", X: 540, Y: 190}, + }, + }, + { + Name: "Actors", + Space: sceneformat.SpaceWorld, + Objects: []sceneformat.ObjectDoc{ + {ID: "player", Name: "Player", X: 110, Y: 280}, + {ID: "knight", Name: "Knight", X: 400, Y: 224}, + {ID: "door", Name: "Door", X: 530, Y: 280}, + }, + }, + }, + } + ed, err := editor.New(doc, nil) + if err != nil { + t.Fatalf("editor.New: %v", err) + } + ed.SetCanvasSize(640, 360) + return ed +} + +func assertSketchNear(t *testing.T, label string, got, want, tol float32) { + t.Helper() + if math.Abs(float64(got-want)) > float64(tol) { + t.Fatalf("%s = %v, want %v (±%v)", label, got, want, tol) + } +} + +// #1025 Acceptance 1: A test draws a box, an arrow and a text mark, sends them, and the scripted +// agent receives three marks with scene coordinates that match the viewport at two zoom levels +// (plus a rendered PNG with the marks overlaid), while scene YAML never contains sketch marks. +func TestSketchDrawBoxArrowTextAndSendAtTwoZoomLevels(t *testing.T) { + ed := newSketchTestEditor(t) + + initialYAML, err := ed.SaveYAML() + if err != nil { + t.Fatalf("SaveYAML: %v", err) + } + cleanPNG, _, _, err := ed.RenderSketchViewportPNG(1) + if err != nil { + t.Fatalf("RenderSketchViewportPNG(clean): %v", err) + } + + var received []editor.SketchAgentRequest + ed.OnSendSketch = func(req editor.SketchAgentRequest) { + received = append(received, req) + } + + // Zoom level 1: 1.0x centered on (320, 180). + ed.SetView2D(editor.View2D{X: 320, Y: 180, Zoom: 1.0}) + ed.StartSketch() + + // Draw Box via canvas drag at zoom 1.0. + ed.SetSketchTool(editor.SketchToolBox) + if !ed.BeginSketchDrag(171, 269) || !ed.UpdateSketchDrag(280, 302) { + t.Fatal("Begin/UpdateSketchDrag for box failed") + } + m1, ok := ed.EndSketchDrag() + if !ok || m1.Number != 1 || m1.Kind != editor.SketchToolBox || m1.Rect == nil { + t.Fatalf("box mark = (%+v, %v)", m1, ok) + } + ed.SetSketchMarkLabel(1, "3 spikes") + + // Draw Arrow via canvas drag at zoom 1.0. + ed.SetSketchTool(editor.SketchToolArrow) + if !ed.BeginSketchDrag(465, 111) || !ed.UpdateSketchDrag(533, 242) { + t.Fatal("Begin/UpdateSketchDrag for arrow failed") + } + m2, ok := ed.EndSketchDrag() + if !ok || m2.Number != 2 || m2.Kind != editor.SketchToolArrow || m2.Start == nil || m2.End == nil { + t.Fatalf("arrow mark = (%+v, %v)", m2, ok) + } + ed.SetSketchMarkLabel(2, "locked until the lever") + + // Place Text mark via canvas click at zoom 1.0. + ed.SetSketchTool(editor.SketchToolText) + if !ed.BeginSketchDrag(490, 170) { + t.Fatal("BeginSketchDrag for text failed") + } + m3, ok := ed.EndSketchDrag() + if !ok || m3.Number != 3 || m3.Kind != editor.SketchToolText || m3.At == nil { + t.Fatalf("text mark = (%+v, %v)", m3, ok) + } + ed.SetSketchMarkLabel(3, "platform, back and forth") + + if ed.SketchBarCountLabel() != "3 marks not saved" { + t.Fatalf("SketchBarCountLabel = %q, want %q", ed.SketchBarCountLabel(), "3 marks not saved") + } + if ed.SketchChipLabel() != "Sketch · 3 marks" { + t.Fatalf("SketchChipLabel = %q, want %q", ed.SketchChipLabel(), "Sketch · 3 marks") + } + + req1, err := ed.SendSketch("Build what I sketched.") + if err != nil { + t.Fatalf("SendSketch zoom 1: %v", err) + } + if len(received) != 1 || len(req1.Marks) != 3 { + t.Fatalf("received=%d marks=%d, want 1 / 3", len(received), len(req1.Marks)) + } + if req1.ChipLabel != "Sketch · 3 marks" { + t.Fatalf("ChipLabel = %q, want Sketch · 3 marks", req1.ChipLabel) + } + // Verify exact scene coordinates match CanvasToWorld at zoom 1.0. + bx0, by0 := ed.CanvasToWorld(171, 269) + bx1, by1 := ed.CanvasToWorld(280, 302) + assertSketchNear(t, "zoom1 box.X", req1.Marks[0].Rect.X, bx0, 0.01) + assertSketchNear(t, "zoom1 box.Y", req1.Marks[0].Rect.Y, by0, 0.01) + assertSketchNear(t, "zoom1 box.W", req1.Marks[0].Rect.Width, bx1-bx0, 0.01) + assertSketchNear(t, "zoom1 box.H", req1.Marks[0].Rect.Height, by1-by0, 0.01) + + ax0, ay0 := ed.CanvasToWorld(465, 111) + ax1, ay1 := ed.CanvasToWorld(533, 242) + assertSketchNear(t, "zoom1 arrow.Start.X", req1.Marks[1].Start.X, ax0, 0.01) + assertSketchNear(t, "zoom1 arrow.Start.Y", req1.Marks[1].Start.Y, ay0, 0.01) + assertSketchNear(t, "zoom1 arrow.End.X", req1.Marks[1].End.X, ax1, 0.01) + assertSketchNear(t, "zoom1 arrow.End.Y", req1.Marks[1].End.Y, ay1, 0.01) + + tx, ty := ed.CanvasToWorld(490, 170) + assertSketchNear(t, "zoom1 text.At.X", req1.Marks[2].At.X, tx, 0.01) + assertSketchNear(t, "zoom1 text.At.Y", req1.Marks[2].At.Y, ty, 0.01) + + // Verify PNG is a valid image that visibly differs from the unmarked viewport PNG. + img1, err := png.Decode(bytes.NewReader(req1.PNG)) + if err != nil { + t.Fatalf("decode sketch PNG zoom 1: %v", err) + } + if img1.Bounds().Dx() != 640 || img1.Bounds().Dy() != 360 { + t.Fatalf("sketch PNG bounds = %v, want 640x360", img1.Bounds()) + } + if bytes.Equal(req1.PNG, cleanPNG) { + t.Fatal("rendered sketch PNG is identical to unmarked viewport PNG") + } + + // Zoom level 2: 2.0x panned to (400, 210). + // First verify the existing marks project accurately via WorldToCanvas at zoom 2.0 without shifting scene coords. + ed.SetView2D(editor.View2D{X: 400, Y: 210, Zoom: 2.0}) + cx2, cy2 := ed.WorldToCanvas(req1.Marks[0].Rect.X, req1.Marks[0].Rect.Y) + backX, backY := ed.CanvasToWorld(cx2, cy2) + assertSketchNear(t, "zoom2 roundtrip X", backX, req1.Marks[0].Rect.X, 0.01) + assertSketchNear(t, "zoom2 roundtrip Y", backY, req1.Marks[0].Rect.Y, 0.01) + + // Clear and draw a fresh Box, Arrow, and Text mark at zoom 2.0, then send and verify exact scene coordinates. + ed.ClearSketch() + ed.StartSketch() + + ed.SetSketchTool(editor.SketchToolBox) + ed.BeginSketchDrag(100, 120) + ed.UpdateSketchDrag(260, 200) + ed.EndSketchDrag() + ed.SetSketchMarkLabel(1, "spikes zoomed") + + ed.SetSketchTool(editor.SketchToolArrow) + ed.BeginSketchDrag(300, 80) + ed.UpdateSketchDrag(460, 240) + ed.EndSketchDrag() + ed.SetSketchMarkLabel(2, "door zoomed") + + ed.SetSketchTool(editor.SketchToolText) + ed.BeginSketchDrag(420, 150) + ed.EndSketchDrag() + ed.SetSketchMarkLabel(3, "note zoomed") + + req2, err := ed.SendSketch("Zoomed sketch") + if err != nil { + t.Fatalf("SendSketch zoom 2: %v", err) + } + if len(received) != 2 || len(req2.Marks) != 3 { + t.Fatalf("zoom 2 received=%d marks=%d, want 2 / 3", len(received), len(req2.Marks)) + } + z2bx0, z2by0 := ed.CanvasToWorld(100, 120) + z2bx1, z2by1 := ed.CanvasToWorld(260, 200) + assertSketchNear(t, "zoom2 box.X", req2.Marks[0].Rect.X, z2bx0, 0.01) + assertSketchNear(t, "zoom2 box.Y", req2.Marks[0].Rect.Y, z2by0, 0.01) + assertSketchNear(t, "zoom2 box.W", req2.Marks[0].Rect.Width, z2bx1-z2bx0, 0.01) + assertSketchNear(t, "zoom2 box.H", req2.Marks[0].Rect.Height, z2by1-z2by0, 0.01) + + z2ax0, z2ay0 := ed.CanvasToWorld(300, 80) + z2ax1, z2ay1 := ed.CanvasToWorld(460, 240) + assertSketchNear(t, "zoom2 arrow.Start.X", req2.Marks[1].Start.X, z2ax0, 0.01) + assertSketchNear(t, "zoom2 arrow.Start.Y", req2.Marks[1].Start.Y, z2ay0, 0.01) + assertSketchNear(t, "zoom2 arrow.End.X", req2.Marks[1].End.X, z2ax1, 0.01) + assertSketchNear(t, "zoom2 arrow.End.Y", req2.Marks[1].End.Y, z2ay1, 0.01) + + z2tx, z2ty := ed.CanvasToWorld(420, 150) + assertSketchNear(t, "zoom2 text.At.X", req2.Marks[2].At.X, z2tx, 0.01) + assertSketchNear(t, "zoom2 text.At.Y", req2.Marks[2].At.Y, z2ty, 0.01) + + // Scene YAML and History must be completely untouched by sketch marks. + afterYAML, err := ed.SaveYAML() + if err != nil { + t.Fatalf("SaveYAML after sketch: %v", err) + } + if !bytes.Equal(initialYAML, afterYAML) { + t.Fatalf("scene YAML mutated by sketch layer:\n%s", string(afterYAML)) + } + if ed.History.Len() != 0 { + t.Fatalf("History.Len() = %d, want 0 (sketch marks must not pollute scene undo history)", ed.History.Len()) + } + if strings.Contains(string(afterYAML), "spikes") || strings.Contains(string(afterYAML), "sketch") { + t.Fatalf("scene YAML leaked sketch content:\n%s", string(afterYAML)) + } +} + +// #1025 Acceptance 2 & 3 + Keyboard paths & UI workflow: +// - Esc finishes sketch mode while keeping marks +// - Keyboard shortcuts switch tools (D, P, A, B, T, I, H) and register in ScopeSketch +// - Reading card displays Go ahead and Correct a mark (reopening sketch with that exact mark selected) +// - Review Sketch overlay toggles, Revert keeps sketch marks, Keep clears sketch layer +// - Compact 2D editor-toolbar stays untouched +func TestSketchUIKeyboardReadingCorrectMarkAndReviewKeepRevert(t *testing.T) { + ed := newSketchTestEditor(t) + macEnv := nsgotest.Environment(core.Environment{OS: core.OSMacOS, Idiom: core.IdiomDesktop, Dark: true, Locale: "en-US"}) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), macEnv) + + // Confirm the 2D editor-toolbar stays compact (no extra sketch button added). + if app.Exists("id:editor-toolbar >> id:tool-sketch") { + t.Fatal("editor-toolbar must stay compact without adding extra sketch buttons") + } + + // Verify all sketch commands are registered with keyboard paths and shortcut rows. + wantCmds := []string{ + editor.CmdSketchToggle, + editor.CmdSketchToolPen, + editor.CmdSketchToolArrow, + editor.CmdSketchToolBox, + editor.CmdSketchToolText, + editor.CmdSketchAddMarkAtCursor, + editor.CmdSketchUndoMark, + editor.CmdSketchToggleMarks, + editor.CmdSketchClear, + editor.CmdSketchDone, + editor.CmdSketchSend, + editor.CmdSketchApproveReading, + editor.CmdSketchCorrectMark, + editor.CmdSketchToggleReviewOverlay, + editor.CmdSketchKeepReview, + editor.CmdSketchRevertReview, + } + for _, id := range wantCmds { + cmd, ok := ed.Command(id) + if !ok { + t.Fatalf("command %q missing from registry", id) + } + if cmd.Shortcut == "" { + t.Fatalf("command %q has no shortcut row", id) + } + } + + // Press 'd' to start Sketch mode. + app.Key("d") + if !ed.SketchActive() { + t.Fatal("pressing 'd' did not activate sketch mode") + } + if !app.Exists("id:viewport-sketch-toolbar") { + t.Fatal("viewport-sketch-toolbar did not appear when sketch mode activated") + } + if !app.Exists("id:scene-tree-sketch-layer") { + t.Fatal("SKETCH LAYER row missing in scene tree") + } + if got := app.Find("id:editor-status-mode").Text; !strings.Contains(got, "Sketch layer") || !strings.Contains(got, "scene") { + t.Fatalf("status bar mode while sketching = %q, want Sketch layer + scene coords", got) + } + + // Keyboard tool switching in ScopeSketch: B (Box), I (add mark at cursor), A (Arrow), I, T (Text), I, P (Pen). + app.Key("b") + if ed.SketchTool() != editor.SketchToolBox { + t.Fatalf("SketchTool after 'b' = %v, want box", ed.SketchTool()) + } + app.Key("i") + app.Key("a") + if ed.SketchTool() != editor.SketchToolArrow { + t.Fatalf("SketchTool after 'a' = %v, want arrow", ed.SketchTool()) + } + app.Key("i") + app.Key("t") + if ed.SketchTool() != editor.SketchToolText { + t.Fatalf("SketchTool after 't' = %v, want text", ed.SketchTool()) + } + app.Key("i") + app.Key("p") + if ed.SketchTool() != editor.SketchToolPen { + t.Fatalf("SketchTool after 'p' = %v, want pen", ed.SketchTool()) + } + if ed.SketchMarkCount() != 3 { + t.Fatalf("SketchMarkCount after keyboard insert = %d, want 3", ed.SketchMarkCount()) + } + if got := app.Find("id:sketch-bar-count").Text; got != "3 marks not saved" { + t.Fatalf("sketch-bar-count = %q, want %q", got, "3 marks not saved") + } + + // Press Esc to finish sketch mode while keeping the 3 marks. + app.Key("escape") + if ed.SketchActive() { + t.Fatal("Escape did not finish sketch mode") + } + if ed.SketchMarkCount() != 3 { + t.Fatalf("Escape cleared sketch marks: got %d, want 3", ed.SketchMarkCount()) + } + if !app.Exists("id:sketch-context-chip") { + t.Fatal("Sketch · 3 marks chip missing in composer after Esc") + } + // Click chip to open "Sent with this request" preview. + app.Press("id:sketch-context-chip") + if !app.Exists("id:sketch-sent-preview") { + t.Fatal("clicking sketch-context-chip did not open Sent with this request preview") + } + + // Send the sketch. + app.Post(func() { + ed.SetSketchMarkLabel(1, "3 spikes") + ed.SetSketchMarkLabel(2, "locked until the lever") + ed.SetSketchMarkLabel(3, "platform, back and forth") + ed.SetSketchPromptDraft("Build what I sketched.") + }) + app.Settle() + app.Press("id:sketch-composer-send") + if !ed.SketchHoldActive() { + t.Fatal("sending sketch did not arm the hold gate") + } + + // Agent posts reading card. + app.Post(func() { + if err := ed.PostSketchReading(editor.SketchReading{ + Items: []editor.SketchReadingItem{ + {Number: 1, Text: "Three spike tiles on the floor."}, + {Number: 2, Text: "Door stays locked until lever_01 is pulled."}, + {Number: 3, Text: "Moving platform between x 487 and 604."}, + }, + Assumptions: []string{ + "There is no lever in level_01 yet. I will add lever_01 left of the plank at x 295 unless you point somewhere else.", + }, + }); err != nil { + t.Errorf("PostSketchReading: %v", err) + } + }) + app.Settle() + if !app.Exists("id:sketch-reading-card") || !app.Exists("id:sketch-reading-go-ahead") || !app.Exists("id:sketch-reading-correct") { + t.Fatal("sketch reading card controls missing") + } + + // Clicking reading item #2 (Correct a mark) reopens sketch mode with mark 2 selected and keeps hold active. + app.Press("id:sketch-reading-item-2") + if !ed.SketchActive() { + t.Fatal("Correct a mark did not reopen sketch mode") + } + if ed.SelectedSketchMark() != 2 { + t.Fatalf("SelectedSketchMark = %d, want 2", ed.SelectedSketchMark()) + } + if !ed.SketchHoldActive() { + t.Fatal("Correct a mark must keep confirmation hold active") + } + + // Re-send, post reading, and press Go ahead. + app.Press("id:sketch-composer-send") + app.Post(func() { + _ = ed.PostSketchReading(editor.SketchReading{ + Items: []editor.SketchReadingItem{ + {Number: 1, Text: "Three spike tiles on the floor."}, + {Number: 2, Text: "Door stays locked until lever_01 is pulled."}, + {Number: 3, Text: "Moving platform."}, + }, + }) + }) + app.Settle() + app.Press("id:sketch-reading-go-ahead") + if ed.SketchHoldActive() || !ed.SketchApproved() { + t.Fatalf("after Go ahead: holdActive=%v approved=%v, want false/true", ed.SketchHoldActive(), ed.SketchApproved()) + } + + // Simulate agent applying edits and opening Sketch Review. + app.Post(func() { + id, err := ed.PlaceObject("Actors", sceneformat.ObjectDoc{ID: "lever_01", Name: "lever_01", X: 295, Y: 280}) + if err != nil { + t.Errorf("PlaceObject: %v", err) + return + } + ed.RecordSketchReviewEdits("Agent: add lever_01", []string{id}, nil, nil) + }) + app.Settle() + if !app.Exists("id:sketch-review-card") || !app.Exists("id:sketch-review-overlay-toggle") { + t.Fatal("sketch review card or Sketch overlay toggle missing") + } + if !ed.SketchReviewOverlayVisible() { + t.Fatal("Sketch overlay should default to ON in review") + } + app.Press("id:sketch-review-overlay-toggle") + if ed.SketchReviewOverlayVisible() { + t.Fatal("clicking Sketch overlay toggle did not turn overlay OFF") + } + app.Press("id:sketch-review-overlay-toggle") + if !ed.SketchReviewOverlayVisible() { + t.Fatal("clicking Sketch overlay toggle again did not turn overlay ON") + } + + // Revert restores scene AND keeps the 3 sketch marks! + app.Press("id:sketch-review-revert") + if ed.SketchReviewOpen() { + t.Fatal("Revert did not close sketch review") + } + if obj, _, _ := ed.FindObject("lever_01"); obj != nil { + t.Fatal("Revert did not remove lever_01 added during review") + } + if ed.SketchMarkCount() != 3 { + t.Fatalf("Revert cleared sketch marks: got %d, want 3", ed.SketchMarkCount()) + } + + // Approve again, apply edit, and Keep -> keeps lever_01 AND clears sketch layer! + app.Post(func() { + _ = ed.ApproveSketchReading() + id, err := ed.PlaceObject("Actors", sceneformat.ObjectDoc{ID: "lever_01", Name: "lever_01", X: 295, Y: 280}) + if err != nil { + t.Errorf("PlaceObject 2: %v", err) + return + } + ed.RecordSketchReviewEdits("Agent: add lever_01", []string{id}, nil, nil) + }) + app.Settle() + app.Press("id:sketch-review-keep") + if ed.SketchReviewOpen() { + t.Fatal("Keep did not close sketch review") + } + if obj, _, _ := ed.FindObject("lever_01"); obj == nil { + t.Fatal("Keep did not retain lever_01") + } + if ed.SketchMarkCount() != 0 { + t.Fatalf("Keep did not clear sketch marks: got %d, want 0", ed.SketchMarkCount()) + } +} + +// #1025 Acceptance 4: Real nsgotest screenshots on macOS beside docs/design/editor/Sketch.dc.html. +func TestSketchUIAndScreenshots(t *testing.T) { + ed := newSketchTestEditor(t) + _ = ed.SetAppearance(editor.AppearanceDark) + ed.SetView2D(editor.View2D{X: 320, Y: 180, Zoom: 1.0}) + ed.StartSketch() + ed.AddSketchBox(171, 240, 109, 36, "3 spikes") + ed.AddSketchPen([]editor.SketchPoint{ + {X: 390, Y: 165}, + {X: 430, Y: 152}, + {X: 470, Y: 174}, + {X: 510, Y: 158}, + {X: 550, Y: 168}, + }, "platform, back and forth") + ed.AddSketchArrow(450, 108, 522, 245, "locked until the lever") + ed.SelectSketchMark(0) + ed.SetSketchTool(editor.SketchToolArrow) + ed.SetSketchPromptDraft("Build what I sketched. Spikes should look like the reference image.") + ed.SetSketchPreviewOpen(true) + + macEnv := nsgotest.Environment(core.Environment{OS: core.OSMacOS, Idiom: core.IdiomDesktop, Dark: true, Locale: "en-US"}) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), macEnv) + + app.Screenshot("sketch-active") + + // State 2: Sent sketch + agent reading card with Go ahead / Correct a mark. + app.Post(func() { + _, _ = ed.SendSketch("Build what I sketched. Spikes should look like the reference image.") + _ = ed.PostSketchReading(editor.SketchReading{ + Summary: "I read your sketch as:", + Items: []editor.SketchReadingItem{ + {Number: 1, Mark: "Box · “3 spikes”", Text: "Three spike tiles on the floor from x 171 to 280, using prefabs/spikes.prefab.yaml, 1 damage each."}, + {Number: 2, Mark: "Line · “platform, back and forth”", Text: "A new moving_platform, 64 px wide, going back and forth between x 390 and 550 at 40 px/s."}, + {Number: 3, Mark: "Arrow at Door · “locked until the lever”", Text: "Door stays locked until lever_01 is pulled once."}, + }, + Assumptions: []string{ + "There is no lever in level_01 yet. I will add lever_01 left of the plank at x 295 unless you point somewhere else.", + }, + }) + }) + app.Settle() + + app.Screenshot("sketch-reading") + + // State 3: Review with Sketch overlay toggle + Keep / Revert. + app.Post(func() { + _ = ed.ApproveSketchReading() + s1, _ := ed.PlaceObject("Actors", sceneformat.ObjectDoc{ID: "spikes_01", Name: "spikes_01", X: 225, Y: 258}) + p1, _ := ed.PlaceObject("Actors", sceneformat.ObjectDoc{ID: "moving_platform", Name: "moving_platform", X: 465, Y: 165}) + l1, _ := ed.PlaceObject("Actors", sceneformat.ObjectDoc{ID: "lever_01", Name: "lever_01", X: 295, Y: 280}) + _ = ed.SetProperty("door", "locked_until", "lever_01") + ed.RecordSketchReviewEdits("Agent: build sketch", []string{s1, p1, l1}, []string{"door"}, nil) + }) + app.Settle() + + app.Screenshot("sketch-review") +} diff --git a/packages/game/editor/sketch_ui.go b/packages/game/editor/sketch_ui.go new file mode 100644 index 000000000..2f27e17b3 --- /dev/null +++ b/packages/game/editor/sketch_ui.go @@ -0,0 +1,1394 @@ +package editor + +import ( + "fmt" + "strconv" + "strings" + + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/icons/lucide" + "github.com/nsgo-dev/nsgo/ui" +) + +// viewportSketchOverlayView renders the floating top-center Sketch toolbar, tool hint, and inline +// selected-mark label editor over the 2D viewport while Sketch mode is active, using exclusively Spec tokens. +func viewportSketchOverlayView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { + active := core.NewMemo(cx, func() bool { + _ = rev.Get() + return ed.SketchActive() + }) + return core.Show{ + When: active.Get, + Then: func(cx *core.Scope) core.Node { + p := ed.SpecPalette(cx) + divider := func() core.Node { + return core.View{ + Style: core.Style{ + Width: core.Pt(1), + Height: core.Pt(16), + Background: p.LineRaised, + Margin: core.Symmetric(0, 4), + }, + } + } + + toolBtn := func(testID string, tool SketchTool, label string, key string, icon func() *core.SVG, textFallback string) core.Node { + t := tool + btn := ui.Button{ + TestID: testID, + Label: fmt.Sprintf("%s · %s", label, key), + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Color: func() core.Color { + _ = rev.Get() + if ed.SketchTool() == t { + return p.LineRaised + } + return core.Transparent + }, + Tint: func() core.Color { + _ = rev.Get() + if ed.SketchTool() == t { + return p.TextPrimary + } + return p.TextMuted + }, + TextStyle: core.Style{ + FontSize: 12, + FontWeight: 600, + Color: p.TextSecondary, + }, + Style: core.Style{ + Width: core.Pt(32), + Height: core.Pt(28), + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.SetSketchTool(t) + }, + } + if icon != nil { + btn.Icon = icon + btn.IconSize = 15 + } else { + btn.Text = textFallback + } + return btn + } + + selectedMarkKey := core.NewMemo(cx, func() int { + _ = rev.Get() + return ed.SelectedSketchMark() + }) + + return core.View{ + TestID: "viewport-sketch-overlay-wrap", + PointerEvents: core.PointerEventsBoxNone, + Style: core.Style{ + Position: core.Absolute, + Left: core.Pt(0), + Right: core.Pt(0), + Top: core.Pt(14), + AlignItems: core.AlignCenter, + Gap: 8, + }, + Children: []core.Node{ + // Main floating sketch toolbar matching Sketch.dc.html. + core.View{ + TestID: "viewport-sketch-toolbar", + Role: core.RoleToolbar, + Label: ed.T("sketch.toolbarLabel"), + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 2, + Padding: core.All(4), + CornerRadius: 12, + Background: ui.Alpha(p.Raised, 0.96), + BorderWidth: 1, + BorderColor: p.LineRaised, + }, + Children: []core.Node{ + toolBtn("sketch-tool-pen", SketchToolPen, ed.T("sketch.tool.pen"), "P", lucide.Pencil, ""), + toolBtn("sketch-tool-arrow", SketchToolArrow, ed.T("sketch.tool.arrow"), "A", lucide.ArrowUpRight, ""), + toolBtn("sketch-tool-box", SketchToolBox, ed.T("sketch.tool.box"), "B", lucide.Square, ""), + toolBtn("sketch-tool-text", SketchToolText, ed.T("sketch.tool.text"), "T", nil, "T"), + divider(), + ui.Button{ + TestID: "sketch-undo-mark", + Icon: lucide.RotateCcw, + IconSize: 15, + Label: ed.T("sketch.undoMark"), + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Side: 28, + Disabled: func() bool { + _ = rev.Get() + return !ed.CanUndoSketchMark() + }, + Tint: func() core.Color { return p.TextMuted }, + Style: core.Style{ + Width: core.Pt(32), + Height: core.Pt(28), + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.UndoLastSketchMark() + }, + }, + ui.Button{ + TestID: "sketch-toggle-marks", + Icon: lucide.Eye, + IconSize: 15, + LabelFunc: func() string { + _ = rev.Get() + if ed.SketchMarksHidden() { + return ed.T("sketch.showMarks") + } + return ed.T("sketch.hideMarks") + }, + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Color: func() core.Color { + _ = rev.Get() + if ed.SketchMarksHidden() { + return p.LineRaised + } + return core.Transparent + }, + Tint: func() core.Color { + _ = rev.Get() + if ed.SketchMarksHidden() { + return p.TextPrimary + } + return p.TextMuted + }, + Style: core.Style{ + Width: core.Pt(32), + Height: core.Pt(28), + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.ToggleSketchMarksHidden() + }, + }, + core.Text{ + TestID: "sketch-bar-count", + ContentFunc: func() string { + _ = rev.Get() + return ed.SketchBarCountLabel() + }, + Style: core.Style{ + FontSize: 11.5, + Color: p.TextFaint, + Padding: core.Symmetric(0, 6), + }, + }, + ui.Button{ + TestID: "sketch-clear", + Text: ed.T("sketch.clear"), + Label: ed.T("sketch.clear"), + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Disabled: func() bool { + _ = rev.Get() + return ed.SketchMarkCount() == 0 + }, + TextStyle: core.Style{ + FontSize: 12, + FontWeight: 500, + Color: p.TextMuted, + }, + Style: core.Style{ + Height: core.Pt(28), + Padding: core.Symmetric(0, 8), + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.ClearSketch() + }, + }, + divider(), + ui.Button{ + TestID: "sketch-done", + Text: ed.T("sketch.done"), + Label: ed.T("sketch.done"), + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Color: func() core.Color { return p.TextPrimary }, + TextStyle: core.Style{ + FontSize: 12, + FontWeight: 600, + Color: p.OnTextPrimary, + }, + Style: core.Style{ + Height: core.Pt(28), + Padding: core.Symmetric(0, 12), + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.FinishSketch() + }, + }, + }, + }, + + // Active tool hint pill. + core.View{ + TestID: "sketch-tool-hint-pill", + PointerEvents: core.PointerEventsNone, + Style: core.Style{ + Height: core.Pt(22), + Padding: core.Symmetric(0, 8), + CornerRadius: 6, + Background: ui.Alpha(p.PillBg, 0.92), + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + }, + Children: []core.Node{ + core.Text{ + TestID: "sketch-tool-hint", + ContentFunc: func() string { + _ = rev.Get() + return ed.SketchTool().Hint() + }, + Style: core.Style{ + FontSize: 11.5, + Color: p.TextMuted, + }, + }, + }, + }, + + // Selected mark inline label editor (shown whenever a mark is selected, including after Correct a mark). + core.Show{ + When: func() bool { + return selectedMarkKey.Get() > 0 + }, + Then: func(cx *core.Scope) core.Node { + return core.Dynamic(func(cx *core.Scope) core.Node { + num := selectedMarkKey.Get() + m, ok := ed.SketchMarkByNumber(num) + if !ok { + return core.View{} + } + pal := ed.SpecPalette(cx) + return core.View{ + TestID: "sketch-mark-label-bar", + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + Padding: core.Edges{Top: 4, Bottom: 4, Left: 8, Right: 6}, + CornerRadius: 10, + Background: ui.Alpha(pal.Raised, 0.96), + BorderWidth: 1, + BorderColor: pal.Accent.Edge, + }, + Children: []core.Node{ + core.View{ + TestID: "sketch-selected-mark-badge", + Style: core.Style{ + Width: core.Pt(18), + Height: core.Pt(18), + CornerRadius: 9, + Background: pal.Accent.Fg, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + }, + Children: []core.Node{ + core.Text{ + Content: strconv.Itoa(m.Number), + Style: core.Style{ + FontSize: 11, + FontWeight: 600, + Color: pal.Accent.OnFill, + }, + }, + }, + }, + ui.Input{ + TestID: "sketch-mark-label-input", + Label: fmt.Sprintf("Label for mark %d", m.Number), + Placeholder: "Add label (e.g. 3 spikes)...", + Value: func() string { + _ = rev.Get() + if cur, ok := ed.SketchMarkByNumber(num); ok { + return cur.Label + } + return "" + }, + OnChange: func(v string) { + ed.SetSketchMarkLabel(num, v) + }, + Style: core.Style{ + Width: core.Pt(200), + }, + }, + ui.Button{ + TestID: "sketch-mark-delete", + Icon: lucide.Trash, + IconSize: 13, + Label: fmt.Sprintf("Delete mark %d", m.Number), + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Side: 26, + Tint: func() core.Color { return pal.TextMuted }, + Style: core.Style{ + CornerRadius: 6, + FocusVisible: pal.FocusRing(2), + }, + OnPress: func() { + ed.DeleteSketchMark(num) + }, + }, + }, + } + }) + }, + }, + }, + } + }, + } +} + +// sceneTreeSketchSectionView renders the compact "SKETCH LAYER · N marks · not saved" row at the bottom +// of the Scene Tree panel when sketch mode is active or marks exist, matching docs/design/editor/Sketch.dc.html. +func sceneTreeSketchSectionView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { + shown := core.NewMemo(cx, func() bool { + _ = rev.Get() + return !ed.Playing() && (ed.SketchActive() || ed.SketchMarkCount() > 0) + }) + return core.Show{ + When: shown.Get, + Then: func(cx *core.Scope) core.Node { + p := ed.SpecPalette(cx) + return core.View{ + TestID: "scene-tree-sketch-section", + Style: core.Style{ + Padding: core.Edges{Top: 8, Bottom: 4, Left: 4, Right: 4}, + Borders: core.Edges{Top: 1}, + BorderColor: p.Line, + Gap: 4, + }, + Children: []core.Node{ + core.Text{ + Content: "SKETCH LAYER", + Style: core.Style{ + FontSize: 11, + FontWeight: 600, + LetterSpacing: 0.6, + Color: p.TextFaint, + Padding: core.Symmetric(0, 4), + }, + }, + core.View{ + TestID: "scene-tree-sketch-layer", + Role: core.RoleButton, + Label: "Sketch layer", + OnPress: func(core.PressEvent) { + ed.StartSketch() + }, + Style: core.Style{ + Height: core.Pt(28), + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + Padding: core.Symmetric(0, 6), + CornerRadius: 6, + FocusVisible: p.FocusRing(-2), + }, + Children: []core.Node{ + core.Text{ + TestID: "scene-tree-sketch-count", + ContentFunc: func() string { + _ = rev.Get() + n := ed.SketchMarkCount() + if n == 1 { + return "1 mark" + } + return fmt.Sprintf("%d marks", n) + }, + Style: core.Style{ + FlexGrow: 1, + FontSize: 12, + Color: p.TextMuted, + }, + }, + core.Text{ + Content: "not saved", + Style: core.Style{ + FontSize: 11, + Color: p.TextFaint, + }, + }, + }, + }, + }, + } + }, + } +} + +// SketchPanelView renders the right-side Agent / Sketch panel matching docs/design/editor/Sketch.dc.html +// using exclusively Spec tokens: Agent header, post-sketch Review card (with Sketch overlay toggle, Keep, Revert), +// Agent Reading card ("I read your sketch as:" with numbered items, assumptions warning box, Go ahead, Correct a mark), +// "Sent with this request" scene-coordinate preview, and composer with the "Sketch · N marks" chip. +func SketchPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { + type panelKey struct { + dark bool + markCount int + selectedMark int + hold SketchHoldState + hasReading bool + readingItems int + readingAssump int + reviewOpen bool + reviewChanges int + reviewOverlay bool + previewOpen bool + attached bool + marksDigest string + } + stateKey := core.NewMemo(cx, func() panelKey { + _ = rev.Get() + var b strings.Builder + for _, m := range ed.SketchMarks() { + fmt.Fprintf(&b, "%d:%s:%s:%s;", m.Number, m.Kind, m.GeometrySummary(), m.Label) + } + var rItems, rAssump int + if rd := ed.SketchReading(); rd != nil { + rItems = len(rd.Items) + rAssump = len(rd.Assumptions) + b.WriteString("|R:") + b.WriteString(rd.Summary) + for _, it := range rd.Items { + fmt.Fprintf(&b, "%d:%s:%s;", it.Number, it.Mark, it.Text) + } + for _, a := range rd.Assumptions { + b.WriteString(a) + b.WriteByte(';') + } + } + return panelKey{ + dark: cx.Dark(), + markCount: ed.SketchMarkCount(), + selectedMark: ed.SelectedSketchMark(), + hold: ed.SketchHoldState(), + hasReading: ed.SketchReading() != nil, + readingItems: rItems, + readingAssump: rAssump, + reviewOpen: ed.SketchReviewOpen(), + reviewChanges: len(ed.SketchReviewChanges()), + reviewOverlay: ed.SketchReviewOverlayVisible(), + previewOpen: ed.SketchPreviewOpen(), + attached: ed.SketchAttached(), + marksDigest: b.String(), + } + }) + + p := ed.SpecPalette(cx) + return core.View{ + TestID: "sketch-agent-panel", + Role: core.RoleRegion, + Label: "Agent Sketch", + Style: core.Style{ + Width: core.Pt(360), + FlexShrink: 0, + Background: p.Panel, + Borders: core.Edges{Left: 1}, + BorderColor: p.Line, + Overflow: core.Hidden, + }, + Children: []core.Node{ + // Panel Header ("Agent" + MCP dot + Inspector toggle). + core.View{ + Style: core.Style{ + Height: core.Pt(44), + FlexShrink: 0, + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + Padding: core.Edges{Left: 16, Right: 8}, + Borders: core.Edges{Bottom: 1}, + BorderColor: p.Line, + }, + Children: []core.Node{ + core.Text{ + Content: "Agent", + Style: core.Style{ + FontSize: 13, + FontWeight: 600, + Color: p.TextPrimary, + FlexGrow: 1, + }, + }, + core.View{ + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 6, + Padding: core.Symmetric(0, 6), + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(6), + Height: core.Pt(6), + CornerRadius: 3, + Background: p.Added.Fg, + }, + }, + core.Text{ + Content: "MCP", + Style: core.Style{ + FontSize: 11.5, + Color: p.TextFaint, + }, + }, + }, + }, + ui.Button{ + TestID: "sketch-panel-close", + Icon: lucide.X, + Label: "Show Inspector", + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Side: 28, + Tint: func() core.Color { return p.TextMuted }, + Style: core.Style{ + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.SetSketchPanelOpen(false) + }, + }, + }, + }, + + // Scrollable body: Review card / Reading card / Marks list. + ui.ScrollView{ + Style: core.Style{ + FlexGrow: 1, + FlexBasis: core.Pt(0), + }, + Children: []core.Node{ + core.Dynamic(func(cx *core.Scope) core.Node { + _ = stateKey.Get() + pal := ed.SpecPalette(cx) + var items []core.Node + + // 1. Post-sketch Review card (Sketch overlay toggle + Keep / Revert). + if ed.SketchReviewOpen() { + items = append(items, sketchReviewCardView(ed, pal)) + } + + // 2. Agent Reading card ("I read your sketch as:" + assumptions + Go ahead / Correct a mark). + if rd := ed.SketchReading(); rd != nil { + items = append(items, sketchReadingCardView(ed, pal, rd)) + } else if ed.SketchHoldState() == SketchHoldPending { + items = append(items, core.View{ + TestID: "sketch-waiting-reading", + Style: core.Style{ + CornerRadius: 12, + Background: pal.Warning.Fill, + BorderWidth: 1, + BorderColor: pal.Warning.Edge, + Padding: core.Symmetric(10, 12), + Gap: 4, + }, + Children: []core.Node{ + core.Text{ + Content: "Waiting for the agent to read your sketch", + Style: core.Style{FontSize: 12, FontWeight: 600, Color: pal.Warning.Fg}, + }, + core.Text{ + Content: "Scene edits are held until the agent restates each mark and you choose Go ahead.", + Style: core.Style{FontSize: 11.5, Color: pal.TextSecondary}, + }, + }, + }) + } + + // 3. Active marks list when not in review and no reading card. + marks := ed.SketchMarks() + if len(marks) > 0 && !ed.SketchReviewOpen() && ed.SketchReading() == nil { + sel := ed.SelectedSketchMark() + rows := make([]core.Node, 0, len(marks)) + for _, mk := range marks { + m := mk + isSel := m.Number == sel + rowBg := pal.Raised + rowBorder := pal.LineRaised + if isSel { + rowBorder = pal.Accent.Edge + } + rows = append(rows, core.View{ + TestID: fmt.Sprintf("sketch-panel-mark-%d", m.Number), + Role: core.RoleButton, + Label: fmt.Sprintf("Mark %d %s", m.Number, m.Kind.String()), + OnPress: func(core.PressEvent) { + ed.SelectSketchMark(m.Number) + if !ed.SketchActive() { + ed.StartSketch() + } + }, + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + Padding: core.Symmetric(8, 10), + CornerRadius: 8, + Background: rowBg, + BorderWidth: 1, + BorderColor: rowBorder, + FocusVisible: pal.FocusRing(-2), + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(18), + Height: core.Pt(18), + FlexShrink: 0, + CornerRadius: 9, + Background: pal.TextPrimary, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + }, + Children: []core.Node{ + core.Text{ + Content: strconv.Itoa(m.Number), + Style: core.Style{FontSize: 11, FontWeight: 600, Color: pal.OnTextPrimary}, + }, + }, + }, + core.View{ + Style: core.Style{FlexGrow: 1, FlexBasis: core.Pt(0), Gap: 2}, + Children: []core.Node{ + core.Text{ + Content: m.GeometrySummary(), + Style: core.Style{ + FontFamily: core.FontMonospace, + FontSize: 11.5, + Color: pal.TextMuted, + }, + }, + core.Show{ + When: func() bool { return m.Label != "" }, + Then: func(cx *core.Scope) core.Node { + return core.Text{ + Content: fmt.Sprintf("“%s”", m.Label), + Style: core.Style{FontSize: 11.5, Color: pal.TextSecondary}, + } + }, + }, + }, + }, + }, + }) + } + items = append(items, core.View{ + TestID: "sketch-panel-marks-list", + Style: core.Style{Gap: 6}, + Children: rows, + }) + } + + // 4. "Sent with this request" scene-coordinates preview card. + if ed.SketchPreviewOpen() { + items = append(items, sketchPreviewCardView(ed, pal)) + } + + if len(items) == 0 { + items = append(items, core.Text{ + TestID: "sketch-panel-empty", + Content: "Draw on the viewport with Pen, Arrow, Box or Text. Marks stay in scene coordinates and are never written to the scene file.", + Style: core.Style{ + FontSize: 12, + LineHeight: 18, + Color: pal.TextFaint, + }, + }) + } + + return core.View{ + Style: core.Style{ + Padding: core.All(12), + Gap: 12, + }, + Children: items, + } + }), + }, + }, + + // Composer footer with "Sketch · N marks" chip and Send button. + sketchComposerView(cx, ed, rev), + }, + } +} + +func sketchReadingCardView(ed *Editor, p SpecPalette, rd *SketchReading) core.Node { + var children []core.Node + + if req, ok := ed.LastSketchRequest(); ok && req.Prompt != "" { + children = append(children, core.View{ + TestID: "sketch-reading-prompt", + Style: core.Style{ + Padding: core.Symmetric(8, 10), + CornerRadius: 10, + Background: p.Inset, + BorderWidth: 1, + BorderColor: p.LineRaised, + Gap: 4, + }, + Children: []core.Node{ + core.Text{ + Content: req.ChipLabel, + Style: core.Style{FontSize: 11, FontWeight: 600, Color: p.TextFaint}, + }, + core.Text{ + Content: req.Prompt, + Style: core.Style{FontSize: 12, Color: p.TextPrimary}, + }, + }, + }) + } + + children = append(children, core.Text{ + TestID: "sketch-reading-heading", + Content: rd.Summary, + Style: core.Style{FontSize: 12.5, FontWeight: 500, Color: p.TextSecondary}, + }) + + for _, item := range rd.Items { + it := item + children = append(children, core.View{ + TestID: fmt.Sprintf("sketch-reading-item-%d", it.Number), + Role: core.RoleButton, + Label: fmt.Sprintf("Correct mark %d: %s", it.Number, it.Mark), + OnPress: func(core.PressEvent) { + ed.report(ed.CorrectSketchMark(it.Number)) + }, + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignStart, + Gap: 8, + Padding: core.Symmetric(4, 4), + CornerRadius: 8, + FocusVisible: p.FocusRing(-2), + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(18), + Height: core.Pt(18), + FlexShrink: 0, + CornerRadius: 9, + Background: p.TextPrimary, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + }, + Children: []core.Node{ + core.Text{ + Content: strconv.Itoa(it.Number), + Style: core.Style{FontSize: 11, FontWeight: 600, Color: p.OnTextPrimary}, + }, + }, + }, + core.View{ + Style: core.Style{FlexGrow: 1, FlexBasis: core.Pt(0), Gap: 2}, + Children: []core.Node{ + core.Text{ + Content: it.Mark, + Style: core.Style{FontSize: 11.5, Color: p.TextFaint}, + }, + core.Text{ + Content: it.Text, + Style: core.Style{FontSize: 12.5, Color: p.TextSecondary}, + }, + }, + }, + }, + }) + } + + if len(rd.Assumptions) > 0 { + assumpNodes := make([]core.Node, 0, len(rd.Assumptions)) + for i, a := range rd.Assumptions { + assumpNodes = append(assumpNodes, core.Text{ + TestID: fmt.Sprintf("sketch-reading-assumption-%d", i), + Content: a, + Style: core.Style{FontSize: 12, Color: p.Warning.Fg}, + }) + } + children = append(children, core.View{ + TestID: "sketch-reading-assumptions", + Style: core.Style{ + CornerRadius: 12, + Background: p.Warning.Fill, + BorderWidth: 1, + BorderColor: p.Warning.Edge, + Padding: core.Symmetric(8, 12), + Gap: 4, + }, + Children: assumpNodes, + }) + } + + if ed.SketchHoldActive() { + correctTarget := ed.SelectedSketchMark() + if correctTarget <= 0 && len(rd.Items) > 0 { + correctTarget = rd.Items[0].Number + } + if correctTarget <= 0 { + correctTarget = 1 + } + children = append(children, core.View{ + Style: core.Style{ + Direction: core.Row, + Gap: 8, + }, + Children: []core.Node{ + ui.Button{ + TestID: "sketch-reading-go-ahead", + Text: "Go ahead", + Label: "Go ahead", + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Color: func() core.Color { return p.TextPrimary }, + TextStyle: core.Style{ + FontSize: 12, + FontWeight: 600, + Color: p.OnTextPrimary, + }, + Style: core.Style{ + Height: core.Pt(30), + Padding: core.Symmetric(0, 12), + CornerRadius: 8, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.report(ed.ApproveSketchReading()) + }, + }, + ui.Button{ + TestID: "sketch-reading-correct", + Text: "Correct a mark", + Label: "Correct a mark", + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Color: func() core.Color { return p.LineRaised }, + TextStyle: core.Style{ + FontSize: 12, + FontWeight: 500, + Color: p.TextPrimary, + }, + Style: core.Style{ + Height: core.Pt(30), + Padding: core.Symmetric(0, 12), + CornerRadius: 8, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.report(ed.CorrectSketchMark(correctTarget)) + }, + }, + }, + }) + } else if ed.SketchApproved() { + children = append(children, core.Text{ + TestID: "sketch-reading-approved-note", + Content: "Approved · agent may edit the scene.", + Style: core.Style{FontSize: 11.5, Color: p.Added.Fg}, + }) + } + + return core.View{ + TestID: "sketch-reading-card", + Style: core.Style{ + CornerRadius: 12, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + Padding: core.All(12), + Gap: 10, + }, + Children: children, + } +} + +func sketchReviewCardView(ed *Editor, p SpecPalette) core.Node { + changes := ed.SketchReviewChanges() + countLabel := fmt.Sprintf("%d changes", len(changes)) + if len(changes) == 1 { + countLabel = "1 change" + } + overlayOn := ed.SketchReviewOverlayVisible() + overlayBg := core.Transparent + overlayFg := p.TextMuted + if overlayOn { + overlayBg = p.LineRaised + overlayFg = p.TextPrimary + } + + var rows []core.Node + for i, ch := range changes { + swatchCol := p.Changed.Fg + prefix := "changed" + if ch.Kind == SketchChangeAdded { + swatchCol = p.Added.Fg + prefix = "added" + } else if ch.Kind == SketchChangeRemoved { + swatchCol = p.Removed.Fg + prefix = "removed" + } + rows = append(rows, core.View{ + TestID: fmt.Sprintf("sketch-review-change-%d", i), + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(10), + Height: core.Pt(10), + FlexShrink: 0, + CornerRadius: 2, + BorderWidth: 1.5, + BorderColor: swatchCol, + }, + }, + core.Text{ + Content: fmt.Sprintf("%s · %s", prefix, ch.ID), + Style: core.Style{FontSize: 11.5, Color: p.TextMuted}, + }, + }, + }) + } + if ed.SketchMarkCount() > 0 { + rows = append(rows, core.View{ + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: 8}, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(10), + Height: core.Pt(2), + FlexShrink: 0, + Background: ui.Alpha(p.TextPrimary, 0.6), + }, + }, + core.Text{ + Content: "your sketch", + Style: core.Style{FontSize: 11.5, Color: p.TextMuted}, + }, + }, + }) + } + + return core.View{ + TestID: "sketch-review-card", + Style: core.Style{ + CornerRadius: 12, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + Overflow: core.Hidden, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Height: core.Pt(40), + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + Padding: core.Edges{Left: 12, Right: 8}, + Borders: core.Edges{Bottom: 1}, + BorderColor: p.Line, + }, + Children: []core.Node{ + core.Text{ + TestID: "sketch-review-count", + Content: countLabel, + Style: core.Style{FontSize: 12.5, FontWeight: 600, Color: p.TextPrimary, FlexGrow: 1}, + }, + ui.Button{ + TestID: "sketch-review-overlay-toggle", + Icon: lucide.Pencil, + IconSize: 13, + Text: "Sketch overlay", + Label: "Toggle sketch overlay", + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Color: func() core.Color { return overlayBg }, + Tint: func() core.Color { return overlayFg }, + TextStyle: core.Style{ + FontSize: 11.5, + FontWeight: 500, + Color: overlayFg, + }, + Style: core.Style{ + Height: core.Pt(28), + Padding: core.Symmetric(0, 8), + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.ToggleSketchReviewOverlay() + }, + }, + }, + }, + core.View{ + Style: core.Style{Padding: core.All(12), Gap: 6}, + Children: rows, + }, + core.View{ + Style: core.Style{ + Direction: core.Row, + Gap: 8, + Padding: core.All(12), + Borders: core.Edges{Top: 1}, + BorderColor: p.Line, + }, + Children: []core.Node{ + ui.Button{ + TestID: "sketch-review-keep", + Text: "Keep", + Label: "Keep changes and clear sketch", + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Color: func() core.Color { return p.Accent.Fg }, + TextStyle: core.Style{ + FontSize: 12, + FontWeight: 600, + Color: p.Accent.OnFill, + }, + Style: core.Style{ + FlexGrow: 1, + Height: core.Pt(30), + CornerRadius: 8, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.report(ed.KeepSketchReview()) + }, + }, + ui.Button{ + TestID: "sketch-review-revert", + Text: "Revert", + Label: "Revert changes and keep sketch", + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Color: func() core.Color { return p.LineRaised }, + TextStyle: core.Style{ + FontSize: 12, + FontWeight: 500, + Color: p.TextSecondary, + }, + Style: core.Style{ + Height: core.Pt(30), + Padding: core.Symmetric(0, 12), + CornerRadius: 8, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.report(ed.RevertSketchReview()) + }, + }, + }, + }, + }, + } +} + +func sketchPreviewCardView(ed *Editor, p SpecPalette) core.Node { + marks := ed.SketchMarks() + rows := make([]core.Node, 0, len(marks)) + for _, m := range marks { + var labelNode core.Node + if m.Label != "" { + labelNode = core.Text{ + Content: fmt.Sprintf("“%s”", m.Label), + Style: core.Style{ + FontFamily: core.FontMonospace, + FontSize: 11.5, + Color: p.TextFaint, + Padding: core.Edges{Left: 20}, + }, + } + } + children := []core.Node{ + core.View{ + Style: core.Style{Direction: core.Row, Gap: 8}, + Children: []core.Node{ + core.Text{ + Content: strconv.Itoa(m.Number), + Style: core.Style{ + Width: core.Pt(12), + FontFamily: core.FontMonospace, + FontSize: 11.5, + Color: p.TextPrimary, + }, + }, + core.Text{ + Content: m.GeometrySummary(), + Style: core.Style{ + FontFamily: core.FontMonospace, + FontSize: 11.5, + Color: p.TextMuted, + }, + }, + }, + }, + } + if labelNode != nil { + children = append(children, labelNode) + } + rows = append(rows, core.View{ + TestID: fmt.Sprintf("sketch-preview-mark-%d", m.Number), + Style: core.Style{Gap: 2}, + Children: children, + }) + } + return core.View{ + TestID: "sketch-sent-preview", + Style: core.Style{ + CornerRadius: 12, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + Padding: core.All(12), + Gap: 8, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, JustifyContent: core.JustifySpaceBetween}, + Children: []core.Node{ + core.Text{ + Content: "Sent with this request", + Style: core.Style{FontSize: 13, FontWeight: 600, Color: p.TextPrimary}, + }, + core.Text{ + Content: "scene coordinates", + Style: core.Style{FontSize: 11.5, Color: p.TextFaint}, + }, + }, + }, + core.View{ + Style: core.Style{Gap: 6}, + Children: rows, + }, + }, + } +} + +func sketchComposerView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { + p := ed.SpecPalette(cx) + submit := func() { + text := strings.TrimSpace(ed.SketchPromptDraft()) + if ed.SketchHoldState() == SketchHoldReading && text != "" { + ed.report(ed.ReplyToSketchReading(text)) + return + } + if ed.SketchMarkCount() > 0 { + if _, err := ed.SendSketch(text); err != nil { + ed.report(err) + } + } + } + + return core.View{ + TestID: "sketch-composer", + Style: core.Style{ + FlexShrink: 0, + Padding: core.All(12), + Borders: core.Edges{Top: 1}, + BorderColor: p.Line, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + CornerRadius: 12, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + Padding: core.Symmetric(8, 10), + Gap: 8, + }, + Children: []core.Node{ + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.SketchAttached() + }, + Then: func(cx *core.Scope) core.Node { + pal := ed.SpecPalette(cx) + return core.View{ + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: 4}, + Children: []core.Node{ + core.View{ + StyleFunc: func() core.Style { + _ = rev.Get() + border := pal.LineRaised + if ed.SketchPreviewOpen() { + border = pal.Accent.Edge + } + return core.Style{ + Height: core.Pt(28), + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 4, + Padding: core.Edges{Left: 8, Right: 2}, + CornerRadius: 6, + Background: pal.LineRaised, + BorderWidth: 1, + BorderColor: border, + } + }, + Children: []core.Node{ + ui.Button{ + TestID: "sketch-context-chip", + Icon: lucide.Pencil, + Variant: ui.ButtonGhost, + Size: ui.SizeSmall, + TextFunc: func() string { + _ = rev.Get() + return ed.SketchChipLabel() + }, + LabelFunc: func() string { + _ = rev.Get() + return ed.SketchChipLabel() + ". Show what is sent" + }, + IconSize: 12, + Tint: func() core.Color { return pal.TextPrimary }, + TextStyle: core.Style{ + FontSize: 11.5, + FontWeight: 500, + Color: pal.TextPrimary, + }, + Style: core.Style{ + Height: core.Pt(24), + Padding: core.Symmetric(0, 4), + CornerRadius: 4, + FocusVisible: pal.FocusRing(2), + }, + OnPress: func() { + ed.ToggleSketchPreview() + }, + }, + ui.Button{ + TestID: "sketch-chip-remove", + Icon: lucide.X, + IconSize: 11, + Label: "Remove the sketch from the request", + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Side: 20, + Tint: func() core.Color { return pal.TextMuted }, + Style: core.Style{ + CornerRadius: 4, + FocusVisible: pal.FocusRing(2), + }, + OnPress: func() { + ed.SetSketchAttached(false) + }, + }, + }, + }, + }, + } + }, + }, + ui.Input{ + TestID: "sketch-composer-input", + Label: "Ask the agent", + Placeholder: "Build what I sketched...", + Value: func() string { + _ = rev.Get() + return ed.SketchPromptDraft() + }, + OnChange: func(v string) { + ed.SetSketchPromptDraft(v) + }, + OnSubmit: func(string) { + submit() + }, + }, + core.View{ + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 4, + }, + Children: []core.Node{ + ui.Button{ + TestID: "sketch-composer-sketch-btn", + Icon: lucide.Pencil, + IconSize: 14, + Label: "Sketch on the viewport · D", + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Side: 28, + Color: func() core.Color { + _ = rev.Get() + if ed.SketchActive() { + return p.LineRaised + } + return core.Transparent + }, + Tint: func() core.Color { + _ = rev.Get() + if ed.SketchActive() { + return p.TextPrimary + } + return p.TextMuted + }, + Style: core.Style{ + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.ToggleSketch() + }, + }, + core.View{Style: core.Style{FlexGrow: 1}}, + ui.Button{ + TestID: "sketch-composer-send", + Icon: lucide.ArrowUp, + IconSize: 14, + Label: "Send sketch to agent", + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Side: 30, + Disabled: func() bool { + _ = rev.Get() + if ed.SketchHoldState() == SketchHoldReading { + return strings.TrimSpace(ed.SketchPromptDraft()) == "" + } + return ed.SketchMarkCount() == 0 + }, + Color: func() core.Color { return p.TextPrimary }, + Tint: func() core.Color { return p.OnTextPrimary }, + Style: core.Style{ + CornerRadius: 8, + FocusVisible: p.FocusRing(2), + }, + OnPress: submit, + }, + }, + }, + }, + }, + }, + } +} diff --git a/packages/game/editor/state.go b/packages/game/editor/state.go index 7e2fcf22f..2d1f1b833 100644 --- a/packages/game/editor/state.go +++ b/packages/game/editor/state.go @@ -596,6 +596,10 @@ type Editor struct { OnFocusWindow func() // OnOpenAgentTask, when set, is called after OpenAgentTask opens a task's scene and switches to the Tasks or Agent panel. OnOpenAgentTask func(task AgentTask) + // OnSendSketch, when set, is called when the author sends a viewport sketch to the agent (SendSketch). + OnSendSketch func(SketchAgentRequest) + // OnReplySketchReading, when set, is called when the author answers an agent sketch reading card (Go ahead, Correct a mark, or a text reply). + OnReplySketchReading func(SketchReadingReply) playing bool playPaused bool @@ -808,6 +812,8 @@ type Editor struct { // tileReview holds the active region-based agent tile edit review for the open scene, or nil. tileReview *tileReviewState tileReviewSeq uint64 + // sketch holds the session-only viewport sketch layer, confirmation hold, reading card, and post-sketch review state. + sketch sketchState // paletteImgCache caches FileResolver-loaded tileset images across TilePalette() calls so 60 Hz rev bumps avoid disk reads. paletteImgCache paletteFileImageCache // inspectAssetFile prefers the selected asset's import settings in InspectorView over SelectedID after selecting an asset in FilesView. diff --git a/packages/game/editor/tabs.go b/packages/game/editor/tabs.go index 1d664c0c5..42d3b96d9 100644 --- a/packages/game/editor/tabs.go +++ b/packages/game/editor/tabs.go @@ -61,6 +61,7 @@ type sceneTab struct { agentTurn *agentTurnState agentWorkingIDs []string agentWorkingActivity string + sketch sketchState view2D View2D view2DFree bool camera3D OrbitCamera3D @@ -166,6 +167,7 @@ func (e *Editor) syncActiveTab() { t.agentTurn = e.agentLive.turn t.agentWorkingIDs = slices.Clone(e.agentLive.workingIDs) t.agentWorkingActivity = e.agentLive.workingActivity + t.sketch = cloneSketchState(e.sketch) t.view2D = e.view2D t.view2DFree = e.view2DFree t.camera3D = e.Camera3D @@ -237,6 +239,7 @@ func (e *Editor) loadActiveTab() { e.agentLive.stateDetail = "" } e.syncAgentPulseLoop() + e.sketch = cloneSketchState(t.sketch) e.view2D = t.view2D e.view2DFree = t.view2DFree e.Camera3D = t.camera3D @@ -287,6 +290,7 @@ func (e *Editor) cancelTransientInteraction() { e.CancelRoomDrag() e.CancelRigDrag() e.CancelHUDTouchDrag() + e.CancelSketchDrag() e.cancelBackgroundPreview() e.CancelGizmoDrag3D() e.CancelHandleDrag3D() diff --git a/packages/game/editor/tile_review.go b/packages/game/editor/tile_review.go index 8dadd547a..91b192173 100644 --- a/packages/game/editor/tile_review.go +++ b/packages/game/editor/tile_review.go @@ -2050,6 +2050,7 @@ func (e *Editor) KeepTileReview() (AgentTileEditResult, error) { historyOwned := rev.historyOwned historyStart := rev.historyStart e.tileReview = nil + e.clearSketchOnReviewKeep() if historyOwned && e.History != nil && historyStart >= 0 && historyStart <= e.History.cursor { // Collapse all intermediate agent review steps back to historyStart so Keep records exactly ONE undo step. @@ -2188,6 +2189,7 @@ func (e *Editor) RevertAllTileReview() error { historyOwned := rev.historyOwned historyStart := rev.historyStart e.tileReview = nil + e.keepSketchOnReviewRevert() if historyOwned && e.History != nil && historyStart >= 0 && historyStart <= e.History.cursor { var toBase []tileChange diff --git a/packages/game/editor/tile_review_ui.go b/packages/game/editor/tile_review_ui.go index 457b8372f..3b519ba6b 100644 --- a/packages/game/editor/tile_review_ui.go +++ b/packages/game/editor/tile_review_ui.go @@ -417,13 +417,63 @@ func tileReviewPanel(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core. }, Style: core.Style{FontSize: 12.5, FontWeight: 500, Color: specTextStrong}, }, - core.Text{ - TestID: "tile-review-file", - ContentFunc: func() string { - _ = rev.Get() - return sceneFileLabel() + core.View{ + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: 8}, + Children: []core.Node{ + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.SketchMarkCount() > 0 + }, + Then: func(cx *core.Scope) core.Node { + return core.View{ + TestID: "tile-review-sketch-overlay", + Role: core.RoleButton, + Label: "Toggle sketch overlay", + OnPress: func(core.PressEvent) { + ed.ToggleSketchReviewOverlay() + }, + StyleFunc: func() core.Style { + _ = rev.Get() + bg := core.Transparent + if ed.SketchReviewOverlayVisible() { + bg = specLineRaised + } + return core.Style{ + Height: core.Pt(24), + Padding: core.Symmetric(0, 8), + CornerRadius: 6, + Background: bg, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FocusVisible: specFocusRingStyle, + } + }, + Children: []core.Node{ + core.Text{ + Content: "Sketch overlay", + StyleFunc: func() core.Style { + _ = rev.Get() + col := specTextSecondary + if ed.SketchReviewOverlayVisible() { + col = specTextStrong + } + return core.Style{FontSize: 11, FontWeight: 500, Color: col} + }, + }, + }, + } + }, + }, + core.Text{ + TestID: "tile-review-file", + ContentFunc: func() string { + _ = rev.Get() + return sceneFileLabel() + }, + Style: core.Style{FontSize: 11, Color: specTextMuted}, + }, }, - Style: core.Style{FontSize: 11, Color: specTextMuted}, }, }, }, diff --git a/packages/game/editor/ui.go b/packages/game/editor/ui.go index b83ddf378..0de545a2a 100644 --- a/packages/game/editor/ui.go +++ b/packages/game/editor/ui.go @@ -746,7 +746,18 @@ func mainRow(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) []core.Node { return TileReviewPanelView(cx, ed, rev) }, Else: func(cx *core.Scope) core.Node { - return RightRailView(cx, ed, rev) + return core.Show{ + When: func() bool { + _ = rev.Get() + return ed.SketchPanelOpen() + }, + Then: func(cx *core.Scope) core.Node { + return SketchPanelView(cx, ed, rev) + }, + Else: func(cx *core.Scope) core.Node { + return RightRailView(cx, ed, rev) + }, + } }, } }, @@ -1711,6 +1722,14 @@ func statusBarView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No } return status } + if !ed.Playing() && ed.SketchActive() { + sx, sy := ed.SketchStatusSceneCoords() + return fmt.Sprintf("Sketch layer · scene %d, %d · Sketch · %s", + int(math.Round(float64(sx))), + int(math.Round(float64(sy))), + ed.SketchTool().String(), + ) + } zoom := int(math.Round(float64(ed.View2D().Zoom * 100))) status := ed.T("status.mode2d", l10n.Param("mode", mode), @@ -1979,6 +1998,9 @@ func statusBarView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No if ed.BuildErr != nil { return ed.T("status.buildError", l10n.Param("error", ed.BuildErr.Error())) } + if !ed.Playing() && ed.ViewMode == ViewMode2D && ed.SketchActive() { + return ed.T("sketch.statusHint") + } if ed.Status == "Ready" { return ed.T("status.ready") } diff --git a/packages/game/editor/viewport.go b/packages/game/editor/viewport.go index 213964e08..169048b4c 100644 --- a/packages/game/editor/viewport.go +++ b/packages/game/editor/viewport.go @@ -514,6 +514,7 @@ func (e *Editor) DrawViewport(d *core.Drawing, size core.Size) { e.drawComponentShapes2D(d, scene) e.drawViewportOverlays(d, scene) e.drawProblemOverlays2D(d, scene) + e.drawSketchOverlay(d) e.drawGizmo2D(d) e.drawComponentShapeHandles2D(d) e.drawMarqueeOverlay(d) @@ -1031,6 +1032,7 @@ type viewportGestures struct { cameraDrag bool boundsDrag bool roomDrag bool + sketchDrag bool touchCamPos core.Point hasTouchCam bool panCamDrag bool @@ -1071,7 +1073,7 @@ func (g *viewportGestures) pan(ed *Editor, ev core.PanEvent, spaceHeld, shiftHel g.panCamDrag = false g.panBoundsDrag = false g.panRoomDrag = false - if g.spacePan || g.middle || g.touchPan || g.cameraDrag || g.boundsDrag || g.roomDrag || ed.PickingConnectionTarget() { + if g.spacePan || g.middle || g.touchPan || g.cameraDrag || g.boundsDrag || g.roomDrag || g.sketchDrag || ed.SketchActive() || ed.PickingConnectionTarget() { return } if g.hasTouchCam { @@ -1269,12 +1271,14 @@ func (g *viewportGestures) touch(ed *Editor, ev core.TouchEvent) { ed.CancelCameraDrag() ed.CancelCameraBoundsDrag() ed.CancelRoomDrag() + ed.CancelSketchDrag() g.panCamDrag = false g.cameraDrag = false g.panBoundsDrag = false g.boundsDrag = false g.panRoomDrag = false g.roomDrag = false + g.sketchDrag = false } if ev.Phase == core.TouchCancel { // The system took the touches: a drag of an object or handle they made is put back, whether or not the pan reports its own cancel. nsgotest's Finger.Cancel (nsgo v0.3.0 nsgotest/pointer.go:259) reports only the touch cancel and no GestureCancelled to an active OnPan, so the touch cancel is the one this drag can rely on in tests. @@ -1461,6 +1465,19 @@ func ViewportView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Nod } } x, y := float32(ev.Position.X), float32(ev.Position.Y) + if ed.SketchActive() { + if ed.SketchTool() == SketchToolText { + if hit := ed.HitTestSketchMark(x, y); hit > 0 { + ed.SelectSketchMark(hit) + } else { + wx, wy := ed.CanvasToWorld(x, y) + ed.AddSketchText(wx, wy, "") + } + } else if hit := ed.HitTestSketchMark(x, y); hit > 0 { + ed.SelectSketchMark(hit) + } + return + } if ev.Modifiers.Alt && ed.ViewMode == ViewMode2D && !ed.Playing() && !ed.PickingConnectionTarget() { if ed.handleShapePress2D(x, y, true) { return @@ -1595,11 +1612,20 @@ func ViewportView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Nod _, strokeActive := ed.TileStrokeActive() selVisible := ed.ViewMode == ViewMode2D && isTileTool(ed.Tool) && ed.hasTileSel navPreview := ed.Tool == ToolNavTestPath && (ed.nav2D.preview.HasStart || ed.nav2D.preview.HasEnd) - activeOp := ed.Dragging2D() != Handle2DNone || ed.MarqueeActive() || ed.AssetDragActive() || ed.DraggingGizmo3D() || ed.DraggingHandle3D() || ed.DraggingComponentGizmo3D() || ed.PluginDragging3D() || ed.DraggingShape2D() || ed.PluginDragging2D() || ed.cameraDrag.active || ed.cameraBoundsDrag.active || ed.roomDrag.active || gmActive || (ed.terrain != nil && ed.terrain.stroke != nil) || strokeActive || selVisible || navPreview - return activeOp || (!ed.Playing() && ed.SelectionCount() > 0) + activeOp := ed.Dragging2D() != Handle2DNone || ed.MarqueeActive() || ed.AssetDragActive() || ed.DraggingGizmo3D() || ed.DraggingHandle3D() || ed.DraggingComponentGizmo3D() || ed.PluginDragging3D() || ed.DraggingShape2D() || ed.PluginDragging2D() || ed.cameraDrag.active || ed.cameraBoundsDrag.active || ed.roomDrag.active || ed.SketchDragging() || gmActive || (ed.terrain != nil && ed.terrain.stroke != nil) || strokeActive || selVisible || navPreview + return activeOp || ed.SketchActive() || (!ed.Playing() && ed.SelectionCount() > 0) }, Then: func(cx *core.Scope) core.Node { cx.OnKeyWith("escape", core.KeyOptions{When: core.KeyNotEditing}, func() { + if ed.SketchDragging() { + ed.CancelSketchDrag() + g.sketchDrag = false + return + } + if ed.SketchActive() { + ed.FinishSketch() + return + } _, gmActive := ed.GridMapStrokeActive() _, strokeActive := ed.TileStrokeActive() selVisible := ed.ViewMode == ViewMode2D && isTileTool(ed.Tool) && ed.hasTileSel @@ -1762,6 +1788,11 @@ func ViewportView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Nod } px, py := float32(ev.Position.X), float32(ev.Position.Y) if !spaceHeld() && !ed.PickingConnectionTarget() { + if ed.SketchActive() && ed.BeginSketchDrag(px, py) { + g.sketchDrag = true + g.suppressPress = true + return + } if ed.RoomCreateMode() && ed.BeginRoomDrag(px, py) { g.roomDrag = true return @@ -1802,6 +1833,20 @@ func ViewportView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Nod }, OnMouseMove: func(ev core.MouseEvent) { lastPointer, lastPointerMode, hasPointer = ev.Position, ed.ViewMode, true + if g.sketchDrag { + if !ed.SketchDragging() { + g.sketchDrag = false + } else if ev.PressedButton != core.MouseButtonLeft || ed.ViewMode != ViewMode2D { + g.sketchDrag = false + ed.EndSketchDrag() + g.suppressPress = true + return + } else { + ed.SetViewportPointer2D(float32(ev.Position.X), float32(ev.Position.Y)) + ed.UpdateSketchDrag(float32(ev.Position.X), float32(ev.Position.Y)) + return + } + } if g.cameraDrag { if !ed.cameraDrag.active { g.cameraDrag = false @@ -1906,6 +1951,12 @@ func ViewportView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Nod case core.MouseButtonMiddle: g.middle = false case core.MouseButtonLeft: + if g.sketchDrag { + g.sketchDrag = false + ed.EndSketchDrag() + g.suppressPress = true + return + } if g.cameraDrag { g.cameraDrag = false if ed.EndCameraDrag() { @@ -2024,6 +2075,7 @@ func ViewportView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Nod viewportTaskLegendOverlay(cx, ed, rev), viewportHistoryPreviewBannerView(cx, ed, rev), PlayTaskDotView(cx, ed, rev), + viewportSketchOverlayView(cx, ed, rev), }, append(viewportTileOverlays(cx, ed, rev), ToastView(cx, ed, rev))...), } } From e818b55054be601b7f0efb50857a39d74d3ab2fd Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Thu, 26 Nov 2026 13:14:29 +0900 Subject: [PATCH 2/5] fix(editor,editormcp): harden sketch lifecycle, bounds, MCP hold gate, panel close, Spec theme, and tests --- packages/game/editor/clipboard_group.go | 18 +- packages/game/editor/commands.go | 32 +- packages/game/editor/demo.go | 1 + packages/game/editor/editormcp/cutscene.go | 3 + packages/game/editor/editormcp/inspector.go | 9 +- packages/game/editor/editormcp/merge.go | 3 + packages/game/editor/editormcp/object_menu.go | 12 + packages/game/editor/editormcp/refs.go | 3 + packages/game/editor/editormcp/sketch_test.go | 71 + packages/game/editor/editormcp/states.go | 3 + packages/game/editor/editormcp/tiles.go | 9 + packages/game/editor/editormcp/tileset.go | 3 + packages/game/editor/project.go | 1 + packages/game/editor/sketch.go | 256 +++- packages/game/editor/sketch_png.go | 5 + packages/game/editor/sketch_test.go | 219 +++ packages/game/editor/sketch_ui.go | 1180 +++++++++-------- packages/game/editor/tile_review_ui.go | 10 +- 18 files changed, 1180 insertions(+), 658 deletions(-) diff --git a/packages/game/editor/clipboard_group.go b/packages/game/editor/clipboard_group.go index 364739893..6af4d2401 100644 --- a/packages/game/editor/clipboard_group.go +++ b/packages/game/editor/clipboard_group.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "maps" + "math" "slices" "strings" @@ -172,14 +173,27 @@ func (e *Editor) SetViewportPointer2D(canvasX, canvasY float32) { return } pos := math2d.Vec2{X: canvasX, Y: canvasY} - changed := !e.hasPointer2D || e.pointer2D != pos + prevHas := e.hasPointer2D + prevPos := e.pointer2D + changed := !prevHas || prevPos != pos if changed { e.pasteStreak = 0 } e.pointer2D = pos e.hasPointer2D = true if changed && e.SketchActive() { - e.notify() + // Only notify when the rounded integer scene coordinates shown in the status bar change, + // avoiding 120 Hz rev storms across the whole editor on sub-pixel mouse movement. + wx, wy := e.CanvasToWorld(pos.X, pos.Y) + rx, ry := int(math.Round(float64(wx))), int(math.Round(float64(wy))) + if !prevHas { + e.notify() + } else { + pwx, pwy := e.CanvasToWorld(prevPos.X, prevPos.Y) + if rx != int(math.Round(float64(pwx))) || ry != int(math.Round(float64(pwy))) { + e.notify() + } + } } } diff --git a/packages/game/editor/commands.go b/packages/game/editor/commands.go index a1de660c7..b982544be 100644 --- a/packages/game/editor/commands.go +++ b/packages/game/editor/commands.go @@ -1946,7 +1946,7 @@ func (e *Editor) initBuiltinCommands() { Keywords: []string{"sketch", "draw", "annotate", "agent", "viewport", "marks"}, Scope: ScopeViewport2D, Shortcut: "d", - Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D }, + Enabled: func() bool { return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D }, Checked: func() bool { return e.SketchActive() }, Run: func() error { e.ToggleSketch() @@ -1961,7 +1961,7 @@ func (e *Editor) initBuiltinCommands() { Keywords: []string{"sketch", "pen", "freehand", "line", "polyline"}, Scope: ScopeSketch, Shortcut: "p", - Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchActive() }, + Enabled: func() bool { return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D && e.SketchActive() }, Checked: func() bool { return e.SketchActive() && e.SketchTool() == SketchToolPen }, Run: func() error { e.SetSketchTool(SketchToolPen) @@ -1976,7 +1976,7 @@ func (e *Editor) initBuiltinCommands() { Keywords: []string{"sketch", "arrow", "pointer", "direction"}, Scope: ScopeSketch, Shortcut: "a", - Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchActive() }, + Enabled: func() bool { return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D && e.SketchActive() }, Checked: func() bool { return e.SketchActive() && e.SketchTool() == SketchToolArrow }, Run: func() error { e.SetSketchTool(SketchToolArrow) @@ -1991,7 +1991,7 @@ func (e *Editor) initBuiltinCommands() { Keywords: []string{"sketch", "box", "rect", "rectangle", "area"}, Scope: ScopeSketch, Shortcut: "b", - Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchActive() }, + Enabled: func() bool { return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D && e.SketchActive() }, Checked: func() bool { return e.SketchActive() && e.SketchTool() == SketchToolBox }, Run: func() error { e.SetSketchTool(SketchToolBox) @@ -2006,7 +2006,7 @@ func (e *Editor) initBuiltinCommands() { Keywords: []string{"sketch", "text", "label", "note", "callout"}, Scope: ScopeSketch, Shortcut: "t", - Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchActive() }, + Enabled: func() bool { return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D && e.SketchActive() }, Checked: func() bool { return e.SketchActive() && e.SketchTool() == SketchToolText }, Run: func() error { e.SetSketchTool(SketchToolText) @@ -2021,7 +2021,7 @@ func (e *Editor) initBuiltinCommands() { Keywords: []string{"sketch", "add", "insert", "mark", "keyboard"}, Scope: ScopeSketch, Shortcut: "i", - Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchActive() }, + Enabled: func() bool { return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D && e.SketchActive() }, Run: func() error { e.AddSketchMarkAtCursor("") return nil @@ -2036,7 +2036,7 @@ func (e *Editor) initBuiltinCommands() { Scope: ScopeSketch, Shortcut: "mod+z", Enabled: func() bool { - return notPlaying() && e.ViewMode == ViewMode2D && e.SketchActive() && e.CanUndoSketchMark() + return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D && e.SketchActive() && e.CanUndoSketchMark() }, Run: func() error { e.UndoLastSketchMark() @@ -2052,7 +2052,7 @@ func (e *Editor) initBuiltinCommands() { Scope: ScopeSketch, Shortcut: "h", Enabled: func() bool { - return notPlaying() && e.ViewMode == ViewMode2D && (e.SketchActive() || e.SketchMarkCount() > 0) + return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D && (e.SketchActive() || e.SketchMarkCount() > 0) }, Checked: func() bool { return e.SketchMarksHidden() }, Run: func() error { @@ -2068,7 +2068,7 @@ func (e *Editor) initBuiltinCommands() { Keywords: []string{"sketch", "clear", "delete", "marks"}, Scope: ScopeSketch, Shortcut: "mod+shift+backspace", - Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchMarkCount() > 0 }, + Enabled: func() bool { return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D && e.SketchMarkCount() > 0 }, Run: func() error { e.ClearSketch() return nil @@ -2082,7 +2082,7 @@ func (e *Editor) initBuiltinCommands() { Keywords: []string{"sketch", "done", "finish", "exit"}, Scope: ScopeSketch, Shortcut: "shift+d", - Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchActive() }, + Enabled: func() bool { return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D && e.SketchActive() }, Run: func() error { e.FinishSketch() return nil @@ -2097,7 +2097,7 @@ func (e *Editor) initBuiltinCommands() { Scope: ScopeSketch, Shortcut: "mod+enter", Enabled: func() bool { - return notPlaying() && e.ViewMode == ViewMode2D && e.SketchMarkCount() > 0 && !e.SketchHoldActive() + return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D && e.SketchAttached() && e.SketchMarkCount() > 0 && !e.SketchHoldActive() }, Run: func() error { _, err := e.SendSketch(e.SketchPromptDraft()) @@ -2113,7 +2113,7 @@ func (e *Editor) initBuiltinCommands() { Scope: ScopeViewport2D, Shortcut: "mod+enter", Enabled: func() bool { - return notPlaying() && e.ViewMode == ViewMode2D && e.SketchHoldActive() && e.SketchReading() != nil + return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D && e.SketchHoldActive() && e.SketchReading() != nil }, Run: func() error { return e.ApproveSketchReading() }, }, @@ -2126,7 +2126,7 @@ func (e *Editor) initBuiltinCommands() { Scope: ScopeViewport2D, Shortcut: "shift+m", Enabled: func() bool { - return notPlaying() && e.ViewMode == ViewMode2D && e.SketchReading() != nil && e.SketchMarkCount() > 0 + return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D && e.SketchReading() != nil && e.SketchMarkCount() > 0 }, Run: func() error { target := e.SelectedSketchMark() @@ -2145,7 +2145,7 @@ func (e *Editor) initBuiltinCommands() { Scope: ScopeViewport2D, Shortcut: "o", Enabled: func() bool { - return notPlaying() && e.ViewMode == ViewMode2D && (e.SketchReviewOpen() || e.TileReviewOpen()) && e.SketchMarkCount() > 0 + return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D && (e.SketchReviewOpen() || e.TileReviewOpen()) && e.SketchMarkCount() > 0 }, Checked: func() bool { return e.SketchReviewOverlayVisible() }, Run: func() error { @@ -2161,7 +2161,7 @@ func (e *Editor) initBuiltinCommands() { Keywords: []string{"sketch", "review", "keep", "accept", "clear"}, Scope: ScopeViewport2D, Shortcut: "mod+shift+enter", - Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchReviewOpen() }, + Enabled: func() bool { return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D && e.SketchReviewOpen() }, Run: func() error { return e.KeepSketchReview() }, }, { @@ -2172,7 +2172,7 @@ func (e *Editor) initBuiltinCommands() { Keywords: []string{"sketch", "review", "revert", "undo", "keep marks"}, Scope: ScopeViewport2D, Shortcut: "mod+backspace", - Enabled: func() bool { return notPlaying() && e.ViewMode == ViewMode2D && e.SketchReviewOpen() }, + Enabled: func() bool { return !e.sketchBlockedByScreen() && e.ViewMode == ViewMode2D && e.SketchReviewOpen() }, Run: func() error { return e.RevertSketchReview() }, }, } diff --git a/packages/game/editor/demo.go b/packages/game/editor/demo.go index 58b4dd18c..16f6efe44 100644 --- a/packages/game/editor/demo.go +++ b/packages/game/editor/demo.go @@ -231,6 +231,7 @@ func (e *Editor) OpenDemo() error { e.resetProblemsForProject() e.resetTasksForProject() e.resetHistoryPanelForProject() + e.resetSketchForProject() e.applyViewStateSnap(nil) e.Doc = DemoSceneDoc() diff --git a/packages/game/editor/editormcp/cutscene.go b/packages/game/editor/editormcp/cutscene.go index ae6c071f2..b164c53f4 100644 --- a/packages/game/editor/editormcp/cutscene.go +++ b/packages/game/editor/editormcp/cutscene.go @@ -153,6 +153,9 @@ func cutsceneWrite(ctx context.Context, c *Call) (*Result, error) { if ed.Playing() { return fmt.Errorf("cutscene_write: %w", editor.ErrPlaying) } + if holdErr := sketchHoldEditError(ed, clean); holdErr != nil { + return holdErr + } root := projectRoot(ed) if root == "" { return errors.New("cutscene_write: no project is open in the editor; open one with go tool game editor ") diff --git a/packages/game/editor/editormcp/inspector.go b/packages/game/editor/editormcp/inspector.go index 67b2098a2..0c713f265 100644 --- a/packages/game/editor/editormcp/inspector.go +++ b/packages/game/editor/editormcp/inspector.go @@ -164,7 +164,7 @@ func objectSetField(ctx context.Context, c *Call) (*Result, error) { defer ed.EndAgentStep() } - return ed.History.Group(label, func() error { + err := ed.History.Group(label, func() error { switch { case args.Property: v, err := scalarValue(args.Value) @@ -187,6 +187,13 @@ func objectSetField(ctx context.Context, c *Call) (*Result, error) { return nil } }) + if err != nil { + return err + } + if ed.SketchApproved() { + ed.RecordSketchReviewEdits(label, nil, []string{targetID}, nil) + } + return nil }) if err != nil { return nil, err diff --git a/packages/game/editor/editormcp/merge.go b/packages/game/editor/editormcp/merge.go index 36570b204..1ca932191 100644 --- a/packages/game/editor/editormcp/merge.go +++ b/packages/game/editor/editormcp/merge.go @@ -254,6 +254,9 @@ func mergeResolve(ctx context.Context, c *Call) (*Result, error) { } var out MergeStatusResult err := c.Editor(ctx, func(ed *editor.Editor) error { + if holdErr := sketchHoldEditError(ed, sceneName(ed, projectRoot(ed))); holdErr != nil { + return holdErr + } if args.Suggest != nil { if args.ID == "" { return errors.New("suggest requires id") diff --git a/packages/game/editor/editormcp/object_menu.go b/packages/game/editor/editormcp/object_menu.go index b44f7f1ff..ca6d2a509 100644 --- a/packages/game/editor/editormcp/object_menu.go +++ b/packages/game/editor/editormcp/object_menu.go @@ -262,6 +262,9 @@ func objectPasteYAML(ctx context.Context, c *Call) (*Result, error) { if err != nil { return err } + if ed.SketchApproved() { + ed.RecordSketchReviewEdits("Agent: paste "+id, []string{id}, nil, nil) + } out = ObjectPasteYAMLResult{ID: id, Revision: ed.Revision()} return nil }) @@ -341,6 +344,9 @@ func objectDuplicate(ctx context.Context, c *Call) (*Result, error) { if err != nil { return err } + if ed.SketchApproved() { + ed.RecordSketchReviewEdits("Agent: duplicate "+src, []string{id}, nil, nil) + } out = ObjectDuplicateResult{SourceID: src, ID: id, Revision: ed.Revision()} return nil }) @@ -436,6 +442,9 @@ func objectGroup(ctx context.Context, c *Call) (*Result, error) { if err != nil { return err } + if ed.SketchApproved() { + ed.RecordSketchReviewEdits("Agent: group "+gid, []string{gid}, ids, nil) + } out = ObjectGroupResult{GroupID: gid, Children: ids, Revision: ed.Revision()} return nil }) @@ -533,6 +542,9 @@ func objectMoveUnder(ctx context.Context, c *Call) (*Result, error) { if err := ed.MoveObjectUnder(id, args.Parent); err != nil { return err } + if ed.SketchApproved() { + ed.RecordSketchReviewEdits("Agent: move "+id, nil, []string{id}, nil) + } out = ObjectMoveUnderResult{ ID: id, Parent: args.Parent, diff --git a/packages/game/editor/editormcp/refs.go b/packages/game/editor/editormcp/refs.go index 534c10bb5..c5a3598da 100644 --- a/packages/game/editor/editormcp/refs.go +++ b/packages/game/editor/editormcp/refs.go @@ -210,6 +210,9 @@ func refactorRename(ctx context.Context, c *Call) (*Result, error) { var out RefactorRenameResult err = c.Editor(ctx, func(ed *editor.Editor) error { + if holdErr := sketchHoldEditError(ed, fromClean); holdErr != nil { + return holdErr + } plan, perr := ed.PreviewSafeRename(fromClean, toRaw) if plan == nil { if perr != nil { diff --git a/packages/game/editor/editormcp/sketch_test.go b/packages/game/editor/editormcp/sketch_test.go index 01ef2bf71..18ec761bf 100644 --- a/packages/game/editor/editormcp/sketch_test.go +++ b/packages/game/editor/editormcp/sketch_test.go @@ -5,6 +5,7 @@ import ( "image/png" "math" "strings" + "sync" "testing" "github.com/modelcontextprotocol/go-sdk/mcp" @@ -194,3 +195,73 @@ func TestSketchMCPReadReadingHoldGateAndKeepRevert(t *testing.T) { t.Fatalf("kept scene YAML contains sketch data:\n%s", string(keptYAML)) } } + +func TestSketchHoldGateBlocksAllMutatingToolsRecordsObjectReviewAndIsRaceFree(t *testing.T) { + f := openFixture(t) + f.ed.SetCanvasSize(640, 360) + s := editormcp.New(f.ed, editormcp.Options{OnPermissionAsk: allowAsk}) + t.Cleanup(func() { _ = s.Close() }) + cs := connect(t, s, nil) + + f.ed.AddSketchBox(80, 120, 60, 40, "spikes") + if _, err := f.ed.SendSketch("build spikes"); err != nil { + t.Fatalf("SendSketch: %v", err) + } + + // Verify ALL mutating MCP tools respect the active sketch hold gate. + blockedCalls := []struct { + name string + args map[string]any + }{ + {editormcp.ToolRefactorRename, map[string]any{"from": "scenes/main.scene.yaml", "to": "scenes/renamed.scene.yaml"}}, + {editormcp.ToolTilesetEdit, map[string]any{"ops": []map[string]any{{"op": "set_tile", "id": 0, "solid": true}}}}, + {editormcp.ToolStatesWrite, map[string]any{"file": "hero.states.yaml", "yaml": "version: 1\nentry: idle\nstates:\n - name: idle\n clip: anim/idle.animation.yaml\n"}}, + {editormcp.ToolCutsceneWrite, map[string]any{"file": "intro.cutscene.yaml", "yaml": "version: 2\nkind: timeline\nscene: scenes/main.scene.yaml\nlength: 2s\ntracks:\n - id: cam\n kind: camera\n clips:\n - id: c1\n start: 0s\n duration: 2s\n action: hold\n target: hero\n"}}, + {editormcp.ToolMergeResolve, map[string]any{"allAgent": true}}, + {editormcp.ToolTileReviewKeep, map[string]any{}}, + {editormcp.ToolTileReviewRevertAll, map[string]any{}}, + {editormcp.ToolObjectSetField, map[string]any{"id": "hero", "field": "x", "value": 99}}, + {editormcp.ToolObjectDuplicate, map[string]any{"id": "hero"}}, + } + for _, tc := range blockedCalls { + res := call(t, cs, tc.name, tc.args) + if !res.IsError { + t.Errorf("%s succeeded while sketch hold was active, want hold error", tc.name) + continue + } + if got := text(res); !strings.Contains(got, "waiting for the person to confirm") { + t.Errorf("%s error = %q, want sketch hold refusal", tc.name, got) + } + } + + // Exercise concurrent sketch_read and sketch_reading calls under -race. + var wg sync.WaitGroup + for range 4 { + wg.Add(2) + go func() { + defer wg.Done() + mustOK(t, call(t, cs, editormcp.ToolSketchRead, map[string]any{"includeImage": false})) + }() + go func() { + defer wg.Done() + mustOK(t, call(t, cs, editormcp.ToolSketchReading, map[string]any{ + "summary": "I read your sketch as:", + "items": []map[string]any{{"number": 1, "text": "Place spikes"}}, + })) + }() + } + wg.Wait() + + // Approving allows object_set_field and records it into the post-sketch review card. + if err := f.ed.ApproveSketchReading(); err != nil { + t.Fatalf("ApproveSketchReading: %v", err) + } + mustOK(t, call(t, cs, editormcp.ToolObjectSetField, map[string]any{"id": "hero", "field": "x", "value": 123})) + if !f.ed.SketchReviewOpen() { + t.Fatal("expected SketchReviewOpen() == true after approved object_set_field") + } + changes := f.ed.SketchReviewChanges() + if len(changes) == 0 || changes[0].ID != "hero" { + t.Fatalf("SketchReviewChanges = %+v, want hero recorded", changes) + } +} diff --git a/packages/game/editor/editormcp/states.go b/packages/game/editor/editormcp/states.go index fb64ad8f5..19919dcf8 100644 --- a/packages/game/editor/editormcp/states.go +++ b/packages/game/editor/editormcp/states.go @@ -146,6 +146,9 @@ func statesWrite(ctx context.Context, c *Call) (*Result, error) { if ed.Playing() { return fmt.Errorf("states_write: %w", editor.ErrPlaying) } + if holdErr := sketchHoldEditError(ed, clean); holdErr != nil { + return holdErr + } root := projectRoot(ed) if root == "" { return errors.New("states_write: no project is open in the editor; open one with go tool game editor ") diff --git a/packages/game/editor/editormcp/tiles.go b/packages/game/editor/editormcp/tiles.go index 69e06d4db..b43c64807 100644 --- a/packages/game/editor/editormcp/tiles.go +++ b/packages/game/editor/editormcp/tiles.go @@ -799,6 +799,9 @@ func tileReviewToggleRegion(ctx context.Context, c *Call, toolName string, rever } var st TileReviewStatusResult if err := c.Editor(ctx, func(ed *editor.Editor) error { + if holdErr := sketchHoldEditError(ed, sceneName(ed, projectRoot(ed))); holdErr != nil { + return holdErr + } var err error if args.ID != "" { err = ed.SetTileReviewRegionReverted(args.ID, revert) @@ -833,6 +836,9 @@ func tileReviewKeep(ctx context.Context, c *Call) (*Result, error) { } var res editor.AgentTileEditResult if err := c.Editor(ctx, func(ed *editor.Editor) error { + if holdErr := sketchHoldEditError(ed, sceneName(ed, projectRoot(ed))); holdErr != nil { + return holdErr + } var err error res, err = ed.KeepTileReview() return err @@ -851,6 +857,9 @@ func tileReviewRevertAll(ctx context.Context, c *Call) (*Result, error) { } var layer string if err := c.Editor(ctx, func(ed *editor.Editor) error { + if holdErr := sketchHoldEditError(ed, sceneName(ed, projectRoot(ed))); holdErr != nil { + return holdErr + } layer, _ = ed.TileReviewLayer() return ed.RevertAllTileReview() }); err != nil { diff --git a/packages/game/editor/editormcp/tileset.go b/packages/game/editor/editormcp/tileset.go index b32ea5801..6d905948a 100644 --- a/packages/game/editor/editormcp/tileset.go +++ b/packages/game/editor/editormcp/tileset.go @@ -317,6 +317,9 @@ func tilesetEdit(ctx context.Context, c *Call) (*Result, error) { if ed.Playing() { return fmt.Errorf("tileset_edit: %w", editor.ErrPlaying) } + if holdErr := sketchHoldEditError(ed, sceneName(ed, projectRoot(ed))); holdErr != nil { + return holdErr + } if clean != "" { if !ed.TilesetOpen() || ed.TilesetPath() != clean { if err := ed.OpenTilesetProjectFile(clean); err != nil { diff --git a/packages/game/editor/project.go b/packages/game/editor/project.go index 44782a00d..194aae23d 100644 --- a/packages/game/editor/project.go +++ b/packages/game/editor/project.go @@ -111,6 +111,7 @@ func (e *Editor) openProject(path, scene string, withScene bool) error { e.cancelTransientInteraction() e.resetInspectorSessionState() e.resetAgentForProject() + e.resetSketchForProject() e.clearTileBrushTransient() e.inspectAssetFile = false e.inspectLayer = false diff --git a/packages/game/editor/sketch.go b/packages/game/editor/sketch.go index 7e4866ba8..6394ebffc 100644 --- a/packages/game/editor/sketch.go +++ b/packages/game/editor/sketch.go @@ -290,38 +290,83 @@ type sketchReviewState struct { } type sketchState struct { - active bool - panelOpen bool - tool SketchTool - marks []SketchMark - undoStack [][]SketchMark - nextSeq uint64 - selectedMark int - marksHidden bool - attached bool - previewOpen bool - promptDraft string - hold SketchHoldState - reading *SketchReading - lastRequest *SketchAgentRequest - draft *sketchDraftDrag - review *sketchReviewState - forcePNGMarks bool + active bool + panelOpen bool + panelDismissed bool + tool SketchTool + marks []SketchMark + undoStack [][]SketchMark + nextSeq uint64 + selectedMark int + marksHidden bool + attached bool + previewOpen bool + promptDraft string + hold SketchHoldState + reading *SketchReading + lastRequest *SketchAgentRequest + draft *sketchDraftDrag + review *sketchReviewState + forcePNGMarks bool } const ( - maxSketchMarks = 200 - maxSketchUndoDepth = 64 - maxSketchPenPoints = 2048 - sketchBadgeRadiusPt = 9.0 - sketchDragMinDistPt = 3.0 - sketchPenStepMinPt = 3.0 - sketchDefaultBoxW = 96.0 - sketchDefaultBoxH = 40.0 - sketchDefaultArrowDX = 84.0 - sketchDefaultArrowDY = 36.0 + maxSketchMarks = 200 + maxSketchUndoDepth = 64 + maxSketchPenPoints = 2048 + maxSketchLabelRunes = 256 + maxSketchReadingItems = maxSketchMarks + maxSketchReadingAssumptions = 32 + maxSketchReadingTextRunes = 2048 + maxSketchPNGDim = 2048 + maxSketchPNGPixels = 4_000_000 + sketchBadgeRadiusPt = 9.0 + sketchDragMinDistPt = 3.0 + sketchPenStepMinPt = 3.0 + sketchDefaultBoxW = 96.0 + sketchDefaultBoxH = 40.0 + sketchDefaultArrowDX = 84.0 + sketchDefaultArrowDY = 36.0 ) +func clampSketchRunes(s string, maxRunes int) string { + s = strings.TrimSpace(s) + if maxRunes <= 0 || len(s) <= maxRunes { + return s + } + n := 0 + for i := range s { + if n == maxRunes { + return s[:i] + } + n++ + } + return s +} + +func (e *Editor) resetSketchForProject() { + if e == nil { + return + } + e.sketch = sketchState{} +} + +func (e *Editor) sketchBlockedByScreen() bool { + if e == nil { + return true + } + return e.playing || + e.StartScreenOpen() || + e.SettingsOpen() || + e.MergeConflictOpen() || + e.ChangesOpen() || + e.BuildReleaseScreenOpen() || + e.UsagesScreenOpen() || + e.PlaytestReportOpen() || + e.AssetGeneratorOpen() || + e.HUDLayoutOpen() +} + var ( // ErrSketchEmpty is returned when sending or reading a sketch with no marks. ErrSketchEmpty = errors.New("editor: no sketch marks on the viewport") @@ -409,6 +454,9 @@ func (e *Editor) SetSketchActive(on bool) { if e == nil || e.playing { return } + if on && e.sketchBlockedByScreen() { + return + } if on && e.ViewMode != ViewMode2D { e.SetViewMode(ViewMode2D) } @@ -417,6 +465,7 @@ func (e *Editor) SetSketchActive(on bool) { e.cancelActiveObjectDrags() e.sketch.active = true e.sketch.panelOpen = true + e.sketch.panelDismissed = false e.sketch.marksHidden = false if len(e.sketch.marks) > 0 { e.sketch.attached = true @@ -456,6 +505,9 @@ func (e *Editor) SketchPanelOpen() bool { if e == nil || e.playing || e.ViewMode != ViewMode2D { return false } + if e.sketch.panelDismissed && !e.sketch.active { + return false + } return e.sketch.panelOpen || e.sketch.active || e.sketch.reading != nil || e.SketchReviewOpen() } @@ -467,6 +519,9 @@ func (e *Editor) SetSketchPanelOpen(open bool) { if !open { e.sketch.active = false e.sketch.draft = nil + e.sketch.panelDismissed = true + } else { + e.sketch.panelDismissed = false } e.sketch.panelOpen = open e.notify() @@ -681,6 +736,7 @@ func (e *Editor) appendSketchMark(m SketchMark) SketchMark { if m.ID == "" { m.ID = fmt.Sprintf("mark_%d", e.sketch.nextSeq) } + m.Label = clampSketchRunes(m.Label, maxSketchLabelRunes) m.Number = len(e.sketch.marks) + 1 if len(e.sketch.marks) >= maxSketchMarks { e.sketch.marks = e.sketch.marks[1:] @@ -692,13 +748,17 @@ func (e *Editor) appendSketchMark(m SketchMark) SketchMark { e.sketch.attached = true e.sketch.marksHidden = false e.sketch.panelOpen = true + e.sketch.panelDismissed = false e.notify() return added.Clone() } // AddSketchBox adds a numbered Box mark strictly in scene coordinates without mutating SceneDoc or History. func (e *Editor) AddSketchBox(x, y, width, height float32, label string) SketchMark { - if e == nil { + if e == nil || e.playing { + return SketchMark{} + } + if !isFiniteFloat32(x) || !isFiniteFloat32(y) || !isFiniteFloat32(width) || !isFiniteFloat32(height) { return SketchMark{} } if width < 0 { @@ -709,24 +769,30 @@ func (e *Editor) AddSketchBox(x, y, width, height float32, label string) SketchM y += height height = -height } + if !isFiniteFloat32(x) || !isFiniteFloat32(y) || !isFiniteFloat32(width) || !isFiniteFloat32(height) { + return SketchMark{} + } r := SketchRect{X: x, Y: y, Width: width, Height: height} return e.appendSketchMark(SketchMark{ Kind: SketchToolBox, - Label: strings.TrimSpace(label), + Label: clampSketchRunes(label, maxSketchLabelRunes), Rect: &r, }) } // AddSketchArrow adds a numbered Arrow mark strictly in scene coordinates without mutating SceneDoc or History. func (e *Editor) AddSketchArrow(x0, y0, x1, y1 float32, label string) SketchMark { - if e == nil { + if e == nil || e.playing { + return SketchMark{} + } + if !isFiniteFloat32(x0) || !isFiniteFloat32(y0) || !isFiniteFloat32(x1) || !isFiniteFloat32(y1) { return SketchMark{} } s := SketchPoint{X: x0, Y: y0} t := SketchPoint{X: x1, Y: y1} return e.appendSketchMark(SketchMark{ Kind: SketchToolArrow, - Label: strings.TrimSpace(label), + Label: clampSketchRunes(label, maxSketchLabelRunes), Start: &s, End: &t, }) @@ -734,7 +800,7 @@ func (e *Editor) AddSketchArrow(x0, y0, x1, y1 float32, label string) SketchMark // AddSketchPen adds a numbered Pen polyline mark strictly in scene coordinates without mutating SceneDoc or History. func (e *Editor) AddSketchPen(points []SketchPoint, label string) SketchMark { - if e == nil || len(points) == 0 { + if e == nil || e.playing || len(points) == 0 { return SketchMark{} } clean := make([]SketchPoint, 0, min(len(points), maxSketchPenPoints)) @@ -751,20 +817,23 @@ func (e *Editor) AddSketchPen(points []SketchPoint, label string) SketchMark { } return e.appendSketchMark(SketchMark{ Kind: SketchToolPen, - Label: strings.TrimSpace(label), + Label: clampSketchRunes(label, maxSketchLabelRunes), Points: clean, }) } // AddSketchText adds a numbered Text mark strictly in scene coordinates without mutating SceneDoc or History. func (e *Editor) AddSketchText(x, y float32, label string) SketchMark { - if e == nil { + if e == nil || e.playing { + return SketchMark{} + } + if !isFiniteFloat32(x) || !isFiniteFloat32(y) { return SketchMark{} } at := SketchPoint{X: x, Y: y} return e.appendSketchMark(SketchMark{ Kind: SketchToolText, - Label: strings.TrimSpace(label), + Label: clampSketchRunes(label, maxSketchLabelRunes), At: &at, }) } @@ -797,10 +866,10 @@ func (e *Editor) AddSketchMarkAtCursor(label string) SketchMark { // SetSketchMarkLabel updates the optional text label on the 1-based sketch mark. func (e *Editor) SetSketchMarkLabel(number int, label string) bool { - if e == nil || number < 1 || number > len(e.sketch.marks) { + if e == nil || e.playing || number < 1 || number > len(e.sketch.marks) { return false } - clean := strings.TrimSpace(label) + clean := clampSketchRunes(label, maxSketchLabelRunes) if e.sketch.marks[number-1].Label == clean { return true } @@ -811,7 +880,7 @@ func (e *Editor) SetSketchMarkLabel(number int, label string) bool { // NudgeSelectedSketchMark translates the selected sketch mark by (dx, dy) in scene coordinates. func (e *Editor) NudgeSelectedSketchMark(dx, dy float32) bool { - if e == nil || !isFiniteFloat32(dx) || !isFiniteFloat32(dy) || (dx == 0 && dy == 0) { + if e == nil || e.playing || !isFiniteFloat32(dx) || !isFiniteFloat32(dy) || (dx == 0 && dy == 0) { return false } sel := e.SelectedSketchMark() @@ -851,7 +920,7 @@ func (e *Editor) NudgeSelectedSketchMark(dx, dy float32) bool { // DeleteSketchMark removes the 1-based mark and renumbers remaining marks sequentially. func (e *Editor) DeleteSketchMark(number int) bool { - if e == nil || number < 1 || number > len(e.sketch.marks) { + if e == nil || e.playing || number < 1 || number > len(e.sketch.marks) { return false } e.pushSketchUndo() @@ -868,7 +937,7 @@ func (e *Editor) CanUndoSketchMark() bool { // UndoLastSketchMark restores the previous sketch mark list without touching SceneDoc or Editor.History. func (e *Editor) UndoLastSketchMark() bool { - if e == nil || len(e.sketch.undoStack) == 0 { + if e == nil || e.playing || len(e.sketch.undoStack) == 0 { return false } prev := e.sketch.undoStack[len(e.sketch.undoStack)-1] @@ -882,7 +951,7 @@ func (e *Editor) UndoLastSketchMark() bool { // ClearSketch clears all sketch marks, any pending reading card, and any active confirmation hold. // It never modifies SceneDoc or Editor.History. func (e *Editor) ClearSketch() { - if e == nil { + if e == nil || e.playing { return } if len(e.sketch.marks) > 0 { @@ -945,6 +1014,9 @@ func (e *Editor) BeginSketchDrag(canvasX, canvasY float32) bool { tool := e.ensureSketchTool() hit := e.HitTestSketchMark(canvasX, canvasY) wx, wy := e.CanvasToWorld(canvasX, canvasY) + if !isFiniteFloat32(wx) || !isFiniteFloat32(wy) { + return false + } start := SketchPoint{X: wx, Y: wy} e.sketch.draft = &sketchDraftDrag{ tool: tool, @@ -964,6 +1036,9 @@ func (e *Editor) UpdateSketchDrag(canvasX, canvasY float32) bool { } dr := e.sketch.draft wx, wy := e.CanvasToWorld(canvasX, canvasY) + if !isFiniteFloat32(wx) || !isFiniteFloat32(wy) { + return false + } pt := SketchPoint{X: wx, Y: wy} sx, sy := e.WorldToCanvas(dr.startWorld.X, dr.startWorld.Y) if math.Hypot(float64(canvasX-sx), float64(canvasY-sy)) >= sketchDragMinDistPt { @@ -1046,6 +1121,9 @@ func (e *Editor) RenderSketchViewportPNG(scale float32) ([]byte, int, int, error if e == nil { return nil, 0, 0, errors.New("editor: nil editor") } + if e.ViewMode != ViewMode2D { + return nil, 0, 0, errors.New("editor: viewport sketch PNG requires 2D view mode") + } if scale <= 0 { scale = 1 } @@ -1053,6 +1131,22 @@ func (e *Editor) RenderSketchViewportPNG(scale float32) ([]byte, int, int, error return nil, 0, 0, fmt.Errorf("editor: sketch render scale %v must be between 0.25 and 4", scale) } w, h := e.CanvasSize() + if !isFiniteFloat32(w) || !isFiniteFloat32(h) || w <= 0 || h <= 0 { + return nil, 0, 0, fmt.Errorf("editor: invalid viewport canvas size %vx%v", w, h) + } + // Cap rendered dimensions to prevent OOM on ultra-high-DPI / oversized viewports. + pw := max(int(math.Round(float64(w*scale))), 1) + ph := max(int(math.Round(float64(h*scale))), 1) + if pw > maxSketchPNGDim || ph > maxSketchPNGDim || int64(pw)*int64(ph) > maxSketchPNGPixels { + fit := math.Min(float64(maxSketchPNGDim)/float64(w), float64(maxSketchPNGDim)/float64(h)) + areaFit := math.Sqrt(float64(maxSketchPNGPixels) / (float64(w) * float64(h))) + scale = float32(math.Min(float64(scale), math.Min(fit, areaFit))) + if scale < 0.25 { + scale = 0.25 + } + pw = min(max(int(math.Round(float64(w*scale))), 1), maxSketchPNGDim) + ph = min(max(int(math.Round(float64(h*scale))), 1), maxSketchPNGDim) + } var d core.Drawing d.Scale(scale, scale) size := core.Size{Width: core.Points(w), Height: core.Points(h)} @@ -1062,8 +1156,6 @@ func (e *Editor) RenderSketchViewportPNG(scale float32) ([]byte, int, int, error e.DrawViewport(&d, size) e.sketch.forcePNGMarks = prevForce - pw := max(int(math.Round(float64(w*scale))), 1) - ph := max(int(math.Round(float64(h*scale))), 1) res, err := gamemcp.RenderPNG(d.Ops, pw, ph, e.SpecPalette(nil).Viewport) if err != nil { return nil, 0, 0, err @@ -1082,7 +1174,10 @@ func (e *Editor) SendSketch(prompt string) (SketchAgentRequest, error) { if e == nil { return SketchAgentRequest{}, errors.New("editor: nil editor") } - if len(e.sketch.marks) == 0 { + if e.playing { + return SketchAgentRequest{}, ErrPlaying + } + if len(e.sketch.marks) == 0 || !e.sketch.attached { return SketchAgentRequest{}, ErrSketchEmpty } if strings.TrimSpace(prompt) == "" { @@ -1119,6 +1214,7 @@ func (e *Editor) SendSketch(prompt string) (SketchAgentRequest, error) { e.sketch.draft = nil e.sketch.previewOpen = false e.sketch.panelOpen = true + e.sketch.panelDismissed = false e.sketch.hold = SketchHoldPending e.sketch.reading = nil e.sketch.promptDraft = "" @@ -1178,31 +1274,43 @@ func (e *Editor) PostSketchReading(reading SketchReading) error { if e == nil { return errors.New("editor: nil editor") } + if e.playing { + return ErrPlaying + } if len(e.sketch.marks) == 0 { return ErrSketchEmpty } if len(reading.Items) == 0 { return errors.New("editor: sketch reading must include at least one item") } - if strings.TrimSpace(reading.Summary) == "" { - reading.Summary = "I read your sketch as:" + if len(reading.Items) > maxSketchReadingItems { + return fmt.Errorf("editor: sketch reading has %d items, max %d", len(reading.Items), maxSketchReadingItems) + } + if len(reading.Assumptions) > maxSketchReadingAssumptions { + return fmt.Errorf("editor: sketch reading has %d assumptions, max %d", len(reading.Assumptions), maxSketchReadingAssumptions) + } + summary := clampSketchRunes(reading.Summary, maxSketchReadingTextRunes) + if summary == "" { + summary = "I read your sketch as:" } items := make([]SketchReadingItem, len(reading.Items)) for i, it := range reading.Items { if it.Number < 1 || it.Number > len(e.sketch.marks) { return fmt.Errorf("editor: sketch reading item number %d out of range (1..%d)", it.Number, len(e.sketch.marks)) } - if strings.TrimSpace(it.Text) == "" { + it.Text = clampSketchRunes(it.Text, maxSketchReadingTextRunes) + if it.Text == "" { return fmt.Errorf("editor: sketch reading item %d has empty text", it.Number) } - if strings.TrimSpace(it.Mark) == "" { + it.Mark = clampSketchRunes(it.Mark, maxSketchLabelRunes) + if it.Mark == "" { it.Mark = e.sketch.marks[it.Number-1].ReadingHeading() } items[i] = it } assumptions := make([]string, 0, len(reading.Assumptions)) for _, a := range reading.Assumptions { - if s := strings.TrimSpace(a); s != "" { + if s := clampSketchRunes(a, maxSketchReadingTextRunes); s != "" { assumptions = append(assumptions, s) } } @@ -1211,13 +1319,14 @@ func (e *Editor) PostSketchReading(reading SketchReading) error { now = e.Now() } e.sketch.reading = &SketchReading{ - Summary: strings.TrimSpace(reading.Summary), + Summary: summary, Items: items, Assumptions: assumptions, PostedAt: now, } e.sketch.hold = SketchHoldReading e.sketch.panelOpen = true + e.sketch.panelDismissed = false e.Status = "Agent posted sketch reading · choose Go ahead or Correct a mark" e.notify() return nil @@ -1229,6 +1338,9 @@ func (e *Editor) ApproveSketchReading() error { if e == nil { return errors.New("editor: nil editor") } + if e.playing { + return ErrPlaying + } if len(e.sketch.marks) == 0 { return ErrSketchEmpty } @@ -1244,6 +1356,7 @@ func (e *Editor) ApproveSketchReading() error { e.sketch.active = false e.sketch.draft = nil e.sketch.panelOpen = true + e.sketch.panelDismissed = false e.sketch.review = &sketchReviewState{ open: false, overlayVisible: true, @@ -1265,6 +1378,9 @@ func (e *Editor) CorrectSketchMark(number int) error { if e == nil { return errors.New("editor: nil editor") } + if e.playing { + return ErrPlaying + } if len(e.sketch.marks) == 0 { return ErrSketchEmpty } @@ -1278,6 +1394,7 @@ func (e *Editor) CorrectSketchMark(number int) error { e.sketch.tool = e.sketch.marks[number-1].Kind e.sketch.active = true e.sketch.panelOpen = true + e.sketch.panelDismissed = false e.sketch.marksHidden = false e.sketch.attached = true e.sketch.hold = SketchHoldPending @@ -1296,6 +1413,9 @@ func (e *Editor) ReplyToSketchReading(message string) error { if e == nil { return errors.New("editor: nil editor") } + if e.playing { + return ErrPlaying + } msg := strings.TrimSpace(message) if msg == "" { return errors.New("editor: reply message cannot be empty") @@ -1314,6 +1434,7 @@ func (e *Editor) ReplyToSketchReading(message string) error { e.sketch.hold = SketchHoldApproved e.sketch.promptDraft = "" e.sketch.panelOpen = true + e.sketch.panelDismissed = false if e.sketch.review == nil { e.sketch.review = &sketchReviewState{ open: false, @@ -1421,6 +1542,7 @@ func (e *Editor) RecordSketchReviewEdits(label string, addedIDs, changedIDs, rem rv.changes = append(rv.changes, SketchReviewChange{Kind: SketchChangeChanged, ID: label}) } e.sketch.panelOpen = true + e.sketch.panelDismissed = false e.notify() } @@ -1465,12 +1587,33 @@ func (e *Editor) RevertSketchReview() error { return fmt.Errorf("editor: revert sketch review: %w", err) } e.Doc = doc - if e.History != nil && rv.historyStart >= 0 && rv.historyStart <= len(e.History.commands) { - clear(e.History.commands[rv.historyStart:]) - e.History.commands = e.History.commands[:rv.historyStart] - e.History.cursor = rv.historyStart + if e.History != nil && rv.historyStart >= 0 { + cut := min(rv.historyStart, len(e.History.commands)) + clear(e.History.commands[cut:]) + e.History.commands = e.History.commands[:cut] + if e.History.cursor > cut { + e.History.cursor = cut + } } e.Rebuild() + // Drop any selection IDs that pointed at agent-added objects removed by Revert. + if e.SelectedID != "" { + if o, _, _ := e.FindObject(e.SelectedID); o == nil { + e.SelectedID = "" + } + } + if len(e.selectedIDs) > 0 { + kept := make([]string, 0, len(e.selectedIDs)) + for _, id := range e.selectedIDs { + if o, _, _ := e.FindObject(id); o != nil { + kept = append(kept, id) + } + } + e.selectedIDs = kept + if e.SelectedID == "" && len(kept) > 0 { + e.SelectedID = kept[len(kept)-1] + } + } } e.keepSketchOnReviewRevert() e.Status = "Reverted agent changes · sketch kept to send again" @@ -1494,6 +1637,7 @@ func (e *Editor) clearSketchOnReviewKeep() { e.sketch.reading = nil e.sketch.lastRequest = nil e.sketch.panelOpen = false + e.sketch.panelDismissed = false } // keepSketchOnReviewRevert preserves the sketch marks ready to send again when an agent review is Reverted. @@ -1509,6 +1653,7 @@ func (e *Editor) keepSketchOnReviewRevert() { e.sketch.attached = true e.sketch.marksHidden = false e.sketch.panelOpen = true + e.sketch.panelDismissed = false } } @@ -1638,6 +1783,9 @@ func (e *Editor) drawSketchDraft(d *core.Drawing, spec SpecPalette, dr *sketchDr func (e *Editor) drawSketchMark(d *core.Drawing, spec SpecPalette, m SketchMark, selected, reviewDotted bool, alpha float32) { haloColor := core.RGBA(0x000000, 0.55*alpha) + if !spec.Dark { + haloColor = ui.Alpha(spec.Bg, 0.72*alpha) + } haloWidth := float32(5) if selected { haloColor = ui.Alpha(spec.Accent.Edge, 0.75) diff --git a/packages/game/editor/sketch_png.go b/packages/game/editor/sketch_png.go index 6f31ff8f2..a6b6668af 100644 --- a/packages/game/editor/sketch_png.go +++ b/packages/game/editor/sketch_png.go @@ -231,7 +231,12 @@ func drawSketchBitmapString(dst *image.RGBA, x, y int, text string, col core.Col bounds := dst.Bounds() cx := x + drawn := 0 for _, ch := range text { + if drawn >= 256 { + break + } + drawn++ glyph, ok := sketchBitmapGlyph5x7[ch] if !ok { if ch >= 'a' && ch <= 'z' { diff --git a/packages/game/editor/sketch_test.go b/packages/game/editor/sketch_test.go index bcb400c77..5b9f95e68 100644 --- a/packages/game/editor/sketch_test.go +++ b/packages/game/editor/sketch_test.go @@ -2,6 +2,7 @@ package editor_test import ( "bytes" + "errors" "image/png" "math" "strings" @@ -522,3 +523,221 @@ func TestSketchUIAndScreenshots(t *testing.T) { app.Screenshot("sketch-review") } + +func TestSketchLifecycleResetPlayGuardAndDetachedChip(t *testing.T) { + ed := newSketchTestEditor(t) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1280, 760)) + _ = app + + // Detaching the sketch chip prevents SendSketch from attaching removed marks. + ed.AddSketchBox(100, 100, 60, 40, "spikes") + ed.SetSketchAttached(false) + if _, err := ed.SendSketch("build it"); !errors.Is(err, editor.ErrSketchEmpty) { + t.Fatalf("SendSketch with detached chip = %v, want ErrSketchEmpty", err) + } + ed.SetSketchAttached(true) + + // Send, post reading, approve, and record review edits, then Play guards all mutators. + if _, err := ed.SendSketch("build spikes"); err != nil { + t.Fatalf("SendSketch: %v", err) + } + if err := ed.PostSketchReading(editor.SketchReading{ + Items: []editor.SketchReadingItem{{Number: 1, Text: "Add spikes"}}, + }); err != nil { + t.Fatalf("PostSketchReading: %v", err) + } + if err := ed.Play(); err != nil { + t.Fatalf("Play: %v", err) + } + if m := ed.AddSketchBox(10, 10, 20, 20, "bad"); m.Number != 0 { + t.Fatalf("AddSketchBox during Play succeeded: %+v", m) + } + if m := ed.AddSketchArrow(10, 10, 20, 20, "bad"); m.Number != 0 { + t.Fatalf("AddSketchArrow during Play succeeded: %+v", m) + } + if m := ed.AddSketchText(10, 10, "bad"); m.Number != 0 { + t.Fatalf("AddSketchText during Play succeeded: %+v", m) + } + if _, err := ed.SendSketch("bad"); !errors.Is(err, editor.ErrPlaying) { + t.Fatalf("SendSketch during Play = %v, want ErrPlaying", err) + } + if err := ed.ApproveSketchReading(); !errors.Is(err, editor.ErrPlaying) { + t.Fatalf("ApproveSketchReading during Play = %v, want ErrPlaying", err) + } + if err := ed.CorrectSketchMark(1); !errors.Is(err, editor.ErrPlaying) { + t.Fatalf("CorrectSketchMark during Play = %v, want ErrPlaying", err) + } + if err := ed.ReplyToSketchReading("ok"); !errors.Is(err, editor.ErrPlaying) { + t.Fatalf("ReplyToSketchReading during Play = %v, want ErrPlaying", err) + } + if err := ed.Stop(); err != nil { + t.Fatalf("Stop: %v", err) + } + + // OpenDemo resets all sketch marks, reading, hold gate, and review baseYAML so nothing leaks across projects. + if err := ed.OpenDemo(); err != nil { + t.Fatalf("OpenDemo: %v", err) + } + if ed.SketchMarkCount() != 0 || ed.SketchHoldActive() || ed.SketchReading() != nil || ed.SketchReviewOpen() { + t.Fatalf("OpenDemo leaked sketch state: marks=%d hold=%v reading=%v review=%v", + ed.SketchMarkCount(), ed.SketchHoldActive(), ed.SketchReading() != nil, ed.SketchReviewOpen()) + } +} + +func TestSketchNonFiniteCoordsAndPayloadBounds(t *testing.T) { + ed := newSketchTestEditor(t) + nan := float32(math.NaN()) + inf := float32(math.Inf(1)) + + if m := ed.AddSketchBox(nan, 0, 10, 10, "nan"); m.Number != 0 { + t.Fatalf("AddSketchBox accepted NaN: %+v", m) + } + if m := ed.AddSketchBox(0, 0, inf, 10, "inf"); m.Number != 0 { + t.Fatalf("AddSketchBox accepted Inf: %+v", m) + } + if m := ed.AddSketchArrow(0, 0, nan, 10, "nan"); m.Number != 0 { + t.Fatalf("AddSketchArrow accepted NaN: %+v", m) + } + if m := ed.AddSketchText(inf, 0, "inf"); m.Number != 0 { + t.Fatalf("AddSketchText accepted Inf: %+v", m) + } + if ed.SketchMarkCount() != 0 { + t.Fatalf("non-finite marks were stored: count=%d", ed.SketchMarkCount()) + } + + // Huge label is clamped cleanly. + longLabel := strings.Repeat("x", 1000) + mk := ed.AddSketchBox(20, 20, 40, 30, longLabel) + if len([]rune(mk.Label)) > 256 { + t.Fatalf("label was not clamped: len=%d", len([]rune(mk.Label))) + } + + // PostSketchReading refuses > 200 items and > 32 assumptions. + tooManyItems := make([]editor.SketchReadingItem, 201) + for i := range tooManyItems { + tooManyItems[i] = editor.SketchReadingItem{Number: 1, Text: "x"} + } + if err := ed.PostSketchReading(editor.SketchReading{Items: tooManyItems}); err == nil { + t.Fatal("PostSketchReading accepted 201 items, want error") + } + tooManyAssump := make([]string, 33) + for i := range tooManyAssump { + tooManyAssump[i] = "a" + } + if err := ed.PostSketchReading(editor.SketchReading{ + Items: []editor.SketchReadingItem{{Number: 1, Text: "ok"}}, + Assumptions: tooManyAssump, + }); err == nil { + t.Fatal("PostSketchReading accepted 33 assumptions, want error") + } + + // RenderSketchViewportPNG refuses 3D view mode and caps huge viewports cleanly. + ed.SetViewMode(editor.ViewMode3D) + if _, _, _, err := ed.RenderSketchViewportPNG(1); err == nil { + t.Fatal("RenderSketchViewportPNG succeeded in 3D mode, want error") + } + ed.SetViewMode(editor.ViewMode2D) + ed.SetCanvasSize(3000, 3000) + _, pw, ph, err := ed.RenderSketchViewportPNG(4) + if err != nil { + t.Fatalf("RenderSketchViewportPNG on oversized viewport: %v", err) + } + if pw > 2048 || ph > 2048 || int64(pw)*int64(ph) > 4_000_000 { + t.Fatalf("RenderSketchViewportPNG did not cap pixels: %dx%d", pw, ph) + } +} + +func TestSketchPanelCloseSpecLightTypingAndRevertSelection(t *testing.T) { + ed := newSketchTestEditor(t) + ed.AddSketchBox(100, 100, 80, 40, "spikes") + ed.StartSketch() + if _, err := ed.SendSketch("build spikes"); err != nil { + t.Fatalf("SendSketch: %v", err) + } + if err := ed.PostSketchReading(editor.SketchReading{ + Items: []editor.SketchReadingItem{{Number: 1, Text: "Add spikes"}}, + }); err != nil { + t.Fatalf("PostSketchReading: %v", err) + } + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1360, 820), 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:sketch-agent-panel").Style.Background; got != light.Panel { + t.Fatalf("light mode sketch-agent-panel bg = %#x, want %#x", uint32(got), uint32(light.Panel)) + } + + // Clicking sketch-panel-close must dismiss the panel cleanly even while a reading card is open, + // revealing RightRailView underneath. + app.Press("id:sketch-panel-close") + app.Settle() + if ed.SketchPanelOpen() { + t.Fatal("SketchPanelOpen remained true after pressing sketch-panel-close with reading open") + } + if !app.Exists("id:right-rail-inspector-wrap") { + t.Fatal("expected RightRailView (right-rail-inspector-wrap) visible after closing SketchPanelView") + } + + // Reopen panel, focus composer input -> IsTyping() == true, then flip Dark mode live. + app.Post(func() { ed.SetSketchPanelOpen(true) }) + app.Settle() + app.Focus("id:sketch-composer-input") + app.Settle() + if !ed.IsTyping() { + t.Fatal("expected IsTyping() true while sketch-composer-input is focused") + } + app.SetEnvironment(core.Environment{ + OS: core.OSMacOS, + Idiom: core.IdiomDesktop, + Dark: true, + Locale: "en-US", + }) + if got := app.Find("id:sketch-agent-panel").Style.Background; got != dark.Panel { + t.Fatalf("dark mode sketch-agent-panel bg = %#x, want %#x", uint32(got), uint32(dark.Panel)) + } + + // Full-window screens block CmdSketchToggle and SetSketchActive. + app.Post(func() { + ed.OpenSettingsPage(editor.SettingsPageGeneral) + ed.SetSketchActive(true) + }) + app.Settle() + if ed.SketchActive() { + t.Fatal("SetSketchActive(true) succeeded while Settings full-window screen was open") + } + app.Post(func() { ed.CloseSettings() }) + app.Settle() + + // RevertSketchReview must clear SelectedID when it pointed at a reverted agent-added object. + app.Post(func() { + if err := ed.ApproveSketchReading(); err != nil { + t.Errorf("ApproveSketchReading: %v", err) + return + } + addedID, err := ed.PlaceObject("Actors", sceneformat.ObjectDoc{ID: "temp_spikes", Name: "temp_spikes", X: 120, Y: 120}) + if err != nil { + t.Errorf("PlaceObject: %v", err) + return + } + ed.SelectObject(addedID) + ed.RecordSketchReviewEdits("Agent: add temp_spikes", []string{addedID}, nil, nil) + if err := ed.RevertSketchReview(); err != nil { + t.Errorf("RevertSketchReview: %v", err) + } + }) + app.Settle() + if ed.SelectedID != "" { + t.Fatalf("SelectedID = %q after RevertSketchReview removed object, want empty", ed.SelectedID) + } +} diff --git a/packages/game/editor/sketch_ui.go b/packages/game/editor/sketch_ui.go index 2f27e17b3..8a99876dc 100644 --- a/packages/game/editor/sketch_ui.go +++ b/packages/game/editor/sketch_ui.go @@ -17,343 +17,349 @@ func viewportSketchOverlayView(cx *core.Scope, ed *Editor, rev *core.Signal[uint _ = rev.Get() return ed.SketchActive() }) + darkMemo := core.NewMemo(cx, func() bool { + _ = rev.Get() + return ed.SpecPalette(cx).Dark + }) return core.Show{ When: active.Get, Then: func(cx *core.Scope) core.Node { - p := ed.SpecPalette(cx) - divider := func() core.Node { - return core.View{ - Style: core.Style{ - Width: core.Pt(1), - Height: core.Pt(16), - Background: p.LineRaised, - Margin: core.Symmetric(0, 4), - }, + return core.Dynamic(func(cx *core.Scope) core.Node { + p := SpecPaletteFor(darkMemo.Get()) + divider := func() core.Node { + return core.View{ + Style: core.Style{ + Width: core.Pt(1), + Height: core.Pt(16), + Background: p.LineRaised, + Margin: core.Symmetric(0, 4), + }, + } } - } - toolBtn := func(testID string, tool SketchTool, label string, key string, icon func() *core.SVG, textFallback string) core.Node { - t := tool - btn := ui.Button{ - TestID: testID, - Label: fmt.Sprintf("%s · %s", label, key), - Size: ui.SizeSmall, - Variant: ui.ButtonGhost, - Color: func() core.Color { - _ = rev.Get() - if ed.SketchTool() == t { - return p.LineRaised - } - return core.Transparent - }, - Tint: func() core.Color { - _ = rev.Get() - if ed.SketchTool() == t { - return p.TextPrimary - } - return p.TextMuted - }, - TextStyle: core.Style{ - FontSize: 12, - FontWeight: 600, - Color: p.TextSecondary, - }, - Style: core.Style{ - Width: core.Pt(32), - Height: core.Pt(28), - CornerRadius: 6, - FocusVisible: p.FocusRing(2), - }, - OnPress: func() { - ed.SetSketchTool(t) - }, - } - if icon != nil { - btn.Icon = icon - btn.IconSize = 15 - } else { - btn.Text = textFallback + toolBtn := func(testID string, tool SketchTool, label string, key string, icon func() *core.SVG, textFallback string) core.Node { + t := tool + btn := ui.Button{ + TestID: testID, + Label: fmt.Sprintf("%s · %s", label, key), + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Color: func() core.Color { + _ = rev.Get() + if ed.SketchTool() == t { + return p.LineRaised + } + return core.Transparent + }, + Tint: func() core.Color { + _ = rev.Get() + if ed.SketchTool() == t { + return p.TextPrimary + } + return p.TextMuted + }, + TextStyle: core.Style{ + FontSize: 12, + FontWeight: 600, + Color: p.TextSecondary, + }, + Style: core.Style{ + Width: core.Pt(32), + Height: core.Pt(28), + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.SetSketchTool(t) + }, + } + if icon != nil { + btn.Icon = icon + btn.IconSize = 15 + } else { + btn.Text = textFallback + } + return btn } - return btn - } - selectedMarkKey := core.NewMemo(cx, func() int { - _ = rev.Get() - return ed.SelectedSketchMark() - }) + selectedMarkKey := core.NewMemo(cx, func() int { + _ = rev.Get() + return ed.SelectedSketchMark() + }) - return core.View{ - TestID: "viewport-sketch-overlay-wrap", - PointerEvents: core.PointerEventsBoxNone, - Style: core.Style{ - Position: core.Absolute, - Left: core.Pt(0), - Right: core.Pt(0), - Top: core.Pt(14), - AlignItems: core.AlignCenter, - Gap: 8, - }, - Children: []core.Node{ - // Main floating sketch toolbar matching Sketch.dc.html. - core.View{ - TestID: "viewport-sketch-toolbar", - Role: core.RoleToolbar, - Label: ed.T("sketch.toolbarLabel"), - Style: core.Style{ - Direction: core.Row, - AlignItems: core.AlignCenter, - Gap: 2, - Padding: core.All(4), - CornerRadius: 12, - Background: ui.Alpha(p.Raised, 0.96), - BorderWidth: 1, - BorderColor: p.LineRaised, - }, - Children: []core.Node{ - toolBtn("sketch-tool-pen", SketchToolPen, ed.T("sketch.tool.pen"), "P", lucide.Pencil, ""), - toolBtn("sketch-tool-arrow", SketchToolArrow, ed.T("sketch.tool.arrow"), "A", lucide.ArrowUpRight, ""), - toolBtn("sketch-tool-box", SketchToolBox, ed.T("sketch.tool.box"), "B", lucide.Square, ""), - toolBtn("sketch-tool-text", SketchToolText, ed.T("sketch.tool.text"), "T", nil, "T"), - divider(), - ui.Button{ - TestID: "sketch-undo-mark", - Icon: lucide.RotateCcw, - IconSize: 15, - Label: ed.T("sketch.undoMark"), - Size: ui.SizeSmall, - Variant: ui.ButtonGhost, - Side: 28, - Disabled: func() bool { - _ = rev.Get() - return !ed.CanUndoSketchMark() - }, - Tint: func() core.Color { return p.TextMuted }, - Style: core.Style{ - Width: core.Pt(32), - Height: core.Pt(28), - CornerRadius: 6, - FocusVisible: p.FocusRing(2), - }, - OnPress: func() { - ed.UndoLastSketchMark() - }, - }, - ui.Button{ - TestID: "sketch-toggle-marks", - Icon: lucide.Eye, - IconSize: 15, - LabelFunc: func() string { - _ = rev.Get() - if ed.SketchMarksHidden() { - return ed.T("sketch.showMarks") - } - return ed.T("sketch.hideMarks") - }, - Size: ui.SizeSmall, - Variant: ui.ButtonGhost, - Color: func() core.Color { - _ = rev.Get() - if ed.SketchMarksHidden() { - return p.LineRaised - } - return core.Transparent - }, - Tint: func() core.Color { - _ = rev.Get() - if ed.SketchMarksHidden() { - return p.TextPrimary - } - return p.TextMuted - }, - Style: core.Style{ - Width: core.Pt(32), - Height: core.Pt(28), - CornerRadius: 6, - FocusVisible: p.FocusRing(2), - }, - OnPress: func() { - ed.ToggleSketchMarksHidden() - }, - }, - core.Text{ - TestID: "sketch-bar-count", - ContentFunc: func() string { - _ = rev.Get() - return ed.SketchBarCountLabel() - }, - Style: core.Style{ - FontSize: 11.5, - Color: p.TextFaint, - Padding: core.Symmetric(0, 6), - }, + return core.View{ + TestID: "viewport-sketch-overlay-wrap", + PointerEvents: core.PointerEventsBoxNone, + Style: core.Style{ + Position: core.Absolute, + Left: core.Pt(0), + Right: core.Pt(0), + Top: core.Pt(14), + AlignItems: core.AlignCenter, + Gap: 8, + }, + Children: []core.Node{ + // Main floating sketch toolbar matching Sketch.dc.html. + core.View{ + TestID: "viewport-sketch-toolbar", + Role: core.RoleToolbar, + Label: ed.T("sketch.toolbarLabel"), + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 2, + Padding: core.All(4), + CornerRadius: 12, + Background: ui.Alpha(p.Raised, 0.96), + BorderWidth: 1, + BorderColor: p.LineRaised, }, - ui.Button{ - TestID: "sketch-clear", - Text: ed.T("sketch.clear"), - Label: ed.T("sketch.clear"), - Size: ui.SizeSmall, - Variant: ui.ButtonGhost, - Disabled: func() bool { - _ = rev.Get() - return ed.SketchMarkCount() == 0 - }, - TextStyle: core.Style{ - FontSize: 12, - FontWeight: 500, - Color: p.TextMuted, - }, - Style: core.Style{ - Height: core.Pt(28), - Padding: core.Symmetric(0, 8), - CornerRadius: 6, - FocusVisible: p.FocusRing(2), + Children: []core.Node{ + toolBtn("sketch-tool-pen", SketchToolPen, ed.T("sketch.tool.pen"), "P", lucide.Pencil, ""), + toolBtn("sketch-tool-arrow", SketchToolArrow, ed.T("sketch.tool.arrow"), "A", lucide.ArrowUpRight, ""), + toolBtn("sketch-tool-box", SketchToolBox, ed.T("sketch.tool.box"), "B", lucide.Square, ""), + toolBtn("sketch-tool-text", SketchToolText, ed.T("sketch.tool.text"), "T", nil, "T"), + divider(), + ui.Button{ + TestID: "sketch-undo-mark", + Icon: lucide.RotateCcw, + IconSize: 15, + Label: ed.T("sketch.undoMark"), + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Side: 28, + Disabled: func() bool { + _ = rev.Get() + return !ed.CanUndoSketchMark() + }, + Tint: func() core.Color { return p.TextMuted }, + Style: core.Style{ + Width: core.Pt(32), + Height: core.Pt(28), + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.UndoLastSketchMark() + }, }, - OnPress: func() { - ed.ClearSketch() + ui.Button{ + TestID: "sketch-toggle-marks", + Icon: lucide.Eye, + IconSize: 15, + LabelFunc: func() string { + _ = rev.Get() + if ed.SketchMarksHidden() { + return ed.T("sketch.showMarks") + } + return ed.T("sketch.hideMarks") + }, + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Color: func() core.Color { + _ = rev.Get() + if ed.SketchMarksHidden() { + return p.LineRaised + } + return core.Transparent + }, + Tint: func() core.Color { + _ = rev.Get() + if ed.SketchMarksHidden() { + return p.TextPrimary + } + return p.TextMuted + }, + Style: core.Style{ + Width: core.Pt(32), + Height: core.Pt(28), + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.ToggleSketchMarksHidden() + }, }, - }, - divider(), - ui.Button{ - TestID: "sketch-done", - Text: ed.T("sketch.done"), - Label: ed.T("sketch.done"), - Size: ui.SizeSmall, - Variant: ui.ButtonGhost, - Color: func() core.Color { return p.TextPrimary }, - TextStyle: core.Style{ - FontSize: 12, - FontWeight: 600, - Color: p.OnTextPrimary, + core.Text{ + TestID: "sketch-bar-count", + ContentFunc: func() string { + _ = rev.Get() + return ed.SketchBarCountLabel() + }, + Style: core.Style{ + FontSize: 11.5, + Color: p.TextFaint, + Padding: core.Symmetric(0, 6), + }, }, - Style: core.Style{ - Height: core.Pt(28), - Padding: core.Symmetric(0, 12), - CornerRadius: 6, - FocusVisible: p.FocusRing(2), + ui.Button{ + TestID: "sketch-clear", + Text: ed.T("sketch.clear"), + Label: ed.T("sketch.clear"), + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Disabled: func() bool { + _ = rev.Get() + return ed.SketchMarkCount() == 0 + }, + TextStyle: core.Style{ + FontSize: 12, + FontWeight: 500, + Color: p.TextMuted, + }, + Style: core.Style{ + Height: core.Pt(28), + Padding: core.Symmetric(0, 8), + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.ClearSketch() + }, }, - OnPress: func() { - ed.FinishSketch() + divider(), + ui.Button{ + TestID: "sketch-done", + Text: ed.T("sketch.done"), + Label: ed.T("sketch.done"), + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Color: func() core.Color { return p.TextPrimary }, + TextStyle: core.Style{ + FontSize: 12, + FontWeight: 600, + Color: p.OnTextPrimary, + }, + Style: core.Style{ + Height: core.Pt(28), + Padding: core.Symmetric(0, 12), + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.FinishSketch() + }, }, }, }, - }, - // Active tool hint pill. - core.View{ - TestID: "sketch-tool-hint-pill", - PointerEvents: core.PointerEventsNone, - Style: core.Style{ - Height: core.Pt(22), - Padding: core.Symmetric(0, 8), - CornerRadius: 6, - Background: ui.Alpha(p.PillBg, 0.92), - AlignItems: core.AlignCenter, - JustifyContent: core.JustifyCenter, - }, - Children: []core.Node{ - core.Text{ - TestID: "sketch-tool-hint", - ContentFunc: func() string { - _ = rev.Get() - return ed.SketchTool().Hint() - }, - Style: core.Style{ - FontSize: 11.5, - Color: p.TextMuted, + // Active tool hint pill. + core.View{ + TestID: "sketch-tool-hint-pill", + PointerEvents: core.PointerEventsNone, + Style: core.Style{ + Height: core.Pt(22), + Padding: core.Symmetric(0, 8), + CornerRadius: 6, + Background: ui.Alpha(p.PillBg, 0.92), + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + }, + Children: []core.Node{ + core.Text{ + TestID: "sketch-tool-hint", + ContentFunc: func() string { + _ = rev.Get() + return ed.SketchTool().Hint() + }, + Style: core.Style{ + FontSize: 11.5, + Color: p.TextMuted, + }, }, }, }, - }, - // Selected mark inline label editor (shown whenever a mark is selected, including after Correct a mark). - core.Show{ - When: func() bool { - return selectedMarkKey.Get() > 0 - }, - Then: func(cx *core.Scope) core.Node { - return core.Dynamic(func(cx *core.Scope) core.Node { - num := selectedMarkKey.Get() - m, ok := ed.SketchMarkByNumber(num) - if !ok { - return core.View{} - } - pal := ed.SpecPalette(cx) - return core.View{ - TestID: "sketch-mark-label-bar", - Style: core.Style{ - Direction: core.Row, - AlignItems: core.AlignCenter, - Gap: 8, - Padding: core.Edges{Top: 4, Bottom: 4, Left: 8, Right: 6}, - CornerRadius: 10, - Background: ui.Alpha(pal.Raised, 0.96), - BorderWidth: 1, - BorderColor: pal.Accent.Edge, - }, - Children: []core.Node{ - core.View{ - TestID: "sketch-selected-mark-badge", - Style: core.Style{ - Width: core.Pt(18), - Height: core.Pt(18), - CornerRadius: 9, - Background: pal.Accent.Fg, - AlignItems: core.AlignCenter, - JustifyContent: core.JustifyCenter, - }, - Children: []core.Node{ - core.Text{ - Content: strconv.Itoa(m.Number), - Style: core.Style{ - FontSize: 11, - FontWeight: 600, - Color: pal.Accent.OnFill, + // Selected mark inline label editor (shown whenever a mark is selected, including after Correct a mark). + core.Show{ + When: func() bool { + return selectedMarkKey.Get() > 0 + }, + Then: func(cx *core.Scope) core.Node { + return core.Dynamic(func(cx *core.Scope) core.Node { + num := selectedMarkKey.Get() + m, ok := ed.SketchMarkByNumber(num) + if !ok { + return core.View{} + } + pal := ed.SpecPalette(cx) + return core.View{ + TestID: "sketch-mark-label-bar", + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + Padding: core.Edges{Top: 4, Bottom: 4, Left: 8, Right: 6}, + CornerRadius: 10, + Background: ui.Alpha(pal.Raised, 0.96), + BorderWidth: 1, + BorderColor: pal.Accent.Edge, + }, + Children: []core.Node{ + core.View{ + TestID: "sketch-selected-mark-badge", + Style: core.Style{ + Width: core.Pt(18), + Height: core.Pt(18), + CornerRadius: 9, + Background: pal.Accent.Fg, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + }, + Children: []core.Node{ + core.Text{ + Content: strconv.Itoa(m.Number), + Style: core.Style{ + FontSize: 11, + FontWeight: 600, + Color: pal.Accent.OnFill, + }, }, }, }, - }, - ui.Input{ - TestID: "sketch-mark-label-input", - Label: fmt.Sprintf("Label for mark %d", m.Number), - Placeholder: "Add label (e.g. 3 spikes)...", - Value: func() string { - _ = rev.Get() - if cur, ok := ed.SketchMarkByNumber(num); ok { - return cur.Label - } - return "" - }, - OnChange: func(v string) { - ed.SetSketchMarkLabel(num, v) - }, - Style: core.Style{ - Width: core.Pt(200), - }, - }, - ui.Button{ - TestID: "sketch-mark-delete", - Icon: lucide.Trash, - IconSize: 13, - Label: fmt.Sprintf("Delete mark %d", m.Number), - Size: ui.SizeSmall, - Variant: ui.ButtonGhost, - Side: 26, - Tint: func() core.Color { return pal.TextMuted }, - Style: core.Style{ - CornerRadius: 6, - FocusVisible: pal.FocusRing(2), - }, - OnPress: func() { - ed.DeleteSketchMark(num) + specInputField(cx, ed, ui.Input{ + TestID: "sketch-mark-label-input", + Label: fmt.Sprintf("Label for mark %d", m.Number), + Placeholder: "Add label (e.g. 3 spikes)...", + Value: func() string { + _ = rev.Get() + if cur, ok := ed.SketchMarkByNumber(num); ok { + return cur.Label + } + return "" + }, + OnChange: func(v string) { + ed.SetSketchMarkLabel(num, v) + }, + Style: core.Style{ + Width: core.Pt(200), + }, + }), + ui.Button{ + TestID: "sketch-mark-delete", + Icon: lucide.Trash, + IconSize: 13, + Label: fmt.Sprintf("Delete mark %d", m.Number), + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Side: 26, + Tint: func() core.Color { return pal.TextMuted }, + Style: core.Style{ + CornerRadius: 6, + FocusVisible: pal.FocusRing(2), + }, + OnPress: func() { + ed.DeleteSketchMark(num) + }, }, }, - }, - } - }) + } + }) + }, }, }, - }, - } + } + }) }, } } @@ -365,73 +371,79 @@ func sceneTreeSketchSectionView(cx *core.Scope, ed *Editor, rev *core.Signal[uin _ = rev.Get() return !ed.Playing() && (ed.SketchActive() || ed.SketchMarkCount() > 0) }) + darkMemo := core.NewMemo(cx, func() bool { + _ = rev.Get() + return ed.SpecPalette(cx).Dark + }) return core.Show{ When: shown.Get, Then: func(cx *core.Scope) core.Node { - p := ed.SpecPalette(cx) - return core.View{ - TestID: "scene-tree-sketch-section", - Style: core.Style{ - Padding: core.Edges{Top: 8, Bottom: 4, Left: 4, Right: 4}, - Borders: core.Edges{Top: 1}, - BorderColor: p.Line, - Gap: 4, - }, - Children: []core.Node{ - core.Text{ - Content: "SKETCH LAYER", - Style: core.Style{ - FontSize: 11, - FontWeight: 600, - LetterSpacing: 0.6, - Color: p.TextFaint, - Padding: core.Symmetric(0, 4), - }, + return core.Dynamic(func(cx *core.Scope) core.Node { + p := SpecPaletteFor(darkMemo.Get()) + return core.View{ + TestID: "scene-tree-sketch-section", + Style: core.Style{ + Padding: core.Edges{Top: 8, Bottom: 4, Left: 4, Right: 4}, + Borders: core.Edges{Top: 1}, + BorderColor: p.Line, + Gap: 4, }, - core.View{ - TestID: "scene-tree-sketch-layer", - Role: core.RoleButton, - Label: "Sketch layer", - OnPress: func(core.PressEvent) { - ed.StartSketch() - }, - Style: core.Style{ - Height: core.Pt(28), - Direction: core.Row, - AlignItems: core.AlignCenter, - Gap: 8, - Padding: core.Symmetric(0, 6), - CornerRadius: 6, - FocusVisible: p.FocusRing(-2), + Children: []core.Node{ + core.Text{ + Content: "SKETCH LAYER", + Style: core.Style{ + FontSize: 11, + FontWeight: 600, + LetterSpacing: 0.6, + Color: p.TextFaint, + Padding: core.Symmetric(0, 4), + }, }, - Children: []core.Node{ - core.Text{ - TestID: "scene-tree-sketch-count", - ContentFunc: func() string { - _ = rev.Get() - n := ed.SketchMarkCount() - if n == 1 { - return "1 mark" - } - return fmt.Sprintf("%d marks", n) - }, - Style: core.Style{ - FlexGrow: 1, - FontSize: 12, - Color: p.TextMuted, - }, + core.View{ + TestID: "scene-tree-sketch-layer", + Role: core.RoleButton, + Label: "Sketch layer", + OnPress: func(core.PressEvent) { + ed.StartSketch() }, - core.Text{ - Content: "not saved", - Style: core.Style{ - FontSize: 11, - Color: p.TextFaint, + Style: core.Style{ + Height: core.Pt(28), + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + Padding: core.Symmetric(0, 6), + CornerRadius: 6, + FocusVisible: p.FocusRing(-2), + }, + Children: []core.Node{ + core.Text{ + TestID: "scene-tree-sketch-count", + ContentFunc: func() string { + _ = rev.Get() + n := ed.SketchMarkCount() + if n == 1 { + return "1 mark" + } + return fmt.Sprintf("%d marks", n) + }, + Style: core.Style{ + FlexGrow: 1, + FontSize: 12, + Color: p.TextMuted, + }, + }, + core.Text{ + Content: "not saved", + Style: core.Style{ + FontSize: 11, + Color: p.TextFaint, + }, }, }, }, }, - }, - } + } + }) }, } } @@ -493,246 +505,253 @@ func SketchPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core. } }) - p := ed.SpecPalette(cx) - return core.View{ - TestID: "sketch-agent-panel", - Role: core.RoleRegion, - Label: "Agent Sketch", - Style: core.Style{ - Width: core.Pt(360), - FlexShrink: 0, - Background: p.Panel, - Borders: core.Edges{Left: 1}, - BorderColor: p.Line, - Overflow: core.Hidden, - }, - Children: []core.Node{ - // Panel Header ("Agent" + MCP dot + Inspector toggle). - core.View{ - Style: core.Style{ - Height: core.Pt(44), - FlexShrink: 0, - Direction: core.Row, - AlignItems: core.AlignCenter, - Gap: 8, - Padding: core.Edges{Left: 16, Right: 8}, - Borders: core.Edges{Bottom: 1}, - BorderColor: p.Line, - }, - Children: []core.Node{ - core.Text{ - Content: "Agent", - Style: core.Style{ - FontSize: 13, - FontWeight: 600, - Color: p.TextPrimary, - FlexGrow: 1, - }, + darkMemo := core.NewMemo(cx, func() bool { + _ = rev.Get() + return ed.SpecPalette(cx).Dark + }) + + return core.Dynamic(func(cx *core.Scope) core.Node { + p := SpecPaletteFor(darkMemo.Get()) + return core.View{ + TestID: "sketch-agent-panel", + Role: core.RoleRegion, + Label: "Agent Sketch", + Style: core.Style{ + Width: core.Pt(360), + FlexShrink: 0, + Background: p.Panel, + Borders: core.Edges{Left: 1}, + BorderColor: p.Line, + Overflow: core.Hidden, + }, + Children: []core.Node{ + // Panel Header ("Agent" + MCP dot + Inspector toggle). + core.View{ + Style: core.Style{ + Height: core.Pt(44), + FlexShrink: 0, + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + Padding: core.Edges{Left: 16, Right: 8}, + Borders: core.Edges{Bottom: 1}, + BorderColor: p.Line, }, - core.View{ - Style: core.Style{ - Direction: core.Row, - AlignItems: core.AlignCenter, - Gap: 6, - Padding: core.Symmetric(0, 6), + Children: []core.Node{ + core.Text{ + Content: "Agent", + Style: core.Style{ + FontSize: 13, + FontWeight: 600, + Color: p.TextPrimary, + FlexGrow: 1, + }, }, - Children: []core.Node{ - core.View{ - Style: core.Style{ - Width: core.Pt(6), - Height: core.Pt(6), - CornerRadius: 3, - Background: p.Added.Fg, - }, + core.View{ + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 6, + Padding: core.Symmetric(0, 6), }, - core.Text{ - Content: "MCP", - Style: core.Style{ - FontSize: 11.5, - Color: p.TextFaint, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(6), + Height: core.Pt(6), + CornerRadius: 3, + Background: p.Added.Fg, + }, + }, + core.Text{ + Content: "MCP", + Style: core.Style{ + FontSize: 11.5, + Color: p.TextFaint, + }, }, }, }, - }, - ui.Button{ - TestID: "sketch-panel-close", - Icon: lucide.X, - Label: "Show Inspector", - Size: ui.SizeSmall, - Variant: ui.ButtonGhost, - Side: 28, - Tint: func() core.Color { return p.TextMuted }, - Style: core.Style{ - CornerRadius: 6, - FocusVisible: p.FocusRing(2), - }, - OnPress: func() { - ed.SetSketchPanelOpen(false) + ui.Button{ + TestID: "sketch-panel-close", + Icon: lucide.X, + Label: "Show Inspector", + Size: ui.SizeSmall, + Variant: ui.ButtonGhost, + Side: 28, + Tint: func() core.Color { return p.TextMuted }, + Style: core.Style{ + CornerRadius: 6, + FocusVisible: p.FocusRing(2), + }, + OnPress: func() { + ed.SetSketchPanelOpen(false) + }, }, }, }, - }, - - // Scrollable body: Review card / Reading card / Marks list. - ui.ScrollView{ - Style: core.Style{ - FlexGrow: 1, - FlexBasis: core.Pt(0), - }, - Children: []core.Node{ - core.Dynamic(func(cx *core.Scope) core.Node { - _ = stateKey.Get() - pal := ed.SpecPalette(cx) - var items []core.Node - // 1. Post-sketch Review card (Sketch overlay toggle + Keep / Revert). - if ed.SketchReviewOpen() { - items = append(items, sketchReviewCardView(ed, pal)) - } + // Scrollable body: Review card / Reading card / Marks list. + ui.ScrollView{ + Style: core.Style{ + FlexGrow: 1, + FlexBasis: core.Pt(0), + }, + Children: []core.Node{ + core.Dynamic(func(cx *core.Scope) core.Node { + _ = stateKey.Get() + pal := ed.SpecPalette(cx) + var items []core.Node - // 2. Agent Reading card ("I read your sketch as:" + assumptions + Go ahead / Correct a mark). - if rd := ed.SketchReading(); rd != nil { - items = append(items, sketchReadingCardView(ed, pal, rd)) - } else if ed.SketchHoldState() == SketchHoldPending { - items = append(items, core.View{ - TestID: "sketch-waiting-reading", - Style: core.Style{ - CornerRadius: 12, - Background: pal.Warning.Fill, - BorderWidth: 1, - BorderColor: pal.Warning.Edge, - Padding: core.Symmetric(10, 12), - Gap: 4, - }, - Children: []core.Node{ - core.Text{ - Content: "Waiting for the agent to read your sketch", - Style: core.Style{FontSize: 12, FontWeight: 600, Color: pal.Warning.Fg}, - }, - core.Text{ - Content: "Scene edits are held until the agent restates each mark and you choose Go ahead.", - Style: core.Style{FontSize: 11.5, Color: pal.TextSecondary}, - }, - }, - }) - } + // 1. Post-sketch Review card (Sketch overlay toggle + Keep / Revert). + if ed.SketchReviewOpen() { + items = append(items, sketchReviewCardView(ed, pal)) + } - // 3. Active marks list when not in review and no reading card. - marks := ed.SketchMarks() - if len(marks) > 0 && !ed.SketchReviewOpen() && ed.SketchReading() == nil { - sel := ed.SelectedSketchMark() - rows := make([]core.Node, 0, len(marks)) - for _, mk := range marks { - m := mk - isSel := m.Number == sel - rowBg := pal.Raised - rowBorder := pal.LineRaised - if isSel { - rowBorder = pal.Accent.Edge - } - rows = append(rows, core.View{ - TestID: fmt.Sprintf("sketch-panel-mark-%d", m.Number), - Role: core.RoleButton, - Label: fmt.Sprintf("Mark %d %s", m.Number, m.Kind.String()), - OnPress: func(core.PressEvent) { - ed.SelectSketchMark(m.Number) - if !ed.SketchActive() { - ed.StartSketch() - } - }, + // 2. Agent Reading card ("I read your sketch as:" + assumptions + Go ahead / Correct a mark). + if rd := ed.SketchReading(); rd != nil { + items = append(items, sketchReadingCardView(ed, pal, rd)) + } else if ed.SketchHoldState() == SketchHoldPending { + items = append(items, core.View{ + TestID: "sketch-waiting-reading", Style: core.Style{ - Direction: core.Row, - AlignItems: core.AlignCenter, - Gap: 8, - Padding: core.Symmetric(8, 10), - CornerRadius: 8, - Background: rowBg, + CornerRadius: 12, + Background: pal.Warning.Fill, BorderWidth: 1, - BorderColor: rowBorder, - FocusVisible: pal.FocusRing(-2), + BorderColor: pal.Warning.Edge, + Padding: core.Symmetric(10, 12), + Gap: 4, }, Children: []core.Node{ - core.View{ - Style: core.Style{ - Width: core.Pt(18), - Height: core.Pt(18), - FlexShrink: 0, - CornerRadius: 9, - Background: pal.TextPrimary, - AlignItems: core.AlignCenter, - JustifyContent: core.JustifyCenter, - }, - Children: []core.Node{ - core.Text{ - Content: strconv.Itoa(m.Number), - Style: core.Style{FontSize: 11, FontWeight: 600, Color: pal.OnTextPrimary}, - }, - }, + core.Text{ + Content: "Waiting for the agent to read your sketch", + Style: core.Style{FontSize: 12, FontWeight: 600, Color: pal.Warning.Fg}, + }, + core.Text{ + Content: "Scene edits are held until the agent restates each mark and you choose Go ahead.", + Style: core.Style{FontSize: 11.5, Color: pal.TextSecondary}, + }, + }, + }) + } + + // 3. Active marks list when not in review and no reading card. + marks := ed.SketchMarks() + if len(marks) > 0 && !ed.SketchReviewOpen() && ed.SketchReading() == nil { + sel := ed.SelectedSketchMark() + rows := make([]core.Node, 0, len(marks)) + for _, mk := range marks { + m := mk + isSel := m.Number == sel + rowBg := pal.Raised + rowBorder := pal.LineRaised + if isSel { + rowBorder = pal.Accent.Edge + } + rows = append(rows, core.View{ + TestID: fmt.Sprintf("sketch-panel-mark-%d", m.Number), + Role: core.RoleButton, + Label: fmt.Sprintf("Mark %d %s", m.Number, m.Kind.String()), + OnPress: func(core.PressEvent) { + ed.SelectSketchMark(m.Number) + if !ed.SketchActive() { + ed.StartSketch() + } + }, + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + Padding: core.Symmetric(8, 10), + CornerRadius: 8, + Background: rowBg, + BorderWidth: 1, + BorderColor: rowBorder, + FocusVisible: pal.FocusRing(-2), }, - core.View{ - Style: core.Style{FlexGrow: 1, FlexBasis: core.Pt(0), Gap: 2}, - Children: []core.Node{ - core.Text{ - Content: m.GeometrySummary(), - Style: core.Style{ - FontFamily: core.FontMonospace, - FontSize: 11.5, - Color: pal.TextMuted, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(18), + Height: core.Pt(18), + FlexShrink: 0, + CornerRadius: 9, + Background: pal.TextPrimary, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + }, + Children: []core.Node{ + core.Text{ + Content: strconv.Itoa(m.Number), + Style: core.Style{FontSize: 11, FontWeight: 600, Color: pal.OnTextPrimary}, }, }, - core.Show{ - When: func() bool { return m.Label != "" }, - Then: func(cx *core.Scope) core.Node { - return core.Text{ - Content: fmt.Sprintf("“%s”", m.Label), - Style: core.Style{FontSize: 11.5, Color: pal.TextSecondary}, - } + }, + core.View{ + Style: core.Style{FlexGrow: 1, FlexBasis: core.Pt(0), Gap: 2}, + Children: []core.Node{ + core.Text{ + Content: m.GeometrySummary(), + Style: core.Style{ + FontFamily: core.FontMonospace, + FontSize: 11.5, + Color: pal.TextMuted, + }, + }, + core.Show{ + When: func() bool { return m.Label != "" }, + Then: func(cx *core.Scope) core.Node { + return core.Text{ + Content: fmt.Sprintf("“%s”", m.Label), + Style: core.Style{FontSize: 11.5, Color: pal.TextSecondary}, + } + }, }, }, }, }, - }, + }) + } + items = append(items, core.View{ + TestID: "sketch-panel-marks-list", + Style: core.Style{Gap: 6}, + Children: rows, }) } - items = append(items, core.View{ - TestID: "sketch-panel-marks-list", - Style: core.Style{Gap: 6}, - Children: rows, - }) - } - // 4. "Sent with this request" scene-coordinates preview card. - if ed.SketchPreviewOpen() { - items = append(items, sketchPreviewCardView(ed, pal)) - } + // 4. "Sent with this request" scene-coordinates preview card. + if ed.SketchPreviewOpen() { + items = append(items, sketchPreviewCardView(ed, pal)) + } - if len(items) == 0 { - items = append(items, core.Text{ - TestID: "sketch-panel-empty", - Content: "Draw on the viewport with Pen, Arrow, Box or Text. Marks stay in scene coordinates and are never written to the scene file.", + if len(items) == 0 { + items = append(items, core.Text{ + TestID: "sketch-panel-empty", + Content: "Draw on the viewport with Pen, Arrow, Box or Text. Marks stay in scene coordinates and are never written to the scene file.", + Style: core.Style{ + FontSize: 12, + LineHeight: 18, + Color: pal.TextFaint, + }, + }) + } + + return core.View{ Style: core.Style{ - FontSize: 12, - LineHeight: 18, - Color: pal.TextFaint, + Padding: core.All(12), + Gap: 12, }, - }) - } - - return core.View{ - Style: core.Style{ - Padding: core.All(12), - Gap: 12, - }, - Children: items, - } - }), + Children: items, + } + }), + }, }, - }, - // Composer footer with "Sketch · N marks" chip and Send button. - sketchComposerView(cx, ed, rev), - }, - } + // Composer footer with "Sketch · N marks" chip and Send button. + sketchComposerView(cx, ed, rev, p), + }, + } + }) } func sketchReadingCardView(ed *Editor, p SpecPalette, rd *SketchReading) core.Node { @@ -1192,15 +1211,14 @@ func sketchPreviewCardView(ed *Editor, p SpecPalette) core.Node { } } -func sketchComposerView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { - p := ed.SpecPalette(cx) +func sketchComposerView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], p SpecPalette) core.Node { submit := func() { text := strings.TrimSpace(ed.SketchPromptDraft()) if ed.SketchHoldState() == SketchHoldReading && text != "" { ed.report(ed.ReplyToSketchReading(text)) return } - if ed.SketchMarkCount() > 0 { + if ed.SketchAttached() && ed.SketchMarkCount() > 0 { if _, err := ed.SendSketch(text); err != nil { ed.report(err) } @@ -1309,7 +1327,7 @@ func sketchComposerView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) co } }, }, - ui.Input{ + specInputField(cx, ed, ui.Input{ TestID: "sketch-composer-input", Label: "Ask the agent", Placeholder: "Build what I sketched...", @@ -1323,7 +1341,7 @@ func sketchComposerView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) co OnSubmit: func(string) { submit() }, - }, + }), core.View{ Style: core.Style{ Direction: core.Row, @@ -1375,7 +1393,7 @@ func sketchComposerView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) co if ed.SketchHoldState() == SketchHoldReading { return strings.TrimSpace(ed.SketchPromptDraft()) == "" } - return ed.SketchMarkCount() == 0 + return !ed.SketchAttached() || ed.SketchMarkCount() == 0 }, Color: func() core.Color { return p.TextPrimary }, Tint: func() core.Color { return p.OnTextPrimary }, diff --git a/packages/game/editor/tile_review_ui.go b/packages/game/editor/tile_review_ui.go index 3b519ba6b..5f73677ae 100644 --- a/packages/game/editor/tile_review_ui.go +++ b/packages/game/editor/tile_review_ui.go @@ -435,9 +435,10 @@ func tileReviewPanel(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core. }, StyleFunc: func() core.Style { _ = rev.Get() + p := ed.SpecPalette(cx) bg := core.Transparent if ed.SketchReviewOverlayVisible() { - bg = specLineRaised + bg = p.LineRaised } return core.Style{ Height: core.Pt(24), @@ -446,7 +447,7 @@ func tileReviewPanel(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core. Background: bg, AlignItems: core.AlignCenter, JustifyContent: core.JustifyCenter, - FocusVisible: specFocusRingStyle, + FocusVisible: p.FocusRing(2), } }, Children: []core.Node{ @@ -454,9 +455,10 @@ func tileReviewPanel(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core. Content: "Sketch overlay", StyleFunc: func() core.Style { _ = rev.Get() - col := specTextSecondary + p := ed.SpecPalette(cx) + col := p.TextMuted if ed.SketchReviewOverlayVisible() { - col = specTextStrong + col = p.TextPrimary } return core.Style{FontSize: 11, FontWeight: 500, Color: col} }, From d42db094173c876de7c1b41d8f04655be3c40498 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Thu, 26 Nov 2026 18:14:38 +0900 Subject: [PATCH 3/5] fix(editor): harden sketch autosave review pause, History sync/preview guards, label spaces, and modal/drag safety --- packages/game/editor/autosave.go | 3 + packages/game/editor/play.go | 1 + packages/game/editor/sketch.go | 90 ++++++++++++++---- packages/game/editor/sketch_test.go | 141 ++++++++++++++++++++++++++++ packages/game/editor/sketch_ui.go | 30 ++++-- packages/game/editor/state.go | 1 + 6 files changed, 242 insertions(+), 24 deletions(-) diff --git a/packages/game/editor/autosave.go b/packages/game/editor/autosave.go index c863f9275..412b3ed21 100644 --- a/packages/game/editor/autosave.go +++ b/packages/game/editor/autosave.go @@ -240,6 +240,9 @@ func (e *Editor) HasOpenReview() bool { if e.DataTableReviewPending() { return true } + if e.SketchReviewOpen() { + return true + } if e.playtest.session != nil && e.playtest.session.ReviewProposalID != "" { return true } diff --git a/packages/game/editor/play.go b/packages/game/editor/play.go index a0fe6b24e..2994a0a55 100644 --- a/packages/game/editor/play.go +++ b/packages/game/editor/play.go @@ -284,6 +284,7 @@ func (e *Editor) startPlaySession(cx *core.Scope, playback *replay.Recording, st e.CancelInspectorScrub() e.CancelShapeDrag2D() e.CancelPluginDrag2D() + e.CancelSketchDrag() e.CancelAssetDrag() e.stopAssetPreviewLoop() e.assetDrawer.previewPlaying = false diff --git a/packages/game/editor/sketch.go b/packages/game/editor/sketch.go index 6394ebffc..4aa94eb9c 100644 --- a/packages/game/editor/sketch.go +++ b/packages/game/editor/sketch.go @@ -344,6 +344,23 @@ func clampSketchRunes(s string, maxRunes int) string { return s } +// clampSketchLabelInput preserves leading/trailing spaces while the user is actively typing in the +// controlled mark-label input (stripping only newlines and clamping total runes). +func clampSketchLabelInput(s string, maxRunes int) string { + s = strings.NewReplacer("\r", " ", "\n", " ").Replace(s) + if maxRunes <= 0 || len(s) <= maxRunes { + return s + } + n := 0 + for i := range s { + if n == maxRunes { + return s[:i] + } + n++ + } + return s +} + func (e *Editor) resetSketchForProject() { if e == nil { return @@ -356,6 +373,8 @@ func (e *Editor) sketchBlockedByScreen() bool { return true } return e.playing || + e.HistoryPreviewActive() || + e.PermissionsDraftOpen() || e.StartScreenOpen() || e.SettingsOpen() || e.MergeConflictOpen() || @@ -445,7 +464,7 @@ func (e *Editor) renumberSketchMarks() { // SketchActive reports whether viewport sketch drawing mode is currently active. func (e *Editor) SketchActive() bool { - return e != nil && e.sketch.active && e.ViewMode == ViewMode2D && !e.playing + return e != nil && e.sketch.active && e.ViewMode == ViewMode2D && !e.playing && !e.HistoryPreviewActive() } // SetSketchActive turns viewport sketch drawing mode on or off. @@ -537,7 +556,7 @@ func (e *Editor) SketchTool() SketchTool { // SetSketchTool switches the active sketch tool and ensures sketch mode is active. func (e *Editor) SetSketchTool(tool SketchTool) { - if e == nil || !tool.Valid() || e.playing { + if e == nil || !tool.Valid() || e.playing || e.HistoryPreviewActive() { return } e.sketch.tool = tool @@ -755,7 +774,7 @@ func (e *Editor) appendSketchMark(m SketchMark) SketchMark { // AddSketchBox adds a numbered Box mark strictly in scene coordinates without mutating SceneDoc or History. func (e *Editor) AddSketchBox(x, y, width, height float32, label string) SketchMark { - if e == nil || e.playing { + if e == nil || e.playing || e.HistoryPreviewActive() { return SketchMark{} } if !isFiniteFloat32(x) || !isFiniteFloat32(y) || !isFiniteFloat32(width) || !isFiniteFloat32(height) { @@ -782,7 +801,7 @@ func (e *Editor) AddSketchBox(x, y, width, height float32, label string) SketchM // AddSketchArrow adds a numbered Arrow mark strictly in scene coordinates without mutating SceneDoc or History. func (e *Editor) AddSketchArrow(x0, y0, x1, y1 float32, label string) SketchMark { - if e == nil || e.playing { + if e == nil || e.playing || e.HistoryPreviewActive() { return SketchMark{} } if !isFiniteFloat32(x0) || !isFiniteFloat32(y0) || !isFiniteFloat32(x1) || !isFiniteFloat32(y1) { @@ -800,7 +819,7 @@ func (e *Editor) AddSketchArrow(x0, y0, x1, y1 float32, label string) SketchMark // AddSketchPen adds a numbered Pen polyline mark strictly in scene coordinates without mutating SceneDoc or History. func (e *Editor) AddSketchPen(points []SketchPoint, label string) SketchMark { - if e == nil || e.playing || len(points) == 0 { + if e == nil || e.playing || e.HistoryPreviewActive() || len(points) == 0 { return SketchMark{} } clean := make([]SketchPoint, 0, min(len(points), maxSketchPenPoints)) @@ -824,7 +843,7 @@ func (e *Editor) AddSketchPen(points []SketchPoint, label string) SketchMark { // AddSketchText adds a numbered Text mark strictly in scene coordinates without mutating SceneDoc or History. func (e *Editor) AddSketchText(x, y float32, label string) SketchMark { - if e == nil || e.playing { + if e == nil || e.playing || e.HistoryPreviewActive() { return SketchMark{} } if !isFiniteFloat32(x) || !isFiniteFloat32(y) { @@ -841,7 +860,7 @@ func (e *Editor) AddSketchText(x, y float32, label string) SketchMark { // AddSketchMarkAtCursor places a new mark using the active sketch tool at the current pointer or view center // in scene coordinates, providing a full keyboard path for creating marks without pointer dragging. func (e *Editor) AddSketchMarkAtCursor(label string) SketchMark { - if e == nil || e.playing { + if e == nil || e.playing || e.HistoryPreviewActive() { return SketchMark{} } tool := e.ensureSketchTool() @@ -866,10 +885,10 @@ func (e *Editor) AddSketchMarkAtCursor(label string) SketchMark { // SetSketchMarkLabel updates the optional text label on the 1-based sketch mark. func (e *Editor) SetSketchMarkLabel(number int, label string) bool { - if e == nil || e.playing || number < 1 || number > len(e.sketch.marks) { + if e == nil || e.playing || e.HistoryPreviewActive() || number < 1 || number > len(e.sketch.marks) { return false } - clean := clampSketchRunes(label, maxSketchLabelRunes) + clean := clampSketchLabelInput(label, maxSketchLabelRunes) if e.sketch.marks[number-1].Label == clean { return true } @@ -880,7 +899,7 @@ func (e *Editor) SetSketchMarkLabel(number int, label string) bool { // NudgeSelectedSketchMark translates the selected sketch mark by (dx, dy) in scene coordinates. func (e *Editor) NudgeSelectedSketchMark(dx, dy float32) bool { - if e == nil || e.playing || !isFiniteFloat32(dx) || !isFiniteFloat32(dy) || (dx == 0 && dy == 0) { + if e == nil || e.playing || e.HistoryPreviewActive() || !isFiniteFloat32(dx) || !isFiniteFloat32(dy) || (dx == 0 && dy == 0) { return false } sel := e.SelectedSketchMark() @@ -920,10 +939,11 @@ func (e *Editor) NudgeSelectedSketchMark(dx, dy float32) bool { // DeleteSketchMark removes the 1-based mark and renumbers remaining marks sequentially. func (e *Editor) DeleteSketchMark(number int) bool { - if e == nil || e.playing || number < 1 || number > len(e.sketch.marks) { + if e == nil || e.playing || e.HistoryPreviewActive() || number < 1 || number > len(e.sketch.marks) { return false } e.pushSketchUndo() + e.sketch.draft = nil e.sketch.marks = slices.Delete(e.sketch.marks, number-1, number) e.renumberSketchMarks() e.notify() @@ -937,11 +957,12 @@ func (e *Editor) CanUndoSketchMark() bool { // UndoLastSketchMark restores the previous sketch mark list without touching SceneDoc or Editor.History. func (e *Editor) UndoLastSketchMark() bool { - if e == nil || e.playing || len(e.sketch.undoStack) == 0 { + if e == nil || e.playing || e.HistoryPreviewActive() || len(e.sketch.undoStack) == 0 { return false } prev := e.sketch.undoStack[len(e.sketch.undoStack)-1] e.sketch.undoStack = e.sketch.undoStack[:len(e.sketch.undoStack)-1] + e.sketch.draft = nil e.sketch.marks = prev e.renumberSketchMarks() e.notify() @@ -951,7 +972,7 @@ func (e *Editor) UndoLastSketchMark() bool { // ClearSketch clears all sketch marks, any pending reading card, and any active confirmation hold. // It never modifies SceneDoc or Editor.History. func (e *Editor) ClearSketch() { - if e == nil || e.playing { + if e == nil || e.playing || e.HistoryPreviewActive() { return } if len(e.sketch.marks) > 0 { @@ -1065,7 +1086,7 @@ func (e *Editor) EndSketchDrag() (SketchMark, bool) { dr := e.sketch.draft e.sketch.draft = nil - if !dr.moved && dr.hitMark > 0 { + if !dr.moved && dr.hitMark > 0 && dr.hitMark <= len(e.sketch.marks) { e.sketch.selectedMark = dr.hitMark e.notify() return e.sketch.marks[dr.hitMark-1].Clone(), false @@ -1177,9 +1198,15 @@ func (e *Editor) SendSketch(prompt string) (SketchAgentRequest, error) { if e.playing { return SketchAgentRequest{}, ErrPlaying } + if e.HistoryPreviewActive() { + return SketchAgentRequest{}, ErrHistoryPreview + } if len(e.sketch.marks) == 0 || !e.sketch.attached { return SketchAgentRequest{}, ErrSketchEmpty } + for i := range e.sketch.marks { + e.sketch.marks[i].Label = clampSketchRunes(e.sketch.marks[i].Label, maxSketchLabelRunes) + } if strings.TrimSpace(prompt) == "" { prompt = strings.TrimSpace(e.sketch.promptDraft) } else { @@ -1277,6 +1304,9 @@ func (e *Editor) PostSketchReading(reading SketchReading) error { if e.playing { return ErrPlaying } + if e.HistoryPreviewActive() { + return ErrHistoryPreview + } if len(e.sketch.marks) == 0 { return ErrSketchEmpty } @@ -1341,6 +1371,9 @@ func (e *Editor) ApproveSketchReading() error { if e.playing { return ErrPlaying } + if e.HistoryPreviewActive() { + return ErrHistoryPreview + } if len(e.sketch.marks) == 0 { return ErrSketchEmpty } @@ -1381,6 +1414,9 @@ func (e *Editor) CorrectSketchMark(number int) error { if e.playing { return ErrPlaying } + if e.HistoryPreviewActive() { + return ErrHistoryPreview + } if len(e.sketch.marks) == 0 { return ErrSketchEmpty } @@ -1416,6 +1452,9 @@ func (e *Editor) ReplyToSketchReading(message string) error { if e.playing { return ErrPlaying } + if e.HistoryPreviewActive() { + return ErrHistoryPreview + } msg := strings.TrimSpace(message) if msg == "" { return errors.New("editor: reply message cannot be empty") @@ -1543,6 +1582,7 @@ func (e *Editor) RecordSketchReviewEdits(label string, addedIDs, changedIDs, rem } e.sketch.panelOpen = true e.sketch.panelDismissed = false + e.cancelAutoSaveTimer() e.notify() } @@ -1555,6 +1595,9 @@ func (e *Editor) KeepSketchReview() error { if e.playing { return ErrPlaying } + if e.HistoryPreviewActive() { + return ErrHistoryPreview + } if !e.SketchReviewOpen() { return ErrNoSketchReview } @@ -1562,6 +1605,7 @@ func (e *Editor) KeepSketchReview() error { e.sketch.review = nil e.clearSketchOnReviewKeep() e.Status = fmt.Sprintf("Kept %d agent changes · sketch cleared", count) + e.scheduleAutoSaveIfNeeded() e.notify() return nil } @@ -1575,17 +1619,24 @@ func (e *Editor) RevertSketchReview() error { if e.playing { return ErrPlaying } + if e.HistoryPreviewActive() { + return ErrHistoryPreview + } if !e.SketchReviewOpen() { return ErrNoSketchReview } rv := e.sketch.review - e.sketch.review = nil if len(rv.baseYAML) > 0 { - doc, err := sceneformat.ParseWith(rv.baseYAML, sceneformat.ParseOptions{Components: e.ComponentRegistry()}) + doc, err := sceneformat.ParseWith(rv.baseYAML, sceneformat.ParseOptions{ + File: e.FilePath, + Components: e.ComponentRegistry(), + PhysicsLayers: e.PhysicsLayers(), + }) if err != nil { return fmt.Errorf("editor: revert sketch review: %w", err) } + e.sketch.review = nil e.Doc = doc if e.History != nil && rv.historyStart >= 0 { cut := min(rv.historyStart, len(e.History.commands)) @@ -1594,6 +1645,8 @@ func (e *Editor) RevertSketchReview() error { if e.History.cursor > cut { e.History.cursor = cut } + e.History.truncateRecordsAfterCommand(cut) + e.History.syncUndoFlags() } e.Rebuild() // Drop any selection IDs that pointed at agent-added objects removed by Revert. @@ -1614,9 +1667,12 @@ func (e *Editor) RevertSketchReview() error { e.SelectedID = kept[len(kept)-1] } } + } else { + e.sketch.review = nil } e.keepSketchOnReviewRevert() e.Status = "Reverted agent changes · sketch kept to send again" + e.scheduleAutoSaveIfNeeded() e.notify() return nil } @@ -1660,7 +1716,7 @@ func (e *Editor) keepSketchOnReviewRevert() { // drawSketchOverlay renders the viewport sketch layer (strokes, numbered badges, labels, in-progress drag preview, // and review comparison outlines) in canvas coordinates projected from scene coordinates via WorldToCanvas. func (e *Editor) drawSketchOverlay(d *core.Drawing) { - if e == nil || d == nil || e.playing || e.ViewMode != ViewMode2D { + if e == nil || d == nil || e.playing || e.ViewMode != ViewMode2D || e.HistoryPreviewActive() { return } spec := e.SpecPalette(nil) diff --git a/packages/game/editor/sketch_test.go b/packages/game/editor/sketch_test.go index 5b9f95e68..41ac1ad10 100644 --- a/packages/game/editor/sketch_test.go +++ b/packages/game/editor/sketch_test.go @@ -741,3 +741,144 @@ func TestSketchPanelCloseSpecLightTypingAndRevertSelection(t *testing.T) { t.Fatalf("SelectedID = %q after RevertSketchReview removed object, want empty", ed.SelectedID) } } + +func TestSketchAutoSavePauseHistorySyncPreviewGuardsAndLabelSpaces(t *testing.T) { + ed := newSketchTestEditor(t) + ed.SetCanvasSize(640, 360) + + // 1. Typing spaces into SetSketchMarkLabel must preserve spaces interactively; SendSketch trims cleanly. + mk := ed.AddSketchBox(100, 120, 80, 32, "") + if !ed.SetSketchMarkLabel(mk.Number, "3 ") { + t.Fatal("SetSketchMarkLabel(\"3 \") failed") + } + got, ok := ed.SketchMarkByNumber(mk.Number) + if !ok || got.Label != "3 " { + t.Fatalf("label after typing trailing space = %q, want %q", got.Label, "3 ") + } + if !ed.SetSketchMarkLabel(mk.Number, "3 spikes ") { + t.Fatal("SetSketchMarkLabel(\"3 spikes \") failed") + } + req, err := ed.SendSketch("build spikes") + if err != nil { + t.Fatalf("SendSketch: %v", err) + } + if len(req.Marks) != 1 || req.Marks[0].Label != "3 spikes" { + t.Fatalf("sent mark label = %q, want trimmed %q", req.Marks[0].Label, "3 spikes") + } + + // 2. EndSketchDrag must not panic if marks are deleted mid-drag, and SetViewMode(3D) cancels drag. + ed.StartSketch() + ed.SetSketchTool(editor.SketchToolArrow) + bx, by := ed.WorldToCanvas(100, 120) + if !ed.BeginSketchDrag(bx-10, by-12) { + t.Fatal("BeginSketchDrag on badge returned false") + } + if !ed.SketchDragging() { + t.Fatal("expected SketchDragging() == true") + } + ed.DeleteSketchMark(1) + ed.EndSketchDrag() // must not panic even though hitMark was 1 + ed.AddSketchBox(100, 120, 80, 32, "spikes") + ed.StartSketch() + ed.BeginSketchDrag(200, 200) + ed.SetViewMode(editor.ViewMode3D) + if ed.SketchDragging() { + t.Fatal("SetViewMode(ViewMode3D) did not cancel active sketch drag") + } + ed.SetViewMode(editor.ViewMode2D) + + // 3. HasOpenReview pauses autosave during SketchReviewOpen, and RevertSketchReview trims History entries. + if err := ed.MoveObject("floor", 325, 320); err != nil { + t.Fatalf("MoveObject baseline: %v", err) + } + baseEntries := len(ed.HistoryEntries()) + if baseEntries == 0 { + t.Fatal("expected at least 1 baseline history entry") + } + if _, err := ed.SendSketch("add spikes"); err != nil { + t.Fatalf("SendSketch 2: %v", err) + } + if err := ed.ApproveSketchReading(); err != nil { + t.Fatalf("ApproveSketchReading: %v", err) + } + addedID, err := ed.PlaceObject("Actors", sceneformat.ObjectDoc{ID: "ghost_spikes", Name: "ghost_spikes", X: 140, Y: 136}) + if err != nil { + t.Fatalf("PlaceObject: %v", err) + } + ed.RecordSketchReviewEdits("Agent: add ghost_spikes", []string{addedID}, nil, nil) + if !ed.HasOpenReview() { + t.Fatal("HasOpenReview() = false while SketchReviewOpen() is true; autosave would persist unkept agent edits") + } + if len(ed.HistoryEntries()) <= baseEntries { + t.Fatalf("expected agent edit to append history entry: got %d, base %d", len(ed.HistoryEntries()), baseEntries) + } + if err := ed.RevertSketchReview(); err != nil { + t.Fatalf("RevertSketchReview: %v", err) + } + if ed.HasOpenReview() { + t.Fatal("HasOpenReview() remained true after RevertSketchReview") + } + if gotEntries := len(ed.HistoryEntries()); gotEntries != baseEntries { + t.Fatalf("RevertSketchReview left ghost history entries: got %d, want %d", gotEntries, baseEntries) + } + + // 4. Read-only History preview guards SketchActive and all sketch mutators. + firstEntryID := ed.HistoryEntries()[0].ID + if err := ed.PreviewHistoryEntry(firstEntryID); err != nil { + t.Fatalf("PreviewHistoryEntry: %v", err) + } + if !ed.HistoryPreviewActive() { + t.Fatal("expected HistoryPreviewActive() == true") + } + ed.SetSketchActive(true) + if ed.SketchActive() { + t.Fatal("SketchActive() must be false while HistoryPreviewActive() is true") + } + if m := ed.AddSketchBox(10, 10, 20, 20, "blocked"); m.Number != 0 { + t.Fatalf("AddSketchBox succeeded during HistoryPreviewActive: %+v", m) + } + if _, err := ed.SendSketch("blocked"); !errors.Is(err, editor.ErrHistoryPreview) { + t.Fatalf("SendSketch during HistoryPreview = %v, want ErrHistoryPreview", err) + } + if err := ed.ApproveSketchReading(); !errors.Is(err, editor.ErrHistoryPreview) { + t.Fatalf("ApproveSketchReading during HistoryPreview = %v, want ErrHistoryPreview", err) + } + if err := ed.CorrectSketchMark(1); !errors.Is(err, editor.ErrHistoryPreview) { + t.Fatalf("CorrectSketchMark during HistoryPreview = %v, want ErrHistoryPreview", err) + } + if err := ed.ReplyToSketchReading("ok"); !errors.Is(err, editor.ErrHistoryPreview) { + t.Fatalf("ReplyToSketchReading during HistoryPreview = %v, want ErrHistoryPreview", err) + } + ed.ExitHistoryPreview() + + // 5. You-only PermissionsDraftOpen blocks sketch shortcut commands (including mod+enter). + if _, err := ed.SendSketch("build spikes"); err != nil { + t.Fatalf("SendSketch 3: %v", err) + } + if err := ed.PostSketchReading(editor.SketchReading{ + Items: []editor.SketchReadingItem{{Number: 1, Text: "Add spikes"}}, + }); err != nil { + t.Fatalf("PostSketchReading: %v", err) + } + if _, err := ed.SubmitPermissionsDraft(editor.PermissionsDraftRequest{ + Request: "allow scenes", + Rules: []editor.PermissionsDraftRuleSpec{ + {Action: editor.PermissionActionEdit, Patterns: []string{"scenes/**"}, Decision: editor.PermissionAllow}, + }, + }); err != nil { + t.Fatalf("SubmitPermissionsDraft: %v", err) + } + if !ed.PermissionsDraftOpen() { + t.Fatal("expected PermissionsDraftOpen() == true") + } + for _, cmdID := range []string{editor.CmdSketchToggle, editor.CmdSketchApproveReading, editor.CmdSketchSend} { + cmd, ok := ed.Command(cmdID) + if !ok { + t.Fatalf("command %s not found", cmdID) + } + if cmd.Enabled == nil || cmd.Enabled() { + t.Fatalf("command %s enabled while PermissionsDraftOpen() == true, want disabled", cmdID) + } + } + ed.DiscardPermissionsDraft() +} diff --git a/packages/game/editor/sketch_ui.go b/packages/game/editor/sketch_ui.go index 8a99876dc..caff87022 100644 --- a/packages/game/editor/sketch_ui.go +++ b/packages/game/editor/sketch_ui.go @@ -17,15 +17,22 @@ func viewportSketchOverlayView(cx *core.Scope, ed *Editor, rev *core.Signal[uint _ = rev.Get() return ed.SketchActive() }) - darkMemo := core.NewMemo(cx, func() bool { + type overlayThemeKey struct { + dark bool + lang string + } + themeMemo := core.NewMemo(cx, func() overlayThemeKey { _ = rev.Get() - return ed.SpecPalette(cx).Dark + return overlayThemeKey{ + dark: ed.SpecPalette(cx).Dark, + lang: ed.ResolvedLanguage(), + } }) return core.Show{ When: active.Get, Then: func(cx *core.Scope) core.Node { return core.Dynamic(func(cx *core.Scope) core.Node { - p := SpecPaletteFor(darkMemo.Get()) + p := SpecPaletteFor(themeMemo.Get().dark) divider := func() core.Node { return core.View{ Style: core.Style{ @@ -455,6 +462,7 @@ func sceneTreeSketchSectionView(cx *core.Scope, ed *Editor, rev *core.Signal[uin func SketchPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { type panelKey struct { dark bool + lang string markCount int selectedMark int hold SketchHoldState @@ -489,7 +497,8 @@ func SketchPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core. } } return panelKey{ - dark: cx.Dark(), + dark: ed.SpecPalette(cx).Dark, + lang: ed.ResolvedLanguage(), markCount: ed.SketchMarkCount(), selectedMark: ed.SelectedSketchMark(), hold: ed.SketchHoldState(), @@ -505,13 +514,20 @@ func SketchPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core. } }) - darkMemo := core.NewMemo(cx, func() bool { + type panelThemeKey struct { + dark bool + lang string + } + darkMemo := core.NewMemo(cx, func() panelThemeKey { _ = rev.Get() - return ed.SpecPalette(cx).Dark + return panelThemeKey{ + dark: ed.SpecPalette(cx).Dark, + lang: ed.ResolvedLanguage(), + } }) return core.Dynamic(func(cx *core.Scope) core.Node { - p := SpecPaletteFor(darkMemo.Get()) + p := SpecPaletteFor(darkMemo.Get().dark) return core.View{ TestID: "sketch-agent-panel", Role: core.RoleRegion, diff --git a/packages/game/editor/state.go b/packages/game/editor/state.go index 2d1f1b833..4fab0809d 100644 --- a/packages/game/editor/state.go +++ b/packages/game/editor/state.go @@ -1300,6 +1300,7 @@ func (e *Editor) SetViewMode(mode ViewMode) { e.CancelCameraDrag() e.CancelCameraBoundsDrag() e.CancelRoomDrag() + e.CancelSketchDrag() e.overlaysPopoverOpen = false e.ViewMode = mode e.Status = "View: " + mode.String() From 6c1c9ef76d9e501f90e87c892c40d5b58913367a Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Thu, 26 Nov 2026 21:05:27 +0900 Subject: [PATCH 4/5] fix(editormcp): enforce Agent Settings outbound privacy switches for sketch_read and sketch_reading --- packages/game/editor/editormcp/privacy.go | 12 +++++ packages/game/editor/editormcp/sketch.go | 3 ++ packages/game/editor/editormcp/sketch_test.go | 54 +++++++++++++++++++ 3 files changed, 69 insertions(+) diff --git a/packages/game/editor/editormcp/privacy.go b/packages/game/editor/editormcp/privacy.go index 93e84b0ac..b0a288b74 100644 --- a/packages/game/editor/editormcp/privacy.go +++ b/packages/game/editor/editormcp/privacy.go @@ -236,6 +236,17 @@ func (s *Server) checkPrivacyPre(ctx context.Context, t Tool, args json.RawMessa if !policy.SceneAndData { return editor.PrivacyRefusalError(editor.PrivacySceneAndData, ToolAgentTurnGet) } + case ToolSketchRead: + var a struct { + IncludeImage *bool `json:"includeImage"` + } + _ = json.Unmarshal(args, &a) + if a.IncludeImage != nil && *a.IncludeImage && !policy.ViewportImages { + return editor.PrivacyRefusalError(editor.PrivacyViewportImages, ToolSketchRead) + } + if !policy.SceneAndData { + return editor.PrivacyRefusalError(editor.PrivacySceneAndData, ToolSketchRead) + } case ToolSceneRead: var a struct { File string `json:"file"` @@ -353,6 +364,7 @@ func (s *Server) checkPrivacyPre(ctx context.Context, t Tool, args json.RawMessa ToolBriefEdit, ToolRulesEdit, ToolHistoryList, + ToolSketchReading, ToolReleaseNotesDraft, ToolReviewStatus, ToolReviewNotesGet, diff --git a/packages/game/editor/editormcp/sketch.go b/packages/game/editor/editormcp/sketch.go index 96d5d3de2..c3ca1ae80 100644 --- a/packages/game/editor/editormcp/sketch.go +++ b/packages/game/editor/editormcp/sketch.go @@ -138,6 +138,9 @@ func sketchRead(ctx context.Context, c *Call) (*Result, error) { wantImg = *args.IncludeImage } if wantImg { + if !ed.AgentPrivacy().ViewportImages { + return editor.PrivacyRefusalError(editor.PrivacyViewportImages, ToolSketchRead) + } b, w, h, err := ed.RenderSketchViewportPNG(float32(scale)) if err != nil { return fmt.Errorf("sketch_read: %w", err) diff --git a/packages/game/editor/editormcp/sketch_test.go b/packages/game/editor/editormcp/sketch_test.go index 18ec761bf..4cbb46bf0 100644 --- a/packages/game/editor/editormcp/sketch_test.go +++ b/packages/game/editor/editormcp/sketch_test.go @@ -265,3 +265,57 @@ func TestSketchHoldGateBlocksAllMutatingToolsRecordsObjectReviewAndIsRaceFree(t t.Fatalf("SketchReviewChanges = %+v, want hero recorded", changes) } } + +func TestSketchToolsRespectPrivacyAndToolToggles(t *testing.T) { + f := openFixture(t) + s := editormcp.New(f.ed, editormcp.Options{}) + t.Cleanup(func() { _ = s.Close() }) + cs := connect(t, s, nil) + + f.ed.AddSketchBox(10, 20, 40, 50, "spikes") + if _, err := f.ed.SendSketch("build spikes"); err != nil { + t.Fatalf("SendSketch: %v", err) + } + + // Turning off Viewport images refuses sketch_read when an image is requested or implied by marks, + // while still allowing includeImage: false so coordinates can be read without sending pixels. + if err := f.ed.SetAgentPrivacy(editor.PrivacyViewportImages, false); err != nil { + t.Fatalf("SetAgentPrivacy(ViewportImages, false): %v", err) + } + if res := call(t, cs, editormcp.ToolSketchRead, map[string]any{"includeImage": true}); !res.IsError { + t.Fatal("sketch_read(includeImage:true) succeeded with ViewportImages disabled") + } + if res := call(t, cs, editormcp.ToolSketchRead, map[string]any{}); !res.IsError { + t.Fatal("sketch_read({}) with marks succeeded with ViewportImages disabled") + } + mustOK(t, call(t, cs, editormcp.ToolSketchRead, map[string]any{"includeImage": false})) + + // Turning off Scene and data files refuses both sketch_read and sketch_reading. + if err := f.ed.SetAgentPrivacy(editor.PrivacySceneAndData, false); err != nil { + t.Fatalf("SetAgentPrivacy(SceneAndData, false): %v", err) + } + if res := call(t, cs, editormcp.ToolSketchRead, map[string]any{"includeImage": false}); !res.IsError { + t.Fatal("sketch_read succeeded with SceneAndData disabled") + } + if res := call(t, cs, editormcp.ToolSketchReading, map[string]any{ + "items": []map[string]any{{"number": 1, "text": "Place spikes"}}, + }); !res.IsError { + t.Fatal("sketch_reading succeeded with SceneAndData disabled") + } + + // Restore privacy and verify Settings › Tools toggle disables sketch_reading cleanly. + if err := f.ed.SetAgentPrivacy(editor.PrivacySceneAndData, true); err != nil { + t.Fatalf("SetAgentPrivacy(SceneAndData, true): %v", err) + } + if err := f.ed.SetAgentPrivacy(editor.PrivacyViewportImages, true); err != nil { + t.Fatalf("SetAgentPrivacy(ViewportImages, true): %v", err) + } + if err := f.ed.SetMCPToolEnabled(editormcp.ToolSketchReading, false); err != nil { + t.Fatalf("SetMCPToolEnabled(sketch_reading, false): %v", err) + } + if res := call(t, cs, editormcp.ToolSketchReading, map[string]any{ + "items": []map[string]any{{"number": 1, "text": "Place spikes"}}, + }); !res.IsError || !strings.Contains(text(res), "turned off") { + t.Fatalf("disabled sketch_reading result = (err=%v, %q), want turned-off refusal", res.IsError, text(res)) + } +} From 833512a540d8316bf5899fa0fb80496a34f816ea Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Thu, 26 Nov 2026 21:58:08 +0900 Subject: [PATCH 5/5] fix(editor): guard Sketch mode against Review, DataTableReview, Settings, FirstRun, and OpenAgentTask --- packages/game/editor/agent_notifications.go | 1 + packages/game/editor/review.go | 3 ++- packages/game/editor/shortcuts.go | 2 +- packages/game/editor/sketch.go | 3 +++ packages/game/editor/sketch_ui.go | 2 +- packages/game/editor/viewport.go | 2 +- 6 files changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/game/editor/agent_notifications.go b/packages/game/editor/agent_notifications.go index 5a75011ee..f837f4ecb 100644 --- a/packages/game/editor/agent_notifications.go +++ b/packages/game/editor/agent_notifications.go @@ -839,6 +839,7 @@ func (e *Editor) OpenAgentTask(id string) error { e.CloseAskInPlace() e.SetProblemAgentPanelOpen(false) e.SetHistoryPanelOpen(false) + e.FinishSketch() if e.LeftRailMode() == LeftRailAssets { e.SetLeftRailMode(LeftRailScene) } diff --git a/packages/game/editor/review.go b/packages/game/editor/review.go index ad77caab7..c655b7f77 100644 --- a/packages/game/editor/review.go +++ b/packages/game/editor/review.go @@ -531,7 +531,8 @@ func (e *Editor) reviewKeepShortcutAllowed() bool { !e.PlaytestReportOpen() && !e.AssetGeneratorOpen() && !e.HUDLayoutOpen() && - !e.CutsceneOpen() + !e.CutsceneOpen() && + !e.SketchActive() } func (e *Editor) validateReviewRelPath(raw string) (string, error) { diff --git a/packages/game/editor/shortcuts.go b/packages/game/editor/shortcuts.go index 75efed681..33a67b8b3 100644 --- a/packages/game/editor/shortcuts.go +++ b/packages/game/editor/shortcuts.go @@ -503,7 +503,7 @@ func (e *Editor) shortcutScopePriority(scope string) int { } return 0 case ScopeSketch: - if e.ViewMode == ViewMode2D && !e.Playing() && e.SketchActive() && !e.ReviewOpen() && !e.SettingsOpen() { + if e.ViewMode == ViewMode2D && !e.sketchBlockedByScreen() && e.SketchActive() { return 5 } return 0 diff --git a/packages/game/editor/sketch.go b/packages/game/editor/sketch.go index 4aa94eb9c..2eaa45218 100644 --- a/packages/game/editor/sketch.go +++ b/packages/game/editor/sketch.go @@ -376,6 +376,9 @@ func (e *Editor) sketchBlockedByScreen() bool { e.HistoryPreviewActive() || e.PermissionsDraftOpen() || e.StartScreenOpen() || + e.FirstRunFullScreenOpen() || + e.ReviewOpen() || + e.DataTableReviewOpen() || e.SettingsOpen() || e.MergeConflictOpen() || e.ChangesOpen() || diff --git a/packages/game/editor/sketch_ui.go b/packages/game/editor/sketch_ui.go index caff87022..068aeb868 100644 --- a/packages/game/editor/sketch_ui.go +++ b/packages/game/editor/sketch_ui.go @@ -15,7 +15,7 @@ import ( func viewportSketchOverlayView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { active := core.NewMemo(cx, func() bool { _ = rev.Get() - return ed.SketchActive() + return ed.SketchActive() && !ed.sketchBlockedByScreen() }) type overlayThemeKey struct { dark bool diff --git a/packages/game/editor/viewport.go b/packages/game/editor/viewport.go index 169048b4c..d13188445 100644 --- a/packages/game/editor/viewport.go +++ b/packages/game/editor/viewport.go @@ -1605,7 +1605,7 @@ func ViewportView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Nod core.Show{ When: func() bool { _ = rev.Get() - if ed.CommandPaletteOpen() || ed.PickingConnectionTarget() || ed.AskInPlaceOpen() || ed.HistoryPreviewActive() { + if ed.CommandPaletteOpen() || ed.PickingConnectionTarget() || ed.AskInPlaceOpen() || ed.HistoryPreviewActive() || ed.SettingsOpen() || ed.ReviewOpen() || ed.DataTableReviewOpen() { return false } _, gmActive := ed.GridMapStrokeActive()