From 0a4c9b4b0c91d48dbbd5c52e8d2aaf38d3bd54ad Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Thu, 26 Nov 2026 13:01:54 +0900 Subject: [PATCH] feat(editor): add agent threads per line of work grouped by scene --- .../2026-11-26-editor-agent-threads.md | 28 + .../public/schemas/agent-thread.v1.json | 205 ++ changelog.d/editor-agent-threads-1019.md | 3 + docs/en/editor.md | 11 +- docs/en/formats.md | 42 + docs/zh/editor.md | 11 +- docs/zh/formats.md | 42 + packages/game/cmd/gameschema/main.go | 7 + packages/game/editor/agent.go | 21 +- packages/game/editor/agent_builtin.go | 14 +- packages/game/editor/agent_threads.go | 2022 +++++++++++++++++ .../editor/agent_threads_conformance_test.go | 17 + packages/game/editor/agent_threads_test.go | 580 +++++ packages/game/editor/agent_threads_ui.go | 1291 +++++++++++ packages/game/editor/agent_ui.go | 308 ++- packages/game/editor/commands.go | 18 + packages/game/editor/demo.go | 1 + .../agent_threads_screenshot_test.go | 267 +++ packages/game/editor/editormcp/edit.go | 13 +- packages/game/editor/editormcp/server_test.go | 21 + packages/game/editor/inspector.go | 3 + packages/game/editor/locales/en.yaml | 55 + packages/game/editor/locales/zh.yaml | 55 + packages/game/editor/project.go | 1 + packages/game/editor/shortcuts.go | 11 + packages/game/editor/state.go | 11 + packages/game/editor/tabs.go | 4 + .../game/editor/testdata/agent_thread.yaml | 59 + packages/game/formats_test.go | 1 + 29 files changed, 5020 insertions(+), 102 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-11-26-editor-agent-threads.md create mode 100644 apps/website/public/schemas/agent-thread.v1.json create mode 100644 changelog.d/editor-agent-threads-1019.md create mode 100644 packages/game/editor/agent_threads.go create mode 100644 packages/game/editor/agent_threads_conformance_test.go create mode 100644 packages/game/editor/agent_threads_test.go create mode 100644 packages/game/editor/agent_threads_ui.go create mode 100644 packages/game/editor/editorcmd/agent_threads_screenshot_test.go create mode 100644 packages/game/editor/testdata/agent_thread.yaml diff --git a/.agents/notes/implemented/feature/2026-11-26-editor-agent-threads.md b/.agents/notes/implemented/feature/2026-11-26-editor-agent-threads.md new file mode 100644 index 000000000..91f7af276 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-26-editor-agent-threads.md @@ -0,0 +1,28 @@ +# Agent Note: Editor agent threads per line of work, grouped by scene + +Status: implemented + +## Problem + +AI-first scene editing in the NSGo Game Editor (`docs/design/editor/Threads.dc.html`, issue #1019) requires separating lines of work into persistent threads scoped by scene, keeping each external agent's session ID per thread, folding reviewed requests so long threads stay scannable, linking folded steps into History, showing an empty-thread orientation seeded from `brief.yaml`, and attributing each scene object in the Inspector footer to the request that last changed it. Previously the right rail rendered only `InspectorView` with no thread persistence, scene-bound thread switching, folded request history, or object-to-request attribution. + +## Decision + +We implement scene-grouped agent threads inside `packages/game/editor` (`agent_threads.go`, `agent_threads_ui.go`) and connect them to scene switching, the Inspector footer, shortcuts, and `editormcp`: + +- **Strict versioned YAML per thread under `.nsgo/threads/.yaml`**: `AgentThread` (`AgentThreadFileVersion = 1`, `AgentThreadSchemaURL = "https://game.nsgo.dev/schemas/agent-thread.v1.json"`) stores `version`, `id`, `title`, `scenePath`, external agent `sessionId`, RFC3339 timestamps, and chronological `requests` with `steps`, review `outcome` (`pending`, `kept`, `reverted`), change counts, changed `objects`, `files`, and `historyStep` links. `ParseAgentThreadYAML` rejects unknown fields, duplicate keys, YAML anchors/aliases/merge keys, trailing documents, path traversal, and invalid counts; `EncodeAgentThreadYAML` writes canonical 2-space YAML that round-trips byte-for-byte. Creating `.nsgo/threads/` writes `.nsgo/.gitignore` (`*\n`) if absent, skips `*.thread.yaml` task-queue files owned by #1022, and validates symlink containment inside the project root. +- **Scene-bound thread lifecycle without carrying threads across scenes**: `openProject` loads valid threads from `.nsgo/threads/` and enters the open scene's most recent thread (or an unsaved empty draft thread). `SelectTab`, `activateNewTab`, `CloseTab`, `openYAMLWithLayers`, and `SaveFile` (when `ScenePath` changes) call `syncAgentThreadForOpenScene()`, which enters the newly active scene's latest thread or a fresh scene draft and never carries the previous scene's thread along. Selecting another scene's thread from the switcher opens that scene tab before activating the chosen thread. +- **Unified right rail with `Inspector` default tab, `Agent` panel with threads, and `History` view**: `RightRailView` integrates `InspectorView` (default `RightTabInspector`, preserving all existing Inspector tests and 272 pt layout), `AgentPanelView` (380 pt matching `Threads.dc.html`, hosting the thread switcher header, popover, folded/expanded requests, empty-thread orientation, live turns, status chip, and composer), `TasksPanelView` (#1022), and `AgentHistoryView` (`RightTabHistory`). Every surface uses `ed.SpecPalette(cx)` tokens across Spec Dark and Spec Light themes. +- **Scoped `⌘N` (`ScopeAgent`)**: `CmdNewAgentThread` binds `mod+n` in a dedicated `ScopeAgent` prioritized above `ScopeGlobal` only while the Agent panel is active (`RightRailAgent`), focused, or its switcher is open, leaving `CmdNewProject` (`mod+n` in `ScopeGlobal`) intact elsewhere without shortcut conflict. +- **Inspector footer attribution and `editormcp` hook**: `LastAgentChangeForObject` scans the open scene's and project-level threads for the most recent non-reverted request touching `objectID` (including edits automatically noted by `editormcp`'s `scene_edit` via `Editor.NoteAgentEditedObjects`), rendering `inspector-thread-footer` above the existing static `inspector-footer` hint and opening/expanding that request on press. + +## Alternatives considered + +- **Storing all threads in one `.nsgo/threads.yaml` index file**: Rejected because concurrent or frequent per-request writes would rewrite unrelated threads, make manual inspection/deletion of one line of work harder, and diverge from issue #1019's requirement of one file per thread under `.nsgo/threads/`. +- **Making `RightRailAgent` the default right-rail tab on `EditorView` mount**: Rejected because existing editor regression tests and workflows expect `InspectorView` controls (`editor-inspector`, `inspector-footer`, field inputs) to be mounted immediately when `EditorView` starts without an extra tab switch; defaulting to `RightRailInspector` keeps every existing test intact while exposing one-click switching to `Agent` and `History`. +- **Rebinding `mod+n` globally from `CmdNewProject` to `CmdNewAgentThread`**: Rejected because `TestDesktopMenuBarMatchesRegistryAndExecutesActions` and desktop File > New Project expect `CmdNewProject` to own `mod+n` in `ScopeGlobal`; placing `CmdNewAgentThread` in `ScopeAgent` follows the editor's scope-aware shortcut architecture (`shortcuts.go`) and resolves `⌘N` cleanly inside the Agent panel. + +## Consequences + +- **Benefits**: Each line of work persists cleanly in readable, schema-validated YAML under `.nsgo/threads/` (ignored by git), scene switching cleanly isolates threads per scene, external agent `sessionId` survives project reloads, folded requests link directly into History, empty threads surface `brief.yaml` suggestions safely, and the Inspector links any agent-modified object back to the exact request that changed it. +- **Costs**: `RightRailView` adds a 38 pt tab header above `InspectorView` and widens the right rail to 380 pt when `Agent` or `History` is active. Full external agent CLI execution and streaming remain owned by #1009 (`Editor.OnSendAgentRequest` provides the clean hook for #1009 to attach without changing the thread storage or UI contract). diff --git a/apps/website/public/schemas/agent-thread.v1.json b/apps/website/public/schemas/agent-thread.v1.json new file mode 100644 index 000000000..770f40837 --- /dev/null +++ b/apps/website/public/schemas/agent-thread.v1.json @@ -0,0 +1,205 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://game.nsgo.dev/schemas/agent-thread.v1.json", + "title": "NSGo game editor agent thread (version 1)", + "description": "AgentThread is the strict versioned YAML document stored per line of work under .nsgo/threads/.yaml. A file looks like this:\n\n# yaml-language-server: $schema=https://game.nsgo.dev/schemas/agent-thread.v1.json version: 1 id: door-lever-pulls title: Door opens after two lever pulls scenePath: scenes/level_01.scene.yaml sessionId: sess_claude_01 createdAt: \"2026-11-26T13:40:00Z\" updatedAt: \"2026-11-26T14:18:00Z\"\n\nParseAgentThreadYAML decodes it strictly and EncodeAgentThreadYAML writes it back in canonical form so loading and saving a thread file changes nothing.", + "type": "object", + "properties": { + "version": { + "description": "Version is the schema version; it must equal AgentThreadFileVersion (1).", + "type": "integer", + "const": 1 + }, + "id": { + "description": "ID is the stable filename-safe identifier for this thread (stored as .nsgo/threads/.yaml).", + "type": "string" + }, + "title": { + "description": "Title is the thread's display name, automatically set from its first request.", + "type": "string" + }, + "scenePath": { + "description": "ScenePath is the slash-separated project-relative scene path this thread belongs to, or empty for Project · no scene.", + "type": "string" + }, + "sessionId": { + "description": "SessionID is the external agent's session identifier so follow-up requests continue the same agent session.", + "type": "string" + }, + "createdAt": { + "description": "CreatedAt is the RFC3339 UTC timestamp when the thread was created.", + "type": "string" + }, + "updatedAt": { + "description": "UpdatedAt is the RFC3339 UTC timestamp of the thread's latest activity.", + "type": "string" + }, + "requests": { + "description": "Requests lists the thread's requests in chronological order (oldest first, latest last).", + "type": "array", + "items": { + "$ref": "#/definitions/AgentThreadRequest" + } + } + }, + "required": [ + "version", + "id", + "createdAt", + "updatedAt" + ], + "additionalProperties": false, + "definitions": { + "AgentThreadRequest": { + "description": "AgentThreadRequest is one author request and its streamed steps, changed objects/files, and review outcome.", + "type": "object", + "properties": { + "id": { + "description": "ID uniquely identifies this request within its thread.", + "type": "string" + }, + "title": { + "description": "Title is the short single-line summary shown when the request is folded or referenced in the Inspector footer.", + "type": "string" + }, + "prompt": { + "description": "Prompt is the full request text sent to the agent.", + "type": "string" + }, + "createdAt": { + "description": "CreatedAt is the RFC3339 UTC timestamp when the request was sent.", + "type": "string" + }, + "updatedAt": { + "description": "UpdatedAt is the RFC3339 UTC timestamp when the request last changed state.", + "type": "string" + }, + "reply": { + "description": "Reply is the agent's short completion message shown under the steps.", + "type": "string" + }, + "outcome": { + "description": "Outcome records whether the request is \"pending\", \"kept\", or \"reverted\".", + "type": "string", + "enum": [ + "pending", + "kept", + "reverted" + ] + }, + "changesTotal": { + "description": "ChangesTotal is the total number of proposed changes in this request.", + "type": "integer", + "minimum": -9223372036854776000, + "maximum": 9223372036854776000 + }, + "changesKept": { + "description": "ChangesKept is the number of proposed changes kept during review (0..ChangesTotal).", + "type": "integer", + "minimum": -9223372036854776000, + "maximum": 9223372036854776000 + }, + "files": { + "description": "Files lists project-relative slash paths of files changed by this request.", + "type": "array", + "items": { + "type": "string" + } + }, + "objects": { + "description": "Objects lists scene object IDs changed by this request (used for Inspector footer attribution).", + "type": "array", + "items": { + "type": "string" + } + }, + "detail": { + "description": "Detail is a compact human-readable summary of changed fields/assets shown when expanded.", + "type": "string" + }, + "historyStep": { + "description": "HistoryStep names the undo step label in History linked to this request.", + "type": "string" + }, + "historyIndex": { + "description": "HistoryIndex records the 1-based undo stack index in History linked to this request, when known.", + "type": "integer", + "minimum": -9223372036854776000, + "maximum": 9223372036854776000 + }, + "steps": { + "description": "Steps lists the recorded agent steps for this request in execution order.", + "type": "array", + "items": { + "$ref": "#/definitions/AgentThreadStep" + } + } + }, + "required": [ + "id", + "prompt", + "createdAt", + "outcome" + ], + "additionalProperties": false + }, + "AgentThreadStep": { + "description": "AgentThreadStep is one recorded action taken by the agent while handling a request.", + "type": "object", + "properties": { + "id": { + "description": "ID uniquely identifies this step within its request.", + "type": "string" + }, + "label": { + "description": "Label is the short human-readable description shown in the thread and History.", + "type": "string" + }, + "status": { + "description": "Status is the step's state (\"pending\", \"running\", \"done\", or \"failed\").", + "type": "string", + "enum": [ + "pending", + "running", + "done", + "failed" + ] + }, + "detail": { + "description": "Detail holds optional extra context for the step (for example changed fields or files).", + "type": "string" + }, + "historyStep": { + "description": "HistoryStep names the corresponding editor History label, when this step edited the scene.", + "type": "string" + }, + "historyIndex": { + "description": "HistoryIndex records the 1-based History stack index created by this step, when known.", + "type": "integer", + "minimum": -9223372036854776000, + "maximum": 9223372036854776000 + }, + "objects": { + "description": "Objects lists the IDs of scene objects modified by this step.", + "type": "array", + "items": { + "type": "string" + } + }, + "files": { + "description": "Files lists project-relative slash paths of files touched by this step.", + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "id", + "label", + "status" + ], + "additionalProperties": false + } + } +} diff --git a/changelog.d/editor-agent-threads-1019.md b/changelog.d/editor-agent-threads-1019.md new file mode 100644 index 000000000..1a9729f87 --- /dev/null +++ b/changelog.d/editor-agent-threads-1019.md @@ -0,0 +1,3 @@ +### Added + +- Add per-line-of-work agent threads persisted as strict versioned YAML under `.nsgo/threads/` (ignored by `.nsgo/.gitignore`), grouped by open scene, other scenes, and `Project · no scene`, with search, `⌘N` new thread, scene-bound thread switching, folded earlier requests with History links and Jump to latest, empty-thread brief suggestions, and an Inspector footer linking each object to the request that last changed it (#1019). diff --git a/docs/en/editor.md b/docs/en/editor.md index a034456dc..d7e53dac0 100644 --- a/docs/en/editor.md +++ b/docs/en/editor.md @@ -1326,7 +1326,6 @@ Every interactive control in the editor carries the `docs/design/editor/Spec.dc. - **Viewport focus is the selection**: the viewport canvas draws no focus ring of its own; while focus is in the viewport (`editor-viewport-frame`), `Tab` (`Editor.SelectNextObject`) and `Shift-Tab` (`Editor.SelectPreviousObject`) cycle through visible, unlocked scene objects in order. - **Dialog focus trapping and opener restoration**: editor dialogs (`EditorSettingsDialogView`, `ShortcutsSheetView`, `CommandPaletteView`, unsaved-changes prompt, scene path dialog, and save-conflict dialog) trap `Tab` / `Shift-Tab` inside the topmost modal (respecting shortcut capture in `Settings › Shortcuts`), block global shortcuts behind the modal except `⌘.` / `Ctrl+.` (`Editor.OnStopAgent`) to stop an active agent, and return focus to the exact control that opened the dialog when dismissed with `Esc` or an action button. - **Focus stability**: nothing moves focus automatically during an active drag or inspector scrub (`Editor.IsDragging`) or while typing in a text field (`Editor.IsTyping`). Showing a toast never steals focus, and `Editor.ShouldFocusAgentPrompt` returns `true` only when no drag or text input is active and focus is already inside the agent panel (`Editor.SetAgentPanelRef`). - ## Connect an agent and status chip (#1009) Connect an external coding agent (Claude Code, Codex, or any MCP client on your computer) directly from the editor or with `go tool game mcp install`, matching `docs/design/editor/Connect.dc.html`, `docs/design/editor/AgentStates.dc.html`, and `docs/design/editor/Settings.dc.html` using exclusively `docs/design/editor/Spec.dc.html` tokens: @@ -1504,3 +1503,13 @@ While an agent edits a scene through `editormcp` or an active agent turn (`Edito - **Scene tree markers**: added nodes show a `NEW` badge, changed nodes show a `MOD` badge, removed nodes remain visible as struck-through ghost rows with a `DEL` badge, and currently touched nodes display a violet agent-working dot until **Keep** or **Revert**. - **Header pill**: follows the agent's state (`Editor.SetAgentState` / `Editor.AgentState`): violet working pill (`"Agent is · manual edits stay available"`), warning waiting pill (`"Waiting for you · "`), pending-review pill with **Keep** (`KeepAgentTurn`, collapsing the turn into one undo step) and **Revert** (`RevertAgentTurn`, undoing the turn and restoring removed objects), and hidden while idle. - **Interactive top-left Overlay Legend**: appears automatically whenever live overlays are active (or when `OverlayLegendOpen` is true). Each row (**Selection**, **Agent working**, **Added**, **Changed**, **Removed**, **Problem**) is a `RoleSwitch` toggle (`ToggleOverlayLegendKind` / `SetOverlayLegendKind`) persisted per-user in `EditorSettings.HiddenOverlayKinds` (`hiddenOverlayKinds` in `editor.yaml`, schema `editor-settings.v1.json`) without modifying project files. + +## Agent threads per line of work, grouped by scene (#1019) + +The right rail (`RightRailView`) switches between **Agent** (`AgentPanelView` / `AgentThreadsView`), **Inspector** (`InspectorView`, the default tab), and **History** (`AgentHistoryView`), using `docs/design/editor/Spec.dc.html` tokens matching `Threads.dc.html` across Dark and Light appearances: + +- **One YAML file per thread under `.nsgo/threads/` (`AgentThread`, `AgentThreadFileVersion = 1`)**: each thread is persisted as a strict versioned YAML document at `.nsgo/threads/.yaml` (with `.nsgo/.gitignore` automatically ignoring the directory from git), storing `id`, `title` (named from its first request), `scenePath`, external agent `sessionId` (`SetAgentThreadSessionID`), timestamps, and chronological `requests` with `steps`, `outcome` (`pending`, `kept`, `reverted`), change counts, changed `objects`, and `historyStep` links. Parsed with `ParseAgentThreadYAML` and written canonically with `EncodeAgentThreadYAML` (JSON Schema `https://game.nsgo.dev/schemas/agent-thread.v1.json`). +- **Grouped thread switcher, search, and `⌘N` (`AgentThreadGroups`, `CmdNewAgentThread`)**: the switcher groups threads under ` · OPEN SCENE`, other scenes (``), and `PROJECT · NO SCENE`, each showing relative age and state (`now · 3 changes to review`, `1 h ago · kept 5 of 6`, `yesterday · reverted`, or changed files). Opening or switching scenes enters that scene's most recent thread (or a fresh draft) and never carries another scene's thread along; `⌘N` (`ScopeAgent`) starts a new empty thread. +- **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. diff --git a/docs/en/formats.md b/docs/en/formats.md index 2e54cb0f7..e7439482d 100644 --- a/docs/en/formats.md +++ b/docs/en/formats.md @@ -2089,6 +2089,48 @@ projects: lastOpened: "2026-11-24T12:30:00Z" ``` + +### Editor agent threads + +| Files | Version | Read and written by | Fields | +| --- | --- | --- | --- | +| `.nsgo/threads/.yaml` (`editor.AgentThreadsDir`, ignored by `.nsgo/.gitignore`) | `version: 1` | `editor.ParseAgentThreadYAML`, `editor.EncodeAgentThreadYAML` | [Editor](editor.md#agent-threads-per-line-of-work-grouped-by-scene-1019); schema `https://game.nsgo.dev/schemas/agent-thread.v1.json` | + +Each line of work is one strict versioned YAML file storing its `id`, `title` (named from its first request), `scenePath` (empty for `Project · no scene` threads), `sessionId` (so follow-up requests continue the external agent's session), RFC3339 timestamps, and chronological `requests` with `steps`, review `outcome` (`pending`, `kept`, `reverted`), change counts, changed `objects` (driving the Inspector footer link), and `historyStep` references. + +```yaml +# yaml-language-server: $schema=https://game.nsgo.dev/schemas/agent-thread.v1.json +version: 1 +id: door-lever-pulls +title: Door opens after two lever pulls +scenePath: scenes/level_01.scene.yaml +sessionId: sess_claude_01 +createdAt: "2026-11-26T13:40:00Z" +updatedAt: "2026-11-26T14:18:00Z" +requests: + - id: req-001 + title: Door opens after two lever pulls + prompt: Keep the door shut until the lever is pulled twice, then let it open. + createdAt: "2026-11-26T13:40:00Z" + updatedAt: "2026-11-26T13:41:00Z" + outcome: kept + changesTotal: 3 + changesKept: 3 + files: + - prefabs/door.prefab.yaml + - scenes/level_01.scene.yaml + objects: + - Door + - lever_01 + detail: Door.locked, Door.opens_after_pulls, lever_01.pulls + historyStep: 'Agent: Door opens after two lever pulls' + historyIndex: 1 + steps: + - id: step-001 + label: Read level_01.scene.yaml and door.prefab.yaml + status: done +``` + ### Asset build cache diff --git a/docs/zh/editor.md b/docs/zh/editor.md index 682049572..27c14f351 100644 --- a/docs/zh/editor.md +++ b/docs/zh/editor.md @@ -1326,7 +1326,6 @@ func main() { - **视口内焦点即选中对象**:视口画布本身不绘制焦点环;当焦点位于视口(`editor-viewport-frame`)内时,`Tab`(`Editor.SelectNextObject`)与 `Shift-Tab`(`Editor.SelectPreviousObject`)按场景顺序循环选中下一个/上一个可见且未锁定的对象。 - **对话框焦点限制与关闭恢复**:所有编辑器对话框(`EditorSettingsDialogView`、`ShortcutsSheetView`、`CommandPaletteView`、未保存提示、场景路径对话框与保存冲突对话框)会将 `Tab` / `Shift-Tab` 限制在最顶层模态框内(同时不干扰 `Settings › Shortcuts` 的按键录制),在对话框打开期间屏蔽全局快捷键(除用于停止智能体的 `⌘.` / `Ctrl+.`,即 `Editor.OnStopAgent` 外),并在按 `Esc` 取消或点击操作按钮关闭后将焦点精确恢复到打开该对话框的控件。 - **焦点稳定性**:在拖拽或检查器数值微调进行中(`Editor.IsDragging`)或用户正在文本字段中输入时(`Editor.IsTyping`),编辑器不会自动抢占焦点;弹出 Toast 不会抢走焦点;`Editor.ShouldFocusAgentPrompt` 仅在未拖拽、未输入且焦点原本就位于智能体面板内(`Editor.SetAgentPanelRef`)时才返回 `true`。 - ## 连接智能体与状态胶囊(#1009) 在编辑器内或通过 `go tool game mcp install` 连接本机的外部编程智能体(Claude Code、Codex 或任意 MCP 客户端),界面严格遵循 `docs/design/editor/Spec.dc.html` 设计 Token 并对应 `docs/design/editor/Connect.dc.html`、`docs/design/editor/AgentStates.dc.html` 与 `docs/design/editor/Settings.dc.html`: @@ -1504,3 +1503,13 @@ func main() { - **场景树标记**:新增节点显示 `NEW` 徽章,修改节点显示 `MOD` 徽章,被移除节点以带删除线的虚影行与 `DEL` 徽章保留在树中,智能体正在操作的节点显示紫色圆点,直至执行 **Keep** 或 **Revert**。 - **顶栏状态胶囊**:随智能体状态自动切换(`Editor.SetAgentState` / `Editor.AgentState`):工作中显示紫色胶囊(`"Agent is · manual edits stay available"`),等待确认显示警告胶囊(`"Waiting for you · "`),待审查状态显示改动数量与 **Keep**(`KeepAgentTurn`,将整个回合合并为单步撤销)/**Revert**(`RevertAgentTurn`,回滚回合改动并还原已删除对象)按钮,空闲时自动隐藏。 - **左上角可交互叠加层图例**:当存在任意实时叠加层(或 `OverlayLegendOpen` 为真)时自动显示。图例中的每一行(**Selection**、**Agent working**、**Added**、**Changed**、**Removed**、**Problem**)都是可点击的 `RoleSwitch` 开关(`ToggleOverlayLegendKind` / `SetOverlayLegendKind`),隐藏项按用户持久化到项目之外的 `EditorSettings.HiddenOverlayKinds`(`editor.yaml` 中的 `hiddenOverlayKinds`,Schema 为 `editor-settings.v1.json`),绝不污染项目文件。 + +## 按工作线与场景分组的智能体线程(#1019) + +右侧栏(`RightRailView`)可在**智能体**(`AgentPanelView` / `AgentThreadsView`)、**检查器**(`InspectorView`,默认标签)与**历史记录**(`AgentHistoryView`)之间切换,全部使用 `docs/design/editor/Spec.dc.html` 的深浅双主题规范令牌并对应 `Threads.dc.html`: + +- **`.nsgo/threads/` 下每条线程一个 YAML 文件(`AgentThread`、`AgentThreadFileVersion = 1`)**:每条线程以严格版本化的 YAML 文档保存在 `.nsgo/threads/.yaml`(同时自动写出 `.nsgo/.gitignore` 使其被 git 忽略),记录 `id`、`title`(自动取自首条请求)、`scenePath`、外部智能体会话 `sessionId`(`SetAgentThreadSessionID`)、时间戳以及按顺序排列的 `requests`(包含 `steps`、审查结果 `outcome`(`pending`、`kept`、`reverted`)、修改计数、受影响的 `objects` 与 `historyStep` 链接)。通过 `ParseAgentThreadYAML` 严格解析并以 `EncodeAgentThreadYAML` 写出规范形式(JSON Schema:`https://game.nsgo.dev/schemas/agent-thread.v1.json`)。 +- **分组线程切换器、搜索与 `⌘N`(`AgentThreadGroups`、`CmdNewAgentThread`)**:切换器按`<当前场景> · 当前场景`、其他场景以及`项目 · 无场景`分组展示线程,每行附带相对时间与状态(如“刚刚 · 3 项待审查修改”、“1 小时前 · 已保留 5/6 项”、“昨天 · 已还原”或涉及文件)。打开或切换场景会自动进入该场景最近使用的线程(或新的空白草稿),绝不把上一场景的线程带到新场景;在智能体作用域(`ScopeAgent`)中按 `⌘N` 可新建空白线程。 +- **折叠较早请求、跳转历史记录与跳到最新**:已审查的较早请求折叠为单行(`N 条较早请求`),点击展开显示完整提示词、变更明细、步骤列表以及**在历史记录中打开此步骤**(`OpenHistoryStep`)链接,点击后在统一历史时间线中高亮该步骤;展开较早请求时底部浮现**跳到最新**按钮(`JumpToLatestAgentRequest`)。 +- **空白线程视图(`AgentAlwaysReadItems`、`AgentBriefSuggestions`)**:空白线程会列出智能体每次请求必读的上下文(`<场景> · 整个场景`、`brief.yaml`、`AGENTS.md`、`视口图像`),并安全读取项目 `brief.yaml` 中的建议提示(`来自项目简报`)。 +- **检查器页脚来源链接(`LastAgentChangeForObject`、`OpenAgentRequest`)**:当选中对象曾被未还原的智能体请求修改(无论是通过 `SendAgentRequestWith`、`RecordAgentStep` 还是 `editormcp` 的 `scene_edit`),检查器页脚会显示“修改自“<请求标题>” · <时间>”,点击即可打开对应线程并定位/展开该请求。 diff --git a/docs/zh/formats.md b/docs/zh/formats.md index 65aff44e9..8023a5b94 100644 --- a/docs/zh/formats.md +++ b/docs/zh/formats.md @@ -2089,6 +2089,48 @@ projects: lastOpened: "2026-11-24T12:30:00Z" ``` + +### 编辑器智能体线程 + +| 文件 | 版本 | 读写函数 | 字段 | +| --- | --- | --- | --- | +| `.nsgo/threads/.yaml`(`editor.AgentThreadsDir`,由 `.nsgo/.gitignore` 忽略) | `version: 1` | `editor.ParseAgentThreadYAML`、`editor.EncodeAgentThreadYAML` | [编辑器](editor.md#按工作线与场景分组的智能体线程1019);Schema 为 `https://game.nsgo.dev/schemas/agent-thread.v1.json` | + +每条工作线对应一个严格版本化的 YAML 文件,记录 `id`、`title`(由首条请求自动命名)、`scenePath`(为空表示“项目 · 无场景”线程)、`sessionId`(便于后续请求延续同一外部智能体会话)、RFC3339 时间戳以及按时间顺序排列的 `requests`(包含 `steps`、审查结果 `outcome`(`pending`、`kept`、`reverted`)、修改计数、受影响的 `objects` 与 `historyStep` 引用)。 + +```yaml +# yaml-language-server: $schema=https://game.nsgo.dev/schemas/agent-thread.v1.json +version: 1 +id: door-lever-pulls +title: Door opens after two lever pulls +scenePath: scenes/level_01.scene.yaml +sessionId: sess_claude_01 +createdAt: "2026-11-26T13:40:00Z" +updatedAt: "2026-11-26T14:18:00Z" +requests: + - id: req-001 + title: Door opens after two lever pulls + prompt: Keep the door shut until the lever is pulled twice, then let it open. + createdAt: "2026-11-26T13:40:00Z" + updatedAt: "2026-11-26T13:41:00Z" + outcome: kept + changesTotal: 3 + changesKept: 3 + files: + - prefabs/door.prefab.yaml + - scenes/level_01.scene.yaml + objects: + - Door + - lever_01 + detail: Door.locked, Door.opens_after_pulls, lever_01.pulls + historyStep: 'Agent: Door opens after two lever pulls' + historyIndex: 1 + steps: + - id: step-001 + label: Read level_01.scene.yaml and door.prefab.yaml + status: done +``` + ### 资源构建缓存 diff --git a/packages/game/cmd/gameschema/main.go b/packages/game/cmd/gameschema/main.go index bf8304bba..afe87e3d0 100644 --- a/packages/game/cmd/gameschema/main.go +++ b/packages/game/cmd/gameschema/main.go @@ -303,6 +303,13 @@ var formats = []format{ pkg: "editor", version: editor.AutomationsVersion, }, + { + url: editor.AgentThreadSchemaURL, + title: "NSGo game editor agent thread (version 1)", + typ: reflect.TypeFor[editor.AgentThread](), + pkg: "editor", + version: editor.AgentThreadFileVersion, + }, } // durationTypes maps duration types to their YAML schema forms: time.Duration accepts a Go duration string or integer nanoseconds; cutscene.Duration accepts only Go duration strings such as "1.5s". diff --git a/packages/game/editor/agent.go b/packages/game/editor/agent.go index c6f6b32e2..29dc75350 100644 --- a/packages/game/editor/agent.go +++ b/packages/game/editor/agent.go @@ -23,8 +23,15 @@ type RightRailTab string const ( // RightTabInspector shows the property / scene / layer inspector (default). RightTabInspector RightRailTab = "inspector" - // RightTabAgent shows the Agent panel with status chip, thread, and composer. + // RightTabAgent shows the Agent panel with status chip, threads, and composer. RightTabAgent RightRailTab = "agent" + // RightTabHistory shows the unified timeline of agent and manual steps. + RightTabHistory RightRailTab = "history" + + // RightRailInspector, RightRailAgent, and RightRailHistory alias the right-rail tabs. + RightRailInspector = RightTabInspector + RightRailAgent = RightTabAgent + RightRailHistory = RightTabHistory ) // AgentMode selects how the editor connects to an AI agent. @@ -573,24 +580,24 @@ func (e *Editor) resetAgentForProject() { e.updateAgentAnnouncement() } -// RightRailTab returns the active tab in the right sidebar (RightTabInspector or RightTabAgent). +// RightRailTab returns the active tab in the right sidebar (RightTabInspector, RightTabAgent, or RightTabHistory). func (e *Editor) RightRailTab() RightRailTab { if e == nil || e.agent.rightTab == "" { return RightTabInspector } - if e.agent.mode == AgentModeNone { + if e.agent.mode == AgentModeNone && e.agent.rightTab == RightTabAgent { return RightTabInspector } return e.agent.rightTab } -// SetRightRailTab switches the right sidebar between Inspector and Agent. +// SetRightRailTab switches the right sidebar between Inspector, Agent, and History. // When AgentModeNone is active, the Agent panel stays closed. func (e *Editor) SetRightRailTab(tab RightRailTab) { if e == nil { return } - if tab != RightTabAgent { + if tab != RightTabAgent && tab != RightTabHistory { tab = RightTabInspector } if tab == RightTabAgent && e.agent.mode == AgentModeNone { @@ -600,6 +607,10 @@ func (e *Editor) SetRightRailTab(tab RightRailTab) { return } e.agent.rightTab = tab + if tab != RightTabAgent { + e.agentThreads.switcherOpen = false + } + e.agentThreads.rev++ e.notify() } diff --git a/packages/game/editor/agent_builtin.go b/packages/game/editor/agent_builtin.go index 797bc430f..84defeb6c 100644 --- a/packages/game/editor/agent_builtin.go +++ b/packages/game/editor/agent_builtin.go @@ -632,9 +632,19 @@ func (e *Editor) submitAgentTaskPromptInternal(task AgentTaskKind, prompt string ScenePath: e.ScenePath, }, e.FilePath, time.Time{}) + threadID := e.agent.threadID + sessionID := e.agent.sessionID + if active := e.ActiveAgentThread(); active != nil { + if active.ID != "" { + threadID = active.ID + } + if sessionID == "" && active.SessionID != "" { + sessionID = active.SessionID + } + } req := AgentRequest{ - ThreadID: e.agent.threadID, - SessionID: e.agent.sessionID, + ThreadID: threadID, + SessionID: sessionID, Prompt: text, ProjectRoot: e.agentProjectRoot(), ScenePath: e.ScenePath, diff --git a/packages/game/editor/agent_threads.go b/packages/game/editor/agent_threads.go new file mode 100644 index 000000000..079bf8081 --- /dev/null +++ b/packages/game/editor/agent_threads.go @@ -0,0 +1,2022 @@ +package editor + +import ( + "bytes" + "cmp" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "slices" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/nsgo-dev/game/packages/game/l10n" + "github.com/nsgo-dev/game/packages/game/loaderr" + "go.yaml.in/yaml/v3" +) + +// AgentThreadsDir is the project-relative directory where the editor stores one versioned YAML +// file per agent thread. Creating it writes a .gitignore in .nsgo/ so threads stay local and +// ignored by git. +const AgentThreadsDir = ".nsgo/threads" + +// AgentThreadFileVersion is the YAML schema version of per-thread files under .nsgo/threads/.yaml. +const AgentThreadFileVersion = 1 + +// AgentThreadSchemaURL is where the JSON Schema of version 1 agent thread files is published. +const AgentThreadSchemaURL = "https://game.nsgo.dev/schemas/agent-thread.v1.json" + +// AgentThreadSchemaComment is the first line EncodeAgentThreadYAML writes: a YAML comment pointing +// a YAML language server at AgentThreadSchemaURL. ParseAgentThreadYAML ignores it like any other comment. +const AgentThreadSchemaComment = "# yaml-language-server: $schema=" + AgentThreadSchemaURL + +const ( + maxAgentThreadBytes = 2 << 20 // 2 MiB safety cap per thread file. + maxBriefYAMLBytes = 256 << 10 // 256 KiB safety cap when reading brief.yaml. +) + +// AgentThreadOutcome records how a thread request's proposed changes were resolved. +type AgentThreadOutcome string + +const ( + // AgentThreadOutcomePending marks an in-progress or awaiting-review request. + AgentThreadOutcomePending AgentThreadOutcome = "pending" + // AgentThreadOutcomeKept marks a reviewed request whose changes (all or some) were kept. + AgentThreadOutcomeKept AgentThreadOutcome = "kept" + // AgentThreadOutcomeReverted marks a reviewed request whose changes were reverted. + AgentThreadOutcomeReverted AgentThreadOutcome = "reverted" +) + +// Valid reports whether o is a recognized AgentThreadOutcome value. +func (o AgentThreadOutcome) Valid() bool { + switch o { + case AgentThreadOutcomePending, AgentThreadOutcomeKept, AgentThreadOutcomeReverted: + return true + default: + return false + } +} + +// AgentThreadStepStatus records the execution state of one step inside an agent request. +type AgentThreadStepStatus string + +const ( + // AgentThreadStepPending marks a queued step that has not started yet. + AgentThreadStepPending AgentThreadStepStatus = "pending" + // AgentThreadStepRunning marks a step currently executing. + AgentThreadStepRunning AgentThreadStepStatus = "running" + // AgentThreadStepDone marks a completed step. + AgentThreadStepDone AgentThreadStepStatus = "done" + // AgentThreadStepFailed marks a step that failed. + AgentThreadStepFailed AgentThreadStepStatus = "failed" +) + +// Valid reports whether s is a recognized AgentThreadStepStatus value. +func (s AgentThreadStepStatus) Valid() bool { + switch s { + case AgentThreadStepPending, AgentThreadStepRunning, AgentThreadStepDone, AgentThreadStepFailed: + return true + default: + return false + } +} + +// AgentThreadStep is one recorded action taken by the agent while handling a request. +type AgentThreadStep struct { + // ID uniquely identifies this step within its request. + ID string `yaml:"id" schema:"required"` + // Label is the short human-readable description shown in the thread and History. + Label string `yaml:"label" schema:"required"` + // Status is the step's state ("pending", "running", "done", or "failed"). + Status AgentThreadStepStatus `yaml:"status" schema:"required,enum=pending|running|done|failed"` + // Detail holds optional extra context for the step (for example changed fields or files). + Detail string `yaml:"detail,omitempty"` + // HistoryStep names the corresponding editor History label, when this step edited the scene. + HistoryStep string `yaml:"historyStep,omitempty"` + // HistoryIndex records the 1-based History stack index created by this step, when known. + HistoryIndex int `yaml:"historyIndex,omitempty"` + // Objects lists the IDs of scene objects modified by this step. + Objects []string `yaml:"objects,omitempty"` + // Files lists project-relative slash paths of files touched by this step. + Files []string `yaml:"files,omitempty"` +} + +// AgentThreadRequest is one author request and its streamed steps, changed objects/files, and review outcome. +type AgentThreadRequest struct { + // ID uniquely identifies this request within its thread. + ID string `yaml:"id" schema:"required"` + // Title is the short single-line summary shown when the request is folded or referenced in the Inspector footer. + Title string `yaml:"title,omitempty"` + // Prompt is the full request text sent to the agent. + Prompt string `yaml:"prompt" schema:"required"` + // CreatedAt is the RFC3339 UTC timestamp when the request was sent. + CreatedAt string `yaml:"createdAt" schema:"required"` + // UpdatedAt is the RFC3339 UTC timestamp when the request last changed state. + UpdatedAt string `yaml:"updatedAt,omitempty"` + // Reply is the agent's short completion message shown under the steps. + Reply string `yaml:"reply,omitempty"` + // Outcome records whether the request is "pending", "kept", or "reverted". + Outcome AgentThreadOutcome `yaml:"outcome" schema:"required,enum=pending|kept|reverted"` + // ChangesTotal is the total number of proposed changes in this request. + ChangesTotal int `yaml:"changesTotal,omitempty"` + // ChangesKept is the number of proposed changes kept during review (0..ChangesTotal). + ChangesKept int `yaml:"changesKept,omitempty"` + // Files lists project-relative slash paths of files changed by this request. + Files []string `yaml:"files,omitempty"` + // Objects lists scene object IDs changed by this request (used for Inspector footer attribution). + Objects []string `yaml:"objects,omitempty"` + // Detail is a compact human-readable summary of changed fields/assets shown when expanded. + Detail string `yaml:"detail,omitempty"` + // HistoryStep names the undo step label in History linked to this request. + HistoryStep string `yaml:"historyStep,omitempty"` + // HistoryIndex records the 1-based undo stack index in History linked to this request, when known. + HistoryIndex int `yaml:"historyIndex,omitempty"` + // Steps lists the recorded agent steps for this request in execution order. + Steps []AgentThreadStep `yaml:"steps,omitempty"` +} + +// AgentThread is the strict versioned YAML document stored per line of work under .nsgo/threads/.yaml. +// A file looks like this: +// +// # yaml-language-server: $schema=https://game.nsgo.dev/schemas/agent-thread.v1.json +// version: 1 +// id: door-lever-pulls +// title: Door opens after two lever pulls +// scenePath: scenes/level_01.scene.yaml +// sessionId: sess_claude_01 +// createdAt: "2026-11-26T13:40:00Z" +// updatedAt: "2026-11-26T14:18:00Z" +// +// ParseAgentThreadYAML decodes it strictly and EncodeAgentThreadYAML writes it back in canonical form so +// loading and saving a thread file changes nothing. +type AgentThread struct { + // Version is the schema version; it must equal AgentThreadFileVersion (1). + Version int `yaml:"version" schema:"required"` + // ID is the stable filename-safe identifier for this thread (stored as .nsgo/threads/.yaml). + ID string `yaml:"id" schema:"required"` + // Title is the thread's display name, automatically set from its first request. + Title string `yaml:"title,omitempty"` + // ScenePath is the slash-separated project-relative scene path this thread belongs to, or empty for Project · no scene. + ScenePath string `yaml:"scenePath,omitempty"` + // SessionID is the external agent's session identifier so follow-up requests continue the same agent session. + SessionID string `yaml:"sessionId,omitempty"` + // CreatedAt is the RFC3339 UTC timestamp when the thread was created. + CreatedAt string `yaml:"createdAt" schema:"required"` + // UpdatedAt is the RFC3339 UTC timestamp of the thread's latest activity. + UpdatedAt string `yaml:"updatedAt" schema:"required"` + // Requests lists the thread's requests in chronological order (oldest first, latest last). + Requests []AgentThreadRequest `yaml:"requests,omitempty"` +} + +// Clone returns a deep copy of t. +func (t *AgentThread) Clone() *AgentThread { + if t == nil { + return nil + } + cp := *t + if len(t.Requests) > 0 { + cp.Requests = make([]AgentThreadRequest, len(t.Requests)) + for i, r := range t.Requests { + rc := r + rc.Files = slices.Clone(r.Files) + rc.Objects = slices.Clone(r.Objects) + if len(r.Steps) > 0 { + rc.Steps = make([]AgentThreadStep, len(r.Steps)) + for j, st := range r.Steps { + sc := st + sc.Objects = slices.Clone(st.Objects) + sc.Files = slices.Clone(st.Files) + rc.Steps[j] = sc + } + } + cp.Requests[i] = rc + } + } + return &cp +} + +// AgentSendRequest describes a request submitted to the active agent thread via SendAgentRequestWith. +type AgentSendRequest struct { + Prompt string + Title string + SessionID string + Reply string + Outcome AgentThreadOutcome + ChangesTotal int + ChangesKept int + Files []string + Objects []string + Detail string + HistoryStep string + HistoryIndex int + Steps []AgentThreadStep +} + +// AgentThreadListItem is one selectable row inside an AgentThreadGroup in the thread switcher. +type AgentThreadListItem struct { + ID string + Title string + ScenePath string + SessionID string + Meta string + Current bool + UpdatedAt string +} + +// AgentThreadGroup is one scene (or Project · no scene) section in the thread switcher. +type AgentThreadGroup struct { + ScenePath string + Heading string + OpenScene bool + Project bool + Threads []AgentThreadListItem +} + +// AgentContextItem describes one item listed under "The agent reads these with every request:". +type AgentContextItem struct { + ID string + Label string + Primary bool + Locked bool +} + +// AgentObjectAttribution identifies the agent thread request that last changed an object, +// displayed in the Inspector footer ("Changed in ‘…’ · 2 min ago"). +type AgentObjectAttribution struct { + ThreadID string + ThreadTitle string + RequestID string + RequestTitle string + ScenePath string + Timestamp string + AgeLabel string +} + +// AgentHistorySelection identifies the step focused when "Open this step in History" is clicked. +type AgentHistorySelection struct { + ThreadID string + RequestID string + StepID string +} + +// AgentHistoryEntry is one item in the History timeline (agent steps and manual undo commands). +type AgentHistoryEntry struct { + ID string + Kind string // "agent", "person", "saved" + Title string + Meta string + ThreadID string + RequestID string + StepID string + Timestamp string + Highlighted bool +} + +type agentThreadsState struct { + threads []*AgentThread + activeThreadID string + draftThread *AgentThread // unsaved empty thread for the current scene or project + switcherOpen bool + switcherQuery string + expandedRequestID string + selectedHistoryStep AgentHistorySelection + threadSeq uint64 + reqSeq uint64 + stepSeq uint64 + rev uint64 +} + +const ( + fixAgentThread = "write an agent thread as version: 1 with id, createdAt, updatedAt, and valid requests/steps" + fixAgentThreadVersion = "set version: 1" + fixAgentThreadYAMLRef = "write values directly without YAML anchors, aliases or merge keys" +) + +// ParseAgentThreadYAML strictly decodes and validates a versioned agent thread YAML document, +// refusing unknown fields, duplicate keys, YAML anchors/aliases/merge keys, trailing YAML +// documents, and unsupported versions. +func ParseAgentThreadYAML(data []byte) (*AgentThread, error) { + t, err := parseAgentThread(data) + if err != nil { + return nil, loaderr.Locate(err, "", data, fixAgentThread) + } + return t, nil +} + +func parseAgentThread(data []byte) (*AgentThread, error) { + if len(bytes.TrimSpace(data)) == 0 { + return nil, errors.New("editor: empty agent thread document") + } + var root yaml.Node + if err := yaml.Unmarshal(data, &root); err != nil { + return nil, fmt.Errorf("editor: agent thread: %w", err) + } + if root.Kind != yaml.DocumentNode || len(root.Content) == 0 || root.Content[0].Kind != yaml.MappingNode { + return nil, errors.New("editor: agent thread must be a YAML mapping") + } + if err := checkDuplicateYAMLKeys(root.Content[0]); err != nil { + return nil, fmt.Errorf("editor: agent thread: %w", err) + } + if err := checkThreadNoYAMLRefs(root.Content[0]); err != nil { + return nil, err + } + + dec := yaml.NewDecoder(bytes.NewReader(data)) + dec.KnownFields(true) + var t AgentThread + if err := dec.Decode(&t); err != nil { + if errors.Is(err, io.EOF) { + return nil, errors.New("editor: empty agent thread document") + } + return nil, fmt.Errorf("editor: agent thread: %w", err) + } + var extra any + if err := dec.Decode(&extra); err != io.EOF { + if err == nil { + return nil, errors.New("editor: agent thread: unexpected trailing YAML document") + } + return nil, fmt.Errorf("editor: agent thread: %w", err) + } + if err := ValidateAgentThread(&t); err != nil { + return nil, err + } + return &t, nil +} + +func checkThreadNoYAMLRefs(n *yaml.Node) error { + if n == nil { + return nil + } + if n.Anchor != "" { + return loaderr.Errorf("", fixAgentThreadYAMLRef, "editor: agent thread must not use YAML anchor &%s", n.Anchor) + } + if n.Kind == yaml.AliasNode { + return loaderr.Errorf("", fixAgentThreadYAMLRef, "editor: agent thread must not use YAML alias *%s", n.Value) + } + if n.Kind == yaml.MappingNode { + for i := 0; i+1 < len(n.Content); i += 2 { + k := n.Content[i] + if k.Tag == "!!merge" || k.Value == "<<" { + return loaderr.Errorf("", fixAgentThreadYAMLRef, "editor: agent thread must not use YAML merge key <<") + } + } + } + for _, child := range n.Content { + if err := checkThreadNoYAMLRefs(child); err != nil { + return err + } + } + return nil +} + +func validAgentThreadFileID(id string) bool { + if id == "" || len(id) > 128 || id == "." || id == ".." { + return false + } + for _, r := range id { + if !((r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == '.') { + return false + } + } + return true +} + +func validThreadRelPath(p string) bool { + if p == "" || strings.ContainsRune(p, '\\') || strings.HasPrefix(p, "/") { + return false + } + if strings.TrimSpace(p) != p || strings.IndexFunc(p, unicode.IsControl) >= 0 { + return false + } + clean := path.Clean(p) + if clean != p || clean == "." || clean == ".." || strings.HasPrefix(clean, "../") { + return false + } + return true +} + +// ValidateAgentThread checks that t conforms to version 1 of the agent thread schema. +func ValidateAgentThread(t *AgentThread) error { + if t == nil { + return errors.New("editor: agent thread: nil document") + } + switch t.Version { + case AgentThreadFileVersion: + case 0: + return loaderr.Errorf("version", fixAgentThreadVersion, "editor: agent thread is missing version (want %d)", AgentThreadFileVersion) + default: + return loaderr.Errorf("version", fixAgentThreadVersion, "editor: unsupported agent thread version %d (want %d)", t.Version, AgentThreadFileVersion) + } + if !validAgentThreadFileID(t.ID) { + return loaderr.Errorf("id", "use a filename-safe thread id containing letters, digits, '-', '_' or '.'", "editor: invalid agent thread id %q", t.ID) + } + if t.ScenePath != "" && !validThreadRelPath(t.ScenePath) { + return loaderr.Errorf("scenePath", "use a slash-separated project-relative scene path", "editor: invalid thread scenePath %q", t.ScenePath) + } + if strings.IndexFunc(t.SessionID, unicode.IsControl) >= 0 { + return loaderr.Errorf("sessionId", "remove control characters from sessionId", "editor: invalid thread sessionId") + } + if _, err := time.Parse(time.RFC3339, t.CreatedAt); err != nil { + return loaderr.Errorf("createdAt", "format createdAt as RFC3339 UTC timestamp", "editor: invalid thread createdAt %q: %v", t.CreatedAt, err) + } + if _, err := time.Parse(time.RFC3339, t.UpdatedAt); err != nil { + return loaderr.Errorf("updatedAt", "format updatedAt as RFC3339 UTC timestamp", "editor: invalid thread updatedAt %q: %v", t.UpdatedAt, err) + } + seenReq := make(map[string]bool, len(t.Requests)) + for i, r := range t.Requests { + prefix := fmt.Sprintf("requests[%d]", i) + if !validAgentThreadFileID(r.ID) { + return loaderr.Errorf(prefix+".id", "use a valid request id", "editor: invalid request id %q", r.ID) + } + if seenReq[r.ID] { + return loaderr.Errorf(prefix+".id", "give every request a unique id", "editor: duplicate request id %q", r.ID) + } + seenReq[r.ID] = true + if strings.TrimSpace(r.Prompt) == "" { + return loaderr.Errorf(prefix+".prompt", "provide a non-empty prompt", "editor: %s prompt must not be empty", prefix) + } + if _, err := time.Parse(time.RFC3339, r.CreatedAt); err != nil { + return loaderr.Errorf(prefix+".createdAt", "format createdAt as RFC3339 UTC timestamp", "editor: %s invalid createdAt %q: %v", prefix, r.CreatedAt, err) + } + if r.UpdatedAt != "" { + if _, err := time.Parse(time.RFC3339, r.UpdatedAt); err != nil { + return loaderr.Errorf(prefix+".updatedAt", "format updatedAt as RFC3339 UTC timestamp", "editor: %s invalid updatedAt %q: %v", prefix, r.UpdatedAt, err) + } + } + if !r.Outcome.Valid() { + return loaderr.Errorf(prefix+".outcome", "set outcome to pending, kept, or reverted", "editor: %s invalid outcome %q", prefix, r.Outcome) + } + if r.ChangesTotal < 0 || r.ChangesKept < 0 || r.ChangesKept > r.ChangesTotal { + return loaderr.Errorf(prefix+".changesKept", "keep 0 <= changesKept <= changesTotal", "editor: %s invalid change counts (%d of %d)", prefix, r.ChangesKept, r.ChangesTotal) + } + if r.HistoryIndex < 0 { + return loaderr.Errorf(prefix+".historyIndex", "use a non-negative historyIndex", "editor: %s invalid historyIndex %d", prefix, r.HistoryIndex) + } + for fi, f := range r.Files { + if !validThreadRelPath(f) { + return loaderr.Errorf(fmt.Sprintf("%s.files[%d]", prefix, fi), "use a slash-separated project-relative path", "editor: %s invalid file path %q", prefix, f) + } + } + seenStep := make(map[string]bool, len(r.Steps)) + for j, st := range r.Steps { + sp := fmt.Sprintf("%s.steps[%d]", prefix, j) + if !validAgentThreadFileID(st.ID) { + return loaderr.Errorf(sp+".id", "use a valid step id", "editor: invalid step id %q", st.ID) + } + if seenStep[st.ID] { + return loaderr.Errorf(sp+".id", "give every step in a request a unique id", "editor: duplicate step id %q", st.ID) + } + seenStep[st.ID] = true + if strings.TrimSpace(st.Label) == "" { + return loaderr.Errorf(sp+".label", "provide a non-empty step label", "editor: %s label must not be empty", sp) + } + if !st.Status.Valid() { + return loaderr.Errorf(sp+".status", "set status to pending, running, done, or failed", "editor: %s invalid status %q", sp, st.Status) + } + if st.HistoryIndex < 0 { + return loaderr.Errorf(sp+".historyIndex", "use a non-negative historyIndex", "editor: %s invalid historyIndex %d", sp, st.HistoryIndex) + } + for fi, f := range st.Files { + if !validThreadRelPath(f) { + return loaderr.Errorf(fmt.Sprintf("%s.files[%d]", sp, fi), "use a slash-separated project-relative path", "editor: %s invalid file path %q", sp, f) + } + } + } + } + return nil +} + +// EncodeAgentThreadYAML validates t and encodes it as deterministic 2-space YAML prefixed with +// AgentThreadSchemaComment so loading and saving changes nothing. +func EncodeAgentThreadYAML(t *AgentThread) ([]byte, error) { + if err := ValidateAgentThread(t); err != nil { + return nil, err + } + var buf bytes.Buffer + buf.WriteString(AgentThreadSchemaComment) + buf.WriteByte('\n') + enc := yaml.NewEncoder(&buf) + enc.SetIndent(2) + if err := enc.Encode(t); err != nil { + _ = enc.Close() + return nil, fmt.Errorf("editor: encode agent thread: %w", err) + } + if err := enc.Close(); err != nil { + return nil, fmt.Errorf("editor: encode agent thread: %w", err) + } + return buf.Bytes(), nil +} + +// LoadAgentThreadFile reads and strictly parses an agent thread YAML file at filePath. +func LoadAgentThreadFile(filePath string) (*AgentThread, error) { + info, err := os.Stat(filePath) + if err != nil { + return nil, err + } + if info.Size() > maxAgentThreadBytes { + return nil, fmt.Errorf("editor: agent thread %s exceeds %d byte limit", filePath, maxAgentThreadBytes) + } + data, err := os.ReadFile(filePath) + if err != nil { + return nil, err + } + t, err := ParseAgentThreadYAML(data) + if err != nil { + return nil, loaderr.WithFile(err, filePath) + } + return t, nil +} + +// SaveAgentThreadFile encodes t and atomically writes it to filePath, creating parent directories if needed. +func SaveAgentThreadFile(filePath string, t *AgentThread) error { + data, err := EncodeAgentThreadYAML(t) + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(filePath), 0o755); err != nil { + return err + } + return writeFileAtomic(filePath, data) +} + +func (e *Editor) agentThreadsRoot() (string, bool) { + if e == nil || e.Project == nil || e.ProjectPath == "" { + return "", false + } + return filepath.Dir(e.ProjectPath), true +} + +// verifyPathWithinProject ensures candidate (and any existing parent inside root) does not escape root via symlinks. +func verifyPathWithinProject(root, candidate string) error { + absRoot, err := filepath.Abs(root) + if err != nil { + return err + } + realRoot := absRoot + if r, err := filepath.EvalSymlinks(absRoot); err == nil { + realRoot = r + } + absCand, err := filepath.Abs(candidate) + if err != nil { + return err + } + rel, err := filepath.Rel(absRoot, absCand) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return fmt.Errorf("editor: path %q leaves project root", candidate) + } + // Walk upward until we hit an existing directory/file and verify its real path stays inside realRoot. + cur := absCand + for { + if info, err := os.Lstat(cur); err == nil { + if info.Mode()&os.ModeSymlink != 0 { + resolved, rerr := filepath.EvalSymlinks(cur) + if rerr != nil { + return fmt.Errorf("editor: unreadable symlink %q: %w", cur, rerr) + } + rrel, rerr := filepath.Rel(realRoot, resolved) + if rerr != nil || rrel == ".." || strings.HasPrefix(rrel, ".."+string(filepath.Separator)) { + return fmt.Errorf("editor: symlink %q points outside project root", cur) + } + } + resolved, rerr := filepath.EvalSymlinks(cur) + if rerr == nil { + rrel, rerr := filepath.Rel(realRoot, resolved) + if rerr != nil || rrel == ".." || strings.HasPrefix(rrel, ".."+string(filepath.Separator)) { + return fmt.Errorf("editor: path %q resolves outside project root", cur) + } + } + break + } + parent := filepath.Dir(cur) + if parent == cur { + break + } + cur = parent + } + return nil +} + +func (e *Editor) persistAgentThread(t *AgentThread) error { + root, ok := e.agentThreadsRoot() + if !ok || t == nil { + return nil + } + nsgoDir := filepath.Join(root, ".nsgo") + threadsDir := filepath.Join(root, filepath.FromSlash(AgentThreadsDir)) + target := filepath.Join(threadsDir, t.ID+".yaml") + if err := verifyPathWithinProject(root, target); err != nil { + return err + } + if err := os.MkdirAll(threadsDir, 0o755); err != nil { + return err + } + // Ensure .nsgo/.gitignore ignores threads so .nsgo/threads/ stays out of version control. + ignore := filepath.Join(nsgoDir, ".gitignore") + if _, err := os.Lstat(ignore); errors.Is(err, fs.ErrNotExist) { + if err := writeFileAtomic(ignore, []byte("*\n")); err != nil { + return err + } + } + return SaveAgentThreadFile(target, t) +} + +// loadAgentThreadsForProject loads all valid .nsgo/threads/*.yaml files for the open project +// and selects the open scene's most recent thread (or a fresh draft when the scene has none). +func (e *Editor) loadAgentThreadsForProject() { + if e == nil { + return + } + e.agentThreads.threads = nil + e.agentThreads.activeThreadID = "" + e.agentThreads.draftThread = nil + e.agentThreads.switcherOpen = false + e.agentThreads.switcherQuery = "" + e.agentThreads.expandedRequestID = "" + e.agentThreads.selectedHistoryStep = AgentHistorySelection{} + e.agentThreads.rev++ + + root, ok := e.agentThreadsRoot() + if !ok { + e.syncAgentThreadForOpenScene() + return + } + threadsDir := filepath.Join(root, filepath.FromSlash(AgentThreadsDir)) + if err := verifyPathWithinProject(root, threadsDir); err != nil { + e.syncAgentThreadForOpenScene() + return + } + entries, err := os.ReadDir(threadsDir) + if err != nil { + e.syncAgentThreadForOpenScene() + return + } + loaded := make([]*AgentThread, 0, len(entries)) + seen := make(map[string]bool, len(entries)) + for _, de := range entries { + if de.IsDir() { + continue + } + name := de.Name() + if !strings.HasSuffix(name, ".yaml") && !strings.HasSuffix(name, ".yml") { + continue + } + // Skip background task queue files (*.thread.yaml) owned by tasks.go. + if strings.HasSuffix(name, ".thread.yaml") { + continue + } + full := filepath.Join(threadsDir, name) + if err := verifyPathWithinProject(root, full); err != nil { + continue + } + t, err := LoadAgentThreadFile(full) + if err != nil || seen[t.ID] { + continue + } + seen[t.ID] = true + loaded = append(loaded, t) + } + sortAgentThreadsRecentFirst(loaded) + e.agentThreads.threads = loaded + e.syncAgentThreadForOpenScene() +} + +func (e *Editor) resetAgentThreadsForDemo() { + if e == nil { + return + } + e.agentThreads.threads = nil + e.agentThreads.activeThreadID = "" + e.agentThreads.draftThread = nil + e.agentThreads.switcherOpen = false + e.agentThreads.switcherQuery = "" + e.agentThreads.expandedRequestID = "" + e.agentThreads.selectedHistoryStep = AgentHistorySelection{} + e.agentThreads.rev++ + e.syncAgentThreadForOpenScene() +} + +func (e *Editor) currentThreadScenePath() string { + if e == nil { + return "" + } + if e.ScenePath != "" { + return e.ScenePath + } + return "" +} + +// syncAgentThreadForOpenScene ensures the active thread belongs to the currently open scene: +// opening or switching to a scene enters its most recent thread (or a fresh empty draft thread +// for that scene) and never carries another scene's thread along. +func (e *Editor) syncAgentThreadForOpenScene() { + if e == nil { + return + } + scenePath := e.currentThreadScenePath() + e.agentThreads.switcherOpen = false + e.agentThreads.expandedRequestID = "" + + // Keep the currently active persisted thread only if it already belongs to this scene. + if cur := e.findPersistedAgentThread(e.agentThreads.activeThreadID); cur != nil && cur.ScenePath == scenePath { + e.agentThreads.draftThread = nil + e.agentThreads.rev++ + return + } + // Otherwise enter the open scene's most recent thread. + if latest := e.mostRecentThreadForScene(scenePath); latest != nil { + e.agentThreads.activeThreadID = latest.ID + e.agentThreads.draftThread = nil + e.agentThreads.rev++ + return + } + // No thread yet for this scene: start a fresh empty draft scoped to it. + e.agentThreads.draftThread = e.makeDraftThread(scenePath) + e.agentThreads.activeThreadID = e.agentThreads.draftThread.ID + e.agentThreads.rev++ +} + +func (e *Editor) makeDraftThread(scenePath string) *AgentThread { + now := e.now().UTC().Format(time.RFC3339) + id := e.nextAgentThreadID(scenePath) + return &AgentThread{ + Version: AgentThreadFileVersion, + ID: id, + ScenePath: scenePath, + CreatedAt: now, + UpdatedAt: now, + } +} + +func (e *Editor) nextAgentThreadID(scenePath string) string { + prefix := "project" + if scenePath != "" { + base := sceneDisplaySlug(scenePath) + if base != "" { + prefix = base + } + } + for { + e.agentThreads.threadSeq++ + cand := fmt.Sprintf("%s-%03d", prefix, e.agentThreads.threadSeq) + if e.findPersistedAgentThread(cand) == nil { + if e.agentThreads.draftThread == nil || e.agentThreads.draftThread.ID != cand { + return cand + } + } + } +} + +func (e *Editor) nextAgentRequestID(t *AgentThread) string { + for { + e.agentThreads.reqSeq++ + cand := fmt.Sprintf("req-%03d", e.agentThreads.reqSeq) + dup := false + if t != nil { + for _, r := range t.Requests { + if r.ID == cand { + dup = true + break + } + } + } + if !dup { + return cand + } + } +} + +func (e *Editor) nextAgentStepID(r *AgentThreadRequest) string { + for { + e.agentThreads.stepSeq++ + cand := fmt.Sprintf("step-%03d", e.agentThreads.stepSeq) + dup := false + if r != nil { + for _, st := range r.Steps { + if st.ID == cand { + dup = true + break + } + } + } + if !dup { + return cand + } + } +} + +func (e *Editor) findPersistedAgentThread(id string) *AgentThread { + if e == nil || id == "" { + return nil + } + for _, t := range e.agentThreads.threads { + if t.ID == id { + return t + } + } + return nil +} + +func (e *Editor) mostRecentThreadForScene(scenePath string) *AgentThread { + var best *AgentThread + for _, t := range e.agentThreads.threads { + if t.ScenePath != scenePath { + continue + } + if best == nil || compareThreadsRecentFirst(t, best) < 0 { + best = t + } + } + return best +} + +func compareThreadsRecentFirst(a, b *AgentThread) int { + ta, erra := time.Parse(time.RFC3339, a.UpdatedAt) + tb, errb := time.Parse(time.RFC3339, b.UpdatedAt) + if erra == nil && errb == nil { + if ta.After(tb) { + return -1 + } + if ta.Before(tb) { + return 1 + } + } else if a.UpdatedAt != b.UpdatedAt { + return strings.Compare(b.UpdatedAt, a.UpdatedAt) + } + return strings.Compare(a.ID, b.ID) +} + +func sortAgentThreadsRecentFirst(list []*AgentThread) { + slices.SortFunc(list, compareThreadsRecentFirst) +} + +// SetAgentMCPConnected updates the live MCP connection status shown in the Agent panel header. +func (e *Editor) SetAgentMCPConnected(connected bool, label string) { + if e == nil { + return + } + name := cmp.Or(strings.TrimSpace(label), "MCP") + if connected { + e.NotifyAgentMCPConnected(AgentClientInfo{ + ID: "mcp-local", + Name: name, + DisplayName: name, + Transport: "stdio", + }) + } else { + e.NotifyAgentMCPDisconnected("mcp-local", "") + } + e.agentThreads.rev++ +} + +// AgentThreads returns a deep-copied snapshot of all persisted threads, most recently updated first. +func (e *Editor) AgentThreads() []*AgentThread { + if e == nil || len(e.agentThreads.threads) == 0 { + return nil + } + sorted := slices.Clone(e.agentThreads.threads) + sortAgentThreadsRecentFirst(sorted) + out := make([]*AgentThread, len(sorted)) + for i, t := range sorted { + out[i] = t.Clone() + } + return out +} + +// AgentThread returns a deep copy of the thread with id (persisted or active draft), or nil. +func (e *Editor) AgentThread(id string) *AgentThread { + if e == nil || id == "" { + return nil + } + if t := e.findPersistedAgentThread(id); t != nil { + return t.Clone() + } + if e.agentThreads.draftThread != nil && e.agentThreads.draftThread.ID == id { + return e.agentThreads.draftThread.Clone() + } + return nil +} + +// ActiveAgentThread returns a deep copy of the currently active thread (creating an empty draft +// for the open scene on demand when none exists yet). +func (e *Editor) ActiveAgentThread() *AgentThread { + if e == nil { + return nil + } + if t := e.findPersistedAgentThread(e.agentThreads.activeThreadID); t != nil { + return t.Clone() + } + if e.agentThreads.draftThread != nil { + return e.agentThreads.draftThread.Clone() + } + e.agentThreads.draftThread = e.makeDraftThread(e.currentThreadScenePath()) + e.agentThreads.activeThreadID = e.agentThreads.draftThread.ID + return e.agentThreads.draftThread.Clone() +} + +// NewAgentThread starts a new empty thread for the currently open scene (⌘N) and activates it. +func (e *Editor) NewAgentThread() *AgentThread { + if e == nil { + return nil + } + return e.newAgentThreadForScene(e.currentThreadScenePath()) +} + +// NewProjectAgentThread starts a new empty project-level thread (Project · no scene) and activates it. +func (e *Editor) NewProjectAgentThread() *AgentThread { + if e == nil { + return nil + } + return e.newAgentThreadForScene("") +} + +func (e *Editor) newAgentThreadForScene(scenePath string) *AgentThread { + draft := e.makeDraftThread(scenePath) + e.agentThreads.draftThread = draft + e.agentThreads.activeThreadID = draft.ID + e.agentThreads.switcherOpen = false + e.agentThreads.switcherQuery = "" + e.agentThreads.expandedRequestID = "" + e.agentThreads.rev++ + e.notify() + return draft.Clone() +} + +// SelectAgentThread switches to thread id. When id belongs to a different scene in the open +// project, SelectAgentThread opens or activates that scene's tab before entering thread id. +func (e *Editor) SelectAgentThread(id string) error { + if e == nil { + return errors.New("editor: nil editor") + } + t := e.findPersistedAgentThread(id) + if t == nil { + if e.agentThreads.draftThread != nil && e.agentThreads.draftThread.ID == id { + e.agentThreads.activeThreadID = id + e.agentThreads.switcherOpen = false + e.agentThreads.expandedRequestID = "" + e.agentThreads.rev++ + e.notify() + return nil + } + return fmt.Errorf("editor: agent thread %q not found", id) + } + if t.ScenePath != "" && t.ScenePath != e.ScenePath && e.Project != nil { + if err := e.OpenScene(t.ScenePath); err != nil { + return err + } + } + e.agentThreads.activeThreadID = t.ID + e.agentThreads.draftThread = nil + e.agentThreads.switcherOpen = false + e.agentThreads.expandedRequestID = "" + e.agentThreads.rev++ + e.notify() + return nil +} + +// AgentSwitcherOpen reports whether the thread switcher popover is open. +func (e *Editor) AgentSwitcherOpen() bool { + return e != nil && e.agentThreads.switcherOpen +} + +// SetAgentSwitcherOpen opens or closes the thread switcher popover. +func (e *Editor) SetAgentSwitcherOpen(open bool) { + if e == nil || e.agentThreads.switcherOpen == open { + return + } + e.agentThreads.switcherOpen = open + if !open { + e.agentThreads.switcherQuery = "" + } + e.agentThreads.rev++ + e.notify() +} + +// ToggleAgentSwitcher toggles the thread switcher popover. +func (e *Editor) ToggleAgentSwitcher() { + if e == nil { + return + } + e.SetAgentSwitcherOpen(!e.agentThreads.switcherOpen) +} + +// AgentSwitcherQuery returns the active search filter inside the thread switcher popover. +func (e *Editor) AgentSwitcherQuery() string { + if e == nil { + return "" + } + return e.agentThreads.switcherQuery +} + +// SetAgentSwitcherQuery updates the thread switcher search filter. +func (e *Editor) SetAgentSwitcherQuery(q string) { + if e == nil || e.agentThreads.switcherQuery == q { + return + } + e.agentThreads.switcherQuery = q + e.agentThreads.rev++ + e.notify() +} + +// ExpandedAgentRequestID returns the ID of the folded earlier request currently expanded, or "". +func (e *Editor) ExpandedAgentRequestID() string { + if e == nil { + return "" + } + return e.agentThreads.expandedRequestID +} + +// SetExpandedAgentRequestID expands reqID (or collapses all folded requests when empty). +func (e *Editor) SetExpandedAgentRequestID(reqID string) { + if e == nil || e.agentThreads.expandedRequestID == reqID { + return + } + e.agentThreads.expandedRequestID = reqID + e.agentThreads.rev++ + e.notify() +} + +// ToggleAgentRequestExpanded expands reqID if collapsed, or collapses it if already expanded. +func (e *Editor) ToggleAgentRequestExpanded(reqID string) { + if e == nil { + return + } + if e.agentThreads.expandedRequestID == reqID { + e.SetExpandedAgentRequestID("") + } else { + e.SetExpandedAgentRequestID(reqID) + } +} + +// JumpToLatestAgentRequest collapses any expanded earlier request and focuses the latest request. +func (e *Editor) JumpToLatestAgentRequest() { + if e == nil { + return + } + if e.agentThreads.expandedRequestID == "" { + return + } + e.agentThreads.expandedRequestID = "" + e.agentThreads.rev++ + e.notify() +} + +// SendAgentRequest appends a new request to the active thread (naming an unnamed thread after +// its first request), persists the thread to .nsgo/threads/.yaml when a project is open, +// and invokes Editor.OnSendAgentRequest if set. +func (e *Editor) SendAgentRequest(prompt string) (*AgentThreadRequest, error) { + return e.SendAgentRequestWith(AgentSendRequest{Prompt: prompt}) +} + +// SendAgentRequestWith appends a configured request to the active thread, persists it to +// .nsgo/threads/.yaml when a project is open, and invokes Editor.OnSendAgentRequest if set. +func (e *Editor) SendAgentRequestWith(in AgentSendRequest) (*AgentThreadRequest, error) { + if e == nil { + return nil, errors.New("editor: nil editor") + } + prompt := strings.TrimSpace(in.Prompt) + if prompt == "" { + return nil, errors.New("editor: agent request prompt must not be empty") + } + now := e.now().UTC().Format(time.RFC3339) + + t := e.findPersistedAgentThread(e.agentThreads.activeThreadID) + promoted := false + if t == nil { + if e.agentThreads.draftThread != nil { + t = e.agentThreads.draftThread + } else { + t = e.makeDraftThread(e.currentThreadScenePath()) + } + promoted = true + } + + title := strings.TrimSpace(in.Title) + if title == "" { + title = deriveThreadTitle(prompt) + } + if t.Title == "" { + t.Title = title + } + if in.SessionID != "" { + t.SessionID = in.SessionID + } + outcome := in.Outcome + if outcome == "" { + outcome = AgentThreadOutcomePending + } + if !outcome.Valid() { + return nil, fmt.Errorf("editor: invalid agent request outcome %q", outcome) + } + changesTotal := max(in.ChangesTotal, 0) + changesKept := in.ChangesKept + if changesKept < 0 { + changesKept = 0 + } + if changesKept > changesTotal { + changesKept = changesTotal + } + if outcome == AgentThreadOutcomeKept && changesTotal > 0 && changesKept == 0 { + changesKept = changesTotal + } + + req := AgentThreadRequest{ + ID: e.nextAgentRequestID(t), + Title: title, + Prompt: prompt, + CreatedAt: now, + UpdatedAt: now, + Reply: strings.TrimSpace(in.Reply), + Outcome: outcome, + ChangesTotal: changesTotal, + ChangesKept: changesKept, + Files: dedupeSortedStrings(in.Files), + Objects: dedupePreserveOrder(in.Objects), + Detail: strings.TrimSpace(in.Detail), + HistoryStep: strings.TrimSpace(in.HistoryStep), + HistoryIndex: max(in.HistoryIndex, 0), + } + for _, st := range in.Steps { + sc := st + if sc.ID == "" { + sc.ID = e.nextAgentStepID(&req) + } + if sc.Status == "" { + sc.Status = AgentThreadStepDone + } + sc.Objects = dedupePreserveOrder(sc.Objects) + sc.Files = dedupeSortedStrings(sc.Files) + req.Objects = mergeUniquePreserveOrder(req.Objects, sc.Objects) + req.Files = dedupeSortedStrings(append(req.Files, sc.Files...)) + req.Steps = append(req.Steps, sc) + } + t.Requests = append(t.Requests, req) + t.UpdatedAt = now + if promoted { + e.agentThreads.threads = append(e.agentThreads.threads, t) + e.agentThreads.draftThread = nil + } + sortAgentThreadsRecentFirst(e.agentThreads.threads) + e.agentThreads.activeThreadID = t.ID + e.agentThreads.expandedRequestID = "" + e.composerDraft = "" + + if err := e.persistAgentThread(t); err != nil { + return nil, err + } + e.agentThreads.rev++ + e.Status = "Sent request to agent: " + title + e.notify() + + if e.OnSendAgentRequest != nil { + e.OnSendAgentRequest(t.Clone(), req) + } + out := req + return &out, nil +} + +// SetAgentThreadSessionID records the external agent's session ID on threadID and persists it, +// so follow-up requests continue the same external agent session. +func (e *Editor) SetAgentThreadSessionID(threadID, sessionID string) error { + if e == nil { + return errors.New("editor: nil editor") + } + if strings.IndexFunc(sessionID, unicode.IsControl) >= 0 { + return errors.New("editor: sessionId must not contain control characters") + } + t := e.findPersistedAgentThread(threadID) + if t == nil { + if e.agentThreads.draftThread != nil && e.agentThreads.draftThread.ID == threadID { + e.agentThreads.draftThread.SessionID = sessionID + e.agentThreads.rev++ + e.notify() + return nil + } + return fmt.Errorf("editor: agent thread %q not found", threadID) + } + t.SessionID = sessionID + if err := e.persistAgentThread(t); err != nil { + return err + } + e.agentThreads.rev++ + e.notify() + return nil +} + +// RecordAgentStep appends or updates a step on requestID in threadID, merges its Objects/Files +// onto the request for Inspector attribution, and persists the thread. +func (e *Editor) RecordAgentStep(threadID, requestID string, step AgentThreadStep) error { + if e == nil { + return errors.New("editor: nil editor") + } + t := e.findPersistedAgentThread(threadID) + if t == nil { + return fmt.Errorf("editor: agent thread %q not found", threadID) + } + reqIdx := -1 + for i := range t.Requests { + if t.Requests[i].ID == requestID { + reqIdx = i + break + } + } + if reqIdx < 0 { + return fmt.Errorf("editor: request %q not found in thread %q", requestID, threadID) + } + r := &t.Requests[reqIdx] + if strings.TrimSpace(step.Label) == "" { + return errors.New("editor: step label must not be empty") + } + if step.Status == "" { + step.Status = AgentThreadStepDone + } + if !step.Status.Valid() { + return fmt.Errorf("editor: invalid step status %q", step.Status) + } + if step.ID == "" { + step.ID = e.nextAgentStepID(r) + } + step.Objects = dedupePreserveOrder(step.Objects) + step.Files = dedupeSortedStrings(step.Files) + + updated := false + for i := range r.Steps { + if r.Steps[i].ID == step.ID { + r.Steps[i] = step + updated = true + break + } + } + if !updated { + r.Steps = append(r.Steps, step) + } + r.Objects = mergeUniquePreserveOrder(r.Objects, step.Objects) + r.Files = dedupeSortedStrings(append(r.Files, step.Files...)) + if step.HistoryStep != "" && r.HistoryStep == "" { + r.HistoryStep = step.HistoryStep + } + if step.HistoryIndex > 0 { + r.HistoryIndex = step.HistoryIndex + } + now := e.now().UTC().Format(time.RFC3339) + r.UpdatedAt = now + t.UpdatedAt = now + sortAgentThreadsRecentFirst(e.agentThreads.threads) + if err := e.persistAgentThread(t); err != nil { + return err + } + e.agentThreads.rev++ + e.notify() + return nil +} + +// UpdateAgentRequestOutcome updates a request's review outcome ("pending", "kept", "reverted"), +// change counts, detail summary, and optional agent reply, and persists the thread. +func (e *Editor) UpdateAgentRequestOutcome(threadID, requestID string, outcome AgentThreadOutcome, kept, total int, detail, reply string) error { + if e == nil { + return errors.New("editor: nil editor") + } + if !outcome.Valid() { + return fmt.Errorf("editor: invalid outcome %q", outcome) + } + t := e.findPersistedAgentThread(threadID) + if t == nil { + return fmt.Errorf("editor: agent thread %q not found", threadID) + } + for i := range t.Requests { + if t.Requests[i].ID != requestID { + continue + } + r := &t.Requests[i] + r.Outcome = outcome + if total >= 0 { + r.ChangesTotal = total + } + if kept >= 0 { + r.ChangesKept = min(kept, r.ChangesTotal) + } + if detail != "" { + r.Detail = strings.TrimSpace(detail) + } + if reply != "" { + r.Reply = strings.TrimSpace(reply) + } + now := e.now().UTC().Format(time.RFC3339) + r.UpdatedAt = now + t.UpdatedAt = now + sortAgentThreadsRecentFirst(e.agentThreads.threads) + if err := e.persistAgentThread(t); err != nil { + return err + } + e.agentThreads.rev++ + e.notify() + return nil + } + return fmt.Errorf("editor: request %q not found in thread %q", requestID, threadID) +} + +// KeepAgentRequest marks requestID in threadID as kept (keeping all proposed changes). +func (e *Editor) KeepAgentRequest(threadID, requestID string) error { + t := e.findPersistedAgentThread(threadID) + if t == nil { + return fmt.Errorf("editor: agent thread %q not found", threadID) + } + for _, r := range t.Requests { + if r.ID == requestID { + return e.UpdateAgentRequestOutcome(threadID, requestID, AgentThreadOutcomeKept, r.ChangesTotal, r.ChangesTotal, "", "") + } + } + return fmt.Errorf("editor: request %q not found in thread %q", requestID, threadID) +} + +// RevertAgentRequest marks requestID in threadID as reverted (kept 0 changes). +func (e *Editor) RevertAgentRequest(threadID, requestID string) error { + t := e.findPersistedAgentThread(threadID) + if t == nil { + return fmt.Errorf("editor: agent thread %q not found", threadID) + } + for _, r := range t.Requests { + if r.ID == requestID { + return e.UpdateAgentRequestOutcome(threadID, requestID, AgentThreadOutcomeReverted, 0, r.ChangesTotal, "", "") + } + } + return fmt.Errorf("editor: request %q not found in thread %q", requestID, threadID) +} + +// NoteAgentEditedObjects records object IDs and files modified by an agent edit (for example +// through editormcp's scene_edit) on the active thread's pending latest request when present. +func (e *Editor) NoteAgentEditedObjects(objectIDs, files []string, label string) { + if e == nil || (len(objectIDs) == 0 && len(files) == 0) { + return + } + t := e.findPersistedAgentThread(e.agentThreads.activeThreadID) + if t == nil || len(t.Requests) == 0 { + return + } + if t.ScenePath != "" && e.ScenePath != "" && t.ScenePath != e.ScenePath { + return + } + r := &t.Requests[len(t.Requests)-1] + if r.Outcome != AgentThreadOutcomePending { + return + } + cleanObjs := dedupePreserveOrder(objectIDs) + var cleanFiles []string + for _, f := range files { + if validThreadRelPath(f) { + cleanFiles = append(cleanFiles, f) + } + } + cleanFiles = dedupeSortedStrings(cleanFiles) + r.Objects = mergeUniquePreserveOrder(r.Objects, cleanObjs) + r.Files = dedupeSortedStrings(append(r.Files, cleanFiles...)) + if label != "" { + step := AgentThreadStep{ + ID: e.nextAgentStepID(r), + Label: label, + Status: AgentThreadStepDone, + HistoryStep: label, + HistoryIndex: e.History.Index(), + Objects: cleanObjs, + Files: cleanFiles, + } + r.Steps = append(r.Steps, step) + if r.HistoryStep == "" { + r.HistoryStep = label + } + r.HistoryIndex = e.History.Index() + } + r.ChangesTotal += max(len(cleanObjs), 1) + now := e.now().UTC().Format(time.RFC3339) + r.UpdatedAt = now + t.UpdatedAt = now + sortAgentThreadsRecentFirst(e.agentThreads.threads) + _ = e.persistAgentThread(t) + e.agentThreads.rev++ + e.notify() +} + +// AgentThreadGroups returns persisted threads grouped by: +// 1. the open scene (" · OPEN SCENE"), +// 2. other scenes (""), ordered by most recent thread activity, +// 3. project-level threads with no scene ("PROJECT · NO SCENE"). +// +// When query is non-empty, only threads matching query (case-insensitive substring over title, +// scene name/path, request titles/prompts, or changed files) are returned, omitting empty groups. +func (e *Editor) AgentThreadGroups(query string) []AgentThreadGroup { + if e == nil { + return nil + } + q := strings.TrimSpace(strings.ToLower(query)) + openScene := e.currentThreadScenePath() + now := e.now() + + sorted := slices.Clone(e.agentThreads.threads) + sortAgentThreadsRecentFirst(sorted) + + byScene := make(map[string][]*AgentThread) + var otherScenes []string + for _, t := range sorted { + if q != "" && !threadMatchesQuery(t, q) { + continue + } + if _, exists := byScene[t.ScenePath]; !exists && t.ScenePath != "" && t.ScenePath != openScene { + otherScenes = append(otherScenes, t.ScenePath) + } + byScene[t.ScenePath] = append(byScene[t.ScenePath], t) + } + + makeItems := func(list []*AgentThread) []AgentThreadListItem { + items := make([]AgentThreadListItem, 0, len(list)) + for _, t := range list { + title := t.Title + if title == "" { + title = e.T("threads.newThread") + } + items = append(items, AgentThreadListItem{ + ID: t.ID, + Title: title, + ScenePath: t.ScenePath, + SessionID: t.SessionID, + Meta: e.formatAgentThreadMeta(t, now), + Current: t.ID == e.agentThreads.activeThreadID, + UpdatedAt: t.UpdatedAt, + }) + } + return items + } + + var groups []AgentThreadGroup + if openScene != "" { + if list := byScene[openScene]; len(list) > 0 { + sceneName := strings.ToUpper(e.sceneHeadingName(openScene)) + groups = append(groups, AgentThreadGroup{ + ScenePath: openScene, + Heading: e.T("threads.group.openScene", l10n.Param("scene", sceneName)), + OpenScene: true, + Threads: makeItems(list), + }) + } + } + for _, sp := range otherScenes { + list := byScene[sp] + if len(list) == 0 { + continue + } + groups = append(groups, AgentThreadGroup{ + ScenePath: sp, + Heading: strings.ToUpper(sceneDisplayName(sp)), + Threads: makeItems(list), + }) + } + if list := byScene[""]; len(list) > 0 { + groups = append(groups, AgentThreadGroup{ + ScenePath: "", + Heading: e.T("threads.group.project"), + Project: true, + Threads: makeItems(list), + }) + } + return groups +} + +func threadMatchesQuery(t *AgentThread, q string) bool { + if strings.Contains(strings.ToLower(t.Title), q) || + strings.Contains(strings.ToLower(t.ScenePath), q) || + strings.Contains(strings.ToLower(sceneDisplayName(t.ScenePath)), q) || + strings.Contains(strings.ToLower(t.ID), q) { + return true + } + for _, r := range t.Requests { + if strings.Contains(strings.ToLower(r.Title), q) || + strings.Contains(strings.ToLower(r.Prompt), q) || + strings.Contains(strings.ToLower(r.Detail), q) { + return true + } + for _, f := range r.Files { + if strings.Contains(strings.ToLower(f), q) { + return true + } + } + for _, o := range r.Objects { + if strings.Contains(strings.ToLower(o), q) { + return true + } + } + } + return false +} + +// LastAgentChangeForObject returns the most recent non-reverted agent request that modified +// objectID in the open scene (or a project-level thread), for the Inspector footer link. +func (e *Editor) LastAgentChangeForObject(objectID string) (AgentObjectAttribution, bool) { + if e == nil || objectID == "" { + return AgentObjectAttribution{}, false + } + openScene := e.currentThreadScenePath() + var best AgentObjectAttribution + var bestTime time.Time + found := false + + for _, t := range e.agentThreads.threads { + if openScene != "" && t.ScenePath != "" && t.ScenePath != openScene { + continue + } + for _, r := range t.Requests { + if r.Outcome == AgentThreadOutcomeReverted { + continue + } + if !requestTouchesObject(r, objectID) { + continue + } + ts := cmp.Or(r.UpdatedAt, r.CreatedAt, t.UpdatedAt) + parsed, _ := time.Parse(time.RFC3339, ts) + if !found || parsed.After(bestTime) || (parsed.Equal(bestTime) && ts > best.Timestamp) { + title := cmp.Or(r.Title, t.Title, deriveThreadTitle(r.Prompt)) + best = AgentObjectAttribution{ + ThreadID: t.ID, + ThreadTitle: cmp.Or(t.Title, title), + RequestID: r.ID, + RequestTitle: title, + ScenePath: t.ScenePath, + Timestamp: ts, + AgeLabel: e.formatRelativeAge(ts, e.now()), + } + bestTime = parsed + found = true + } + } + } + return best, found +} + +func requestTouchesObject(r AgentThreadRequest, objectID string) bool { + if slices.Contains(r.Objects, objectID) { + return true + } + for _, st := range r.Steps { + if slices.Contains(st.Objects, objectID) { + return true + } + } + return false +} + +// OpenAgentRequest switches the right rail to the Agent panel, activates threadID (opening its +// scene if needed), and expands requestID when it is folded as an earlier request. +func (e *Editor) OpenAgentRequest(threadID, requestID string) error { + if e == nil { + return errors.New("editor: nil editor") + } + if err := e.SelectAgentThread(threadID); err != nil { + return err + } + t := e.findPersistedAgentThread(threadID) + if e.agent.mode != AgentModeNone { + e.agent.rightTab = RightTabAgent + } + if t != nil && requestID != "" { + latestID := "" + if len(t.Requests) > 0 { + latestID = t.Requests[len(t.Requests)-1].ID + } + if requestID != latestID { + e.agentThreads.expandedRequestID = requestID + } else { + e.agentThreads.expandedRequestID = "" + } + } + e.agentThreads.rev++ + e.notify() + return nil +} + +// OpenHistoryStep opens the right-rail History timeline focused on the given thread request/step +// and invokes Editor.OnOpenHistoryStep when configured. +func (e *Editor) OpenHistoryStep(threadID, requestID, stepID string) error { + if e == nil { + return errors.New("editor: nil editor") + } + sel := AgentHistorySelection{ + ThreadID: threadID, + RequestID: requestID, + StepID: stepID, + } + e.agentThreads.selectedHistoryStep = sel + e.agent.rightTab = RightTabHistory + e.agentThreads.switcherOpen = false + e.agentThreads.rev++ + e.Status = e.T("threads.history.openedStatus") + e.notify() + if e.OnOpenHistoryStep != nil { + e.OnOpenHistoryStep(sel) + } + return nil +} + +// SelectedHistoryStep returns the step currently highlighted in the History view. +func (e *Editor) SelectedHistoryStep() AgentHistorySelection { + if e == nil { + return AgentHistorySelection{} + } + return e.agentThreads.selectedHistoryStep +} + +// AgentHistoryEntries builds the unified timeline for the History panel: +// agent thread steps for the active scene (most recent first), manual undo steps from History, +// and git commit milestones. +func (e *Editor) AgentHistoryEntries() []AgentHistoryEntry { + if e == nil { + return nil + } + now := e.now() + sel := e.agentThreads.selectedHistoryStep + var entries []AgentHistoryEntry + + // Current state marker. + nowMeta := e.T("threads.history.clean") + if e.HasUnsavedChanges() { + nowMeta = e.T("threads.history.unsaved") + } + entries = append(entries, AgentHistoryEntry{ + ID: "now", + Kind: "now", + Title: e.T("threads.history.now"), + Meta: nowMeta, + }) + + // Collect agent thread requests/steps for the open scene (and any explicitly selected thread). + openScene := e.currentThreadScenePath() + for _, t := range e.agentThreads.threads { + if openScene != "" && t.ScenePath != "" && t.ScenePath != openScene && t.ID != sel.ThreadID { + continue + } + for i := len(t.Requests) - 1; i >= 0; i-- { + r := t.Requests[i] + ts := cmp.Or(r.UpdatedAt, r.CreatedAt) + age := e.formatRelativeAge(ts, now) + if len(r.Steps) > 0 { + for j := len(r.Steps) - 1; j >= 0; j-- { + st := r.Steps[j] + hl := sel.ThreadID == t.ID && sel.RequestID == r.ID && (sel.StepID == st.ID || (sel.StepID == "" && j == len(r.Steps)-1)) + meta := e.formatRequestOutcomeShort(r) + " · " + age + entries = append(entries, AgentHistoryEntry{ + ID: t.ID + ":" + r.ID + ":" + st.ID, + Kind: "agent", + Title: e.T("threads.history.agentPrefix", l10n.Param("label", st.Label)), + Meta: meta, + ThreadID: t.ID, + RequestID: r.ID, + StepID: st.ID, + Timestamp: ts, + Highlighted: hl, + }) + } + } else { + hl := sel.ThreadID == t.ID && sel.RequestID == r.ID + entries = append(entries, AgentHistoryEntry{ + ID: t.ID + ":" + r.ID, + Kind: "agent", + Title: e.T("threads.history.agentPrefix", l10n.Param("label", cmp.Or(r.Title, deriveThreadTitle(r.Prompt)))), + Meta: e.formatRequestOutcomeShort(r) + " · " + age, + ThreadID: t.ID, + RequestID: r.ID, + Timestamp: ts, + Highlighted: hl, + }) + } + } + } + + // Include live manual undo stack commands (most recent first). + if e.History != nil { + for i := e.History.cursor - 1; i >= 0; i-- { + lbl := e.History.commands[i].Label() + entries = append(entries, AgentHistoryEntry{ + ID: fmt.Sprintf("undo-%d", i+1), + Kind: "person", + Title: e.T("threads.history.youPrefix", l10n.Param("label", lbl)), + Meta: e.T("threads.history.undoStep", l10n.Param("index", i+1)), + }) + } + for i, m := range e.History.Milestones() { + entries = append(entries, AgentHistoryEntry{ + ID: fmt.Sprintf("milestone-%d", i), + Kind: "saved", + Title: e.T("threads.history.saved"), + Meta: m.Summary, + }) + } + } + + return entries +} + +// AgentAlwaysReadItems returns the context items shown in the empty-thread view and composer +// ("The agent reads these with every request:"). +func (e *Editor) AgentAlwaysReadItems() []AgentContextItem { + var items []AgentContextItem + active := e.ActiveAgentThread() + scenePath := e.currentThreadScenePath() + if active != nil && active.ScenePath != "" { + scenePath = active.ScenePath + } + if scenePath != "" || (e != nil && e.Doc != nil && e.Doc.Name != "") { + name := e.sceneHeadingName(scenePath) + if name == "" && e != nil && e.Doc != nil { + name = e.Doc.Name + } + if name != "" { + items = append(items, AgentContextItem{ + ID: "scene", + Label: e.T("threads.context.wholeScene", l10n.Param("scene", name)), + Primary: true, + }) + } + } + items = append(items, + AgentContextItem{ID: "brief", Label: "brief.yaml", Locked: true}, + AgentContextItem{ID: "rules", Label: "AGENTS.md", Locked: true}, + AgentContextItem{ID: "viewport", Label: e.T("threads.context.viewportImage")}, + ) + return items +} + +// AgentBriefSuggestions returns up to three starter prompts for the empty-thread view, +// extracted from the open project's brief.yaml (refusing symlinks outside the project root) +// or falling back to scene-aware starter suggestions. +func (e *Editor) AgentBriefSuggestions() []string { + if root, ok := e.agentThreadsRoot(); ok { + if got := loadBriefSuggestionsFromDir(root); len(got) > 0 { + return got + } + } + scene := "level_01" + if e != nil { + if s := e.sceneHeadingName(e.currentThreadScenePath()); s != "" { + scene = s + } + } + return []string{ + e.T("threads.suggestion.blockOut", l10n.Param("scene", scene)), + e.T("threads.suggestion.enemyPatrol"), + e.T("threads.suggestion.hud"), + } +} + +func loadBriefSuggestionsFromDir(root string) []string { + briefPath := filepath.Join(root, "brief.yaml") + if err := verifyPathWithinProject(root, briefPath); err != nil { + return nil + } + info, err := os.Stat(briefPath) + if err != nil || info.IsDir() || info.Size() > maxBriefYAMLBytes { + return nil + } + data, err := os.ReadFile(briefPath) + if err != nil { + return nil + } + var doc map[string]any + if err := yaml.Unmarshal(data, &doc); err != nil || len(doc) == 0 { + return nil + } + var out []string + add := func(s string) { + s = strings.TrimSpace(s) + if s == "" || len(out) >= 3 || slices.Contains(out, s) { + return + } + out = append(out, s) + } + extractList := func(v any) { + switch xs := v.(type) { + case []any: + for _, elem := range xs { + switch item := elem.(type) { + case string: + add(item) + case map[string]any: + for _, k := range []string{"prompt", "text", "summary", "title", "goal", "name"} { + if s, ok := item[k].(string); ok && strings.TrimSpace(s) != "" { + add(s) + break + } + } + } + } + case string: + add(xs) + } + } + for _, key := range []string{"suggestions", "tasks", "next", "goals", "milestones", "features"} { + if v, ok := doc[key]; ok { + extractList(v) + } + } + return out +} + +func (e *Editor) formatAgentThreadMeta(t *AgentThread, now time.Time) string { + if t == nil || len(t.Requests) == 0 { + return e.T("threads.meta.empty") + } + last := t.Requests[len(t.Requests)-1] + age := e.formatRelativeAge(cmp.Or(t.UpdatedAt, last.UpdatedAt, last.CreatedAt), now) + + // Project-wide threads with files and no review counts show file names (matching Threads.dc.html: "Mon · game.yaml, knight.prefab.yaml"). + if t.ScenePath == "" && last.ChangesTotal == 0 && len(last.Files) > 0 && last.Outcome != AgentThreadOutcomeReverted { + return age + " · " + formatThreadFilesMeta(last.Files) + } + + switch last.Outcome { + case AgentThreadOutcomePending: + if last.ChangesTotal == 1 { + return age + " · " + e.T("threads.meta.oneChangeToReview") + } + if last.ChangesTotal > 1 { + return age + " · " + e.T("threads.meta.changesToReview", l10n.Param("count", last.ChangesTotal)) + } + return age + " · " + e.T("threads.meta.inProgress") + case AgentThreadOutcomeReverted: + return age + " · " + e.T("threads.meta.reverted") + default: + if last.ChangesTotal > 0 { + return age + " · " + e.T("threads.meta.keptOf", l10n.Param("kept", last.ChangesKept), l10n.Param("total", last.ChangesTotal)) + } + if len(last.Files) > 0 { + return age + " · " + formatThreadFilesMeta(last.Files) + } + return age + " · " + e.T("threads.meta.kept") + } +} + +func (e *Editor) formatRequestOutcomeShort(r AgentThreadRequest) string { + switch r.Outcome { + case AgentThreadOutcomePending: + if r.ChangesTotal == 1 { + return e.T("threads.meta.oneChangeToReview") + } + if r.ChangesTotal > 1 { + return e.T("threads.meta.changesToReview", l10n.Param("count", r.ChangesTotal)) + } + return e.T("threads.meta.inProgress") + case AgentThreadOutcomeReverted: + return e.T("threads.meta.reverted") + default: + if r.ChangesTotal > 0 { + return e.T("threads.meta.keptOf", l10n.Param("kept", r.ChangesKept), l10n.Param("total", r.ChangesTotal)) + } + return e.T("threads.meta.kept") + } +} + +func (e *Editor) formatRelativeAge(rfc3339 string, now time.Time) string { + ts, err := time.Parse(time.RFC3339, rfc3339) + if err != nil { + return e.T("threads.age.now") + } + d := now.Sub(ts) + if d < time.Minute { + return e.T("threads.age.now") + } + if d < time.Hour { + return e.T("threads.age.minutesAgo", l10n.Param("count", int(d/time.Minute))) + } + if d < 24*time.Hour { + return e.T("threads.age.hoursAgo", l10n.Param("count", int(d/time.Hour))) + } + if d < 48*time.Hour { + return e.T("threads.age.yesterday") + } + if d < 7*24*time.Hour { + return ts.UTC().Format("Mon") + } + return ts.UTC().Format("Jan 2") +} + +func formatRequestClockTime(rfc3339 string) string { + ts, err := time.Parse(time.RFC3339, rfc3339) + if err != nil { + return "" + } + return ts.UTC().Format("15:04") +} + +func formatThreadFilesMeta(files []string) string { + if len(files) == 0 { + return "" + } + limit := min(len(files), 3) + parts := make([]string, limit) + for i := range limit { + parts[i] = path.Base(files[i]) + } + return strings.Join(parts, ", ") +} + +func (e *Editor) sceneHeadingName(scenePath string) string { + if scenePath != "" { + return sceneDisplayName(scenePath) + } + if e != nil && e.Doc != nil && strings.TrimSpace(e.Doc.Name) != "" { + return strings.TrimSpace(e.Doc.Name) + } + return "" +} + +func sceneDisplayName(scenePath string) string { + if scenePath == "" { + return "" + } + base := path.Base(scenePath) + for _, suf := range []string{".scene.yaml", ".scene.yml", ".yaml", ".yml"} { + if strings.HasSuffix(base, suf) { + base = strings.TrimSuffix(base, suf) + break + } + } + return base +} + +func sceneDisplaySlug(scenePath string) string { + name := strings.ToLower(sceneDisplayName(scenePath)) + var b strings.Builder + dash := false + for _, r := range name { + if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') { + b.WriteRune(r) + dash = false + } else if !dash && b.Len() > 0 { + b.WriteByte('-') + dash = true + } + } + return strings.TrimSuffix(b.String(), "-") +} + +func deriveThreadTitle(prompt string) string { + line := strings.TrimSpace(prompt) + if idx := strings.IndexAny(line, "\r\n"); idx >= 0 { + line = strings.TrimSpace(line[:idx]) + } + line = strings.Join(strings.Fields(line), " ") + line = strings.TrimRight(line, ".!?") + const maxRunes = 64 + if utf8.RuneCountInString(line) > maxRunes { + rs := []rune(line) + line = strings.TrimSpace(string(rs[:maxRunes-1])) + "…" + } + return line +} + +func dedupePreserveOrder(xs []string) []string { + if len(xs) == 0 { + return nil + } + seen := make(map[string]bool, len(xs)) + out := make([]string, 0, len(xs)) + for _, s := range xs { + s = strings.TrimSpace(s) + if s == "" || seen[s] { + continue + } + seen[s] = true + out = append(out, s) + } + if len(out) == 0 { + return nil + } + return out +} + +func mergeUniquePreserveOrder(a, b []string) []string { + if len(b) == 0 { + return a + } + out := slices.Clone(a) + seen := make(map[string]bool, len(a)+len(b)) + for _, s := range out { + seen[s] = true + } + for _, s := range b { + s = strings.TrimSpace(s) + if s == "" || seen[s] { + continue + } + seen[s] = true + out = append(out, s) + } + return out +} + +func dedupeSortedStrings(xs []string) []string { + out := dedupePreserveOrder(xs) + slices.Sort(out) + return out +} diff --git a/packages/game/editor/agent_threads_conformance_test.go b/packages/game/editor/agent_threads_conformance_test.go new file mode 100644 index 000000000..291a7cac4 --- /dev/null +++ b/packages/game/editor/agent_threads_conformance_test.go @@ -0,0 +1,17 @@ +package editor_test + +import ( + "testing" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/internal/formattest" +) + +func TestAgentThreadYAMLFormatConformance(t *testing.T) { + formattest.Run(t, formattest.Format[*editor.AgentThread]{ + Doc: "editor#agent-thread", + Decode: editor.ParseAgentThreadYAML, + Encode: editor.EncodeAgentThreadYAML, + Files: []string{"testdata/agent_thread.yaml"}, + }) +} diff --git a/packages/game/editor/agent_threads_test.go b/packages/game/editor/agent_threads_test.go new file mode 100644 index 000000000..a621fe4a9 --- /dev/null +++ b/packages/game/editor/agent_threads_test.go @@ -0,0 +1,580 @@ +package editor_test + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/project" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func writeTwoSceneThreadProject(t *testing.T) (string, string, string) { + t.Helper() + dir := t.TempDir() + scenesDir := filepath.Join(dir, "scenes") + if err := os.MkdirAll(scenesDir, 0o755); err != nil { + t.Fatal(err) + } + level1Doc := &sceneformat.SceneDoc{ + Version: sceneformat.CurrentVersion, + Name: "level_01", + VirtualWidth: 640, + VirtualHeight: 360, + BackgroundColor: "#1a1f2a", + Layers: []sceneformat.LayerDoc{ + { + Name: "actors", + Space: sceneformat.SpaceWorld, + Order: 10, + Objects: []sceneformat.ObjectDoc{ + { + ID: "Door", + Name: "Door", + X: 632, + Y: 356, + Properties: map[string]any{ + "locked": true, + "opens_after_pulls": 2, + }, + }, + { + ID: "lever_01", + Name: "lever_01", + X: 598, + Y: 372, + }, + { + ID: "Knight", + Name: "Knight", + X: 444, + Y: 286, + }, + }, + }, + }, + } + bossDoc := &sceneformat.SceneDoc{ + Version: sceneformat.CurrentVersion, + Name: "boss_room", + VirtualWidth: 640, + VirtualHeight: 360, + BackgroundColor: "#1a1f2a", + Layers: []sceneformat.LayerDoc{ + { + Name: "actors", + Space: sceneformat.SpaceWorld, + Order: 10, + Objects: []sceneformat.ObjectDoc{ + { + ID: "boss_spawn", + Name: "boss_spawn", + X: 320, + Y: 220, + }, + }, + }, + }, + } + l1Bytes, err := sceneformat.Encode(level1Doc) + if err != nil { + t.Fatal(err) + } + bossBytes, err := sceneformat.Encode(bossDoc) + if err != nil { + t.Fatal(err) + } + l1Path := filepath.Join(scenesDir, "level_01.scene.yaml") + bossPath := filepath.Join(scenesDir, "boss_room.scene.yaml") + if err := os.WriteFile(l1Path, l1Bytes, 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(bossPath, bossBytes, 0o644); err != nil { + t.Fatal(err) + } + proj := &project.File{ + Version: project.CurrentVersion, + Name: "dungeon-run", + ID: "dev.nsgo.dungeonrun", + AppVersion: "0.1.0", + Window: project.Window{Width: 640, Height: 360}, + Autoload: &project.Autoload{ + MainScene: "level_01", + Scenes: []project.Entry{ + {Name: "level_01", Path: "scenes/level_01.scene.yaml"}, + {Name: "boss_room", Path: "scenes/boss_room.scene.yaml"}, + }, + }, + } + projBytes, err := project.Encode(proj) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, project.FileName), projBytes, 0o644); err != nil { + t.Fatal(err) + } + briefYAML := `suggestions: + - "Block out level_01 with three platforms and an exit door" + - "Add a slime that patrols the floor and costs the Knight one heart" + - "Set up the HUD: three hearts and a coin counter" +` + if err := os.WriteFile(filepath.Join(dir, "brief.yaml"), []byte(briefYAML), 0o644); err != nil { + t.Fatal(err) + } + return dir, "scenes/level_01.scene.yaml", "scenes/boss_room.scene.yaml" +} + +// #1019 Acceptance 1: A test sends requests in two scenes, switches scenes and sees each scene's own thread; +// after reopening the project the threads and their states are back. +func TestAgentThreadsPerSceneSwitchingPersistenceAndGroups(t *testing.T) { + dir, level1Rel, bossRel := writeTwoSceneThreadProject(t) + + now := time.Date(2026, 11, 26, 14, 20, 0, 0, time.UTC) + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + ed.Now = func() time.Time { return now } + if err := ed.OpenProject(dir); err != nil { + t.Fatalf("OpenProject: %v", err) + } + if ed.ScenePath != level1Rel { + t.Fatalf("initial ScenePath = %q, want %q", ed.ScenePath, level1Rel) + } + + // Initially level_01 has an empty draft thread. + initial := ed.ActiveAgentThread() + if initial == nil || len(initial.Requests) != 0 || initial.ScenePath != level1Rel { + t.Fatalf("initial active thread = %+v, want empty draft for %q", initial, level1Rel) + } + + // Thread 1 in level_01: reverted yesterday. + now = time.Date(2026, 11, 25, 13, 0, 0, 0, time.UTC) + reqRev, err := ed.SendAgentRequestWith(editor.AgentSendRequest{ + Prompt: "Spikes under the plank", + SessionID: "sess-rev", + Outcome: editor.AgentThreadOutcomeReverted, + ChangesTotal: 2, + ChangesKept: 0, + }) + if err != nil { + t.Fatalf("send reverted thread: %v", err) + } + revThreadID := ed.ActiveAgentThread().ID + if reqRev.Outcome != editor.AgentThreadOutcomeReverted { + t.Fatalf("reqRev.Outcome = %q", reqRev.Outcome) + } + + // Thread 2 in level_01: 1 h ago, kept 5 of 6. + ed.NewAgentThread() + now = time.Date(2026, 11, 26, 13, 20, 0, 0, time.UTC) + if _, err := ed.SendAgentRequestWith(editor.AgentSendRequest{ + Prompt: "Slimes and a coin trail", + SessionID: "sess-slimes", + Outcome: editor.AgentThreadOutcomeKept, + ChangesTotal: 6, + ChangesKept: 5, + Objects: []string{"Knight"}, + }); err != nil { + t.Fatalf("send slimes thread: %v", err) + } + + // Thread 3 (most recent) in level_01: now, 3 changes to review, continuing one session ID. + ed.NewAgentThread() + now = time.Date(2026, 11, 26, 14, 18, 0, 0, time.UTC) + if _, err := ed.SendAgentRequestWith(editor.AgentSendRequest{ + Prompt: "Door opens after two lever pulls", + SessionID: "sess-door-42", + Outcome: editor.AgentThreadOutcomeKept, + ChangesTotal: 3, + ChangesKept: 3, + Objects: []string{"Door", "lever_01"}, + Detail: "Door.locked, Door.opens_after_pulls, lever_01.pulls", + }); err != nil { + t.Fatalf("send door req 1: %v", err) + } + now = time.Date(2026, 11, 26, 14, 20, 0, 0, time.UTC) + if _, err := ed.SendAgentRequestWith(editor.AgentSendRequest{ + Prompt: "Open the door with a short rumble and a small camera shake.", + Outcome: editor.AgentThreadOutcomePending, + ChangesTotal: 3, + Files: []string{"prefabs/door.prefab.yaml", "scenes/level_01.scene.yaml"}, + Objects: []string{"Door"}, + }); err != nil { + t.Fatalf("send door req 2: %v", err) + } + doorThread := ed.ActiveAgentThread() + if doorThread.Title != "Door opens after two lever pulls" { + t.Fatalf("doorThread.Title = %q, want named after first request", doorThread.Title) + } + if doorThread.SessionID != "sess-door-42" { + t.Fatalf("doorThread.SessionID = %q, want sess-door-42 preserved across requests", doorThread.SessionID) + } + + // Project-wide thread (Project · no scene). + ed.NewProjectAgentThread() + now = time.Date(2026, 11, 23, 10, 0, 0, 0, time.UTC) + if _, err := ed.SendAgentRequestWith(editor.AgentSendRequest{ + Prompt: "Double jump for the Knight", + Outcome: editor.AgentThreadOutcomeKept, + Files: []string{"game.yaml", "prefabs/knight.prefab.yaml"}, + }); err != nil { + t.Fatalf("send project thread: %v", err) + } + projectThreadID := ed.ActiveAgentThread().ID + + // Switch to boss_room: switching scenes MUST NOT carry level_01's or project's thread along. + if err := ed.OpenScene(bossRel); err != nil { + t.Fatalf("OpenScene(boss_room): %v", err) + } + bossDraft := ed.ActiveAgentThread() + if bossDraft == nil || bossDraft.ScenePath != bossRel || len(bossDraft.Requests) != 0 { + t.Fatalf("switching to boss_room carried thread along: %+v", bossDraft) + } + + // Send a request in boss_room. + now = time.Date(2026, 11, 25, 14, 0, 0, 0, time.UTC) + if _, err := ed.SendAgentRequestWith(editor.AgentSendRequest{ + Prompt: "Torches around the boss arena", + SessionID: "sess-boss-99", + Outcome: editor.AgentThreadOutcomeKept, + ChangesTotal: 4, + ChangesKept: 4, + Objects: []string{"boss_spawn"}, + }); err != nil { + t.Fatalf("send boss thread: %v", err) + } + bossThreadID := ed.ActiveAgentThread().ID + + // Switch back to level_01: enters level_01's most recent thread automatically! + now = time.Date(2026, 11, 26, 14, 20, 0, 0, time.UTC) + if err := ed.OpenScene(level1Rel); err != nil { + t.Fatalf("OpenScene(level_01): %v", err) + } + if got := ed.ActiveAgentThread(); got == nil || got.ID != doorThread.ID { + t.Fatalf("returning to level_01 active thread = %+v, want %q", got, doorThread.ID) + } + + // Switch back to boss_room: enters boss_room's own thread! + if err := ed.OpenScene(bossRel); err != nil { + t.Fatalf("OpenScene(boss_room) again: %v", err) + } + if got := ed.ActiveAgentThread(); got == nil || got.ID != bossThreadID { + t.Fatalf("returning to boss_room active thread = %+v, want %q", got, bossThreadID) + } + + // Switch back to level_01 and verify switcher groups & states match Threads.dc.html! + if err := ed.OpenScene(level1Rel); err != nil { + t.Fatal(err) + } + groups := ed.AgentThreadGroups("") + if len(groups) != 3 { + t.Fatalf("AgentThreadGroups count = %d, want 3 (open scene, boss_room, project): %+v", len(groups), groups) + } + if groups[0].Heading != "LEVEL_01 · OPEN SCENE" || !groups[0].OpenScene || len(groups[0].Threads) != 3 { + t.Fatalf("group[0] = %+v", groups[0]) + } + if got := groups[0].Threads[0].Meta; got != "now · 3 changes to review" { + t.Fatalf("door thread meta = %q, want %q", got, "now · 3 changes to review") + } + if got := groups[0].Threads[1].Meta; got != "1 h ago · kept 5 of 6" { + t.Fatalf("slimes thread meta = %q, want %q", got, "1 h ago · kept 5 of 6") + } + if got := groups[0].Threads[2].Meta; got != "yesterday · reverted" { + t.Fatalf("reverted thread meta = %q, want %q", got, "yesterday · reverted") + } + if groups[1].Heading != "BOSS_ROOM" || len(groups[1].Threads) != 1 || groups[1].Threads[0].Meta != "yesterday · kept 4 of 4" { + t.Fatalf("group[1] = %+v", groups[1]) + } + if groups[2].Heading != "PROJECT · NO SCENE" || !groups[2].Project || len(groups[2].Threads) != 1 || groups[2].Threads[0].ID != projectThreadID { + t.Fatalf("group[2] = %+v", groups[2]) + } + if !strings.Contains(groups[2].Threads[0].Meta, "game.yaml, knight.prefab.yaml") { + t.Fatalf("project thread meta = %q, want files list", groups[2].Threads[0].Meta) + } + + // Search filters groups cleanly. + filtered := ed.AgentThreadGroups("torches") + if len(filtered) != 1 || filtered[0].Heading != "BOSS_ROOM" || len(filtered[0].Threads) != 1 { + t.Fatalf("AgentThreadGroups(torches) = %+v", filtered) + } + + // Verify .nsgo/threads/.yaml files and .nsgo/.gitignore exist on disk. + gitignoreBytes, err := os.ReadFile(filepath.Join(dir, ".nsgo", ".gitignore")) + if err != nil || strings.TrimSpace(string(gitignoreBytes)) != "*" { + t.Fatalf(".nsgo/.gitignore = %q err=%v, want *", string(gitignoreBytes), err) + } + if _, err := os.Stat(filepath.Join(dir, ".nsgo", "threads", doorThread.ID+".yaml")); err != nil { + t.Fatalf("missing persisted door thread file: %v", err) + } + if _, err := os.Stat(filepath.Join(dir, ".nsgo", "threads", revThreadID+".yaml")); err != nil { + t.Fatalf("missing persisted reverted thread file: %v", err) + } + + // Reopen project in a brand-new Editor instance: all threads, session IDs, and states must be back! + ed2, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + ed2.Now = func() time.Time { return now } + if err := ed2.OpenProject(dir); err != nil { + t.Fatalf("reopen OpenProject: %v", err) + } + gotDoor := ed2.ActiveAgentThread() + if gotDoor == nil || gotDoor.ID != doorThread.ID || gotDoor.SessionID != "sess-door-42" || len(gotDoor.Requests) != 2 { + t.Fatalf("after reopen active thread = %+v, want %q with session sess-door-42 and 2 requests", gotDoor, doorThread.ID) + } + reopenedGroups := ed2.AgentThreadGroups("") + if len(reopenedGroups) != 3 { + t.Fatalf("reopened groups = %d, want 3", len(reopenedGroups)) + } + if reopenedGroups[0].Threads[0].Meta != "now · 3 changes to review" || + reopenedGroups[0].Threads[1].Meta != "1 h ago · kept 5 of 6" || + reopenedGroups[0].Threads[2].Meta != "yesterday · reverted" { + t.Fatalf("reopened level_01 metas = %+v", reopenedGroups[0].Threads) + } + if reopenedGroups[1].Threads[0].SessionID != "sess-boss-99" { + t.Fatalf("reopened boss thread sessionId = %q, want sess-boss-99", reopenedGroups[1].Threads[0].SessionID) + } + + // Selecting another scene's thread from the switcher opens that scene and activates that thread. + if err := ed2.SelectAgentThread(bossThreadID); err != nil { + t.Fatalf("SelectAgentThread(boss): %v", err) + } + if ed2.ScenePath != bossRel || ed2.ActiveAgentThread().ID != bossThreadID { + t.Fatalf("after SelectAgentThread(boss): ScenePath=%q active=%+v", ed2.ScenePath, ed2.ActiveAgentThread()) + } +} + +// #1019 Acceptance 2 + Folding + History link + Jump to latest + Empty thread + ⌘N UI flow. +func TestAgentThreadsInspectorFooterFoldingHistoryEmptyAndShortcut(t *testing.T) { + dir, _, _ := writeTwoSceneThreadProject(t) + + now := time.Date(2026, 11, 26, 14, 20, 0, 0, time.UTC) + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + ed.Now = func() time.Time { return now } + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + + // Record 2 requests on level_01: req1 touched Door 2 min ago, req2 touched lever_01 now, req3 reverted on Door. + now = time.Date(2026, 11, 26, 14, 18, 0, 0, time.UTC) + req1, err := ed.SendAgentRequestWith(editor.AgentSendRequest{ + Title: "Door opens after two lever pulls", + Prompt: "Keep the door shut until the lever is pulled twice, then let it open.", + Outcome: editor.AgentThreadOutcomeKept, + ChangesTotal: 3, + ChangesKept: 3, + Objects: []string{"Door", "lever_01"}, + Detail: "Door.locked, Door.opens_after_pulls, lever_01.pulls", + Steps: []editor.AgentThreadStep{ + {ID: "s1", Label: "Set Door.opens_after_pulls = 2", Status: editor.AgentThreadStepDone, Objects: []string{"Door"}}, + }, + }) + if err != nil { + t.Fatal(err) + } + now = time.Date(2026, 11, 26, 14, 19, 0, 0, time.UTC) + if _, err := ed.SendAgentRequestWith(editor.AgentSendRequest{ + Title: "Door opens over 0.6 s", + Prompt: "Slow the door opening down to 0.6 s.", + Outcome: editor.AgentThreadOutcomeReverted, + ChangesTotal: 1, + Objects: []string{"Door"}, + }); err != nil { + t.Fatal(err) + } + now = time.Date(2026, 11, 26, 14, 20, 0, 0, time.UTC) + if _, err := ed.SendAgentRequestWith(editor.AgentSendRequest{ + Title: "Click sound on the lever", + Prompt: "Add a click sound when the lever moves.", + Outcome: editor.AgentThreadOutcomePending, + ChangesTotal: 2, + Files: []string{"scenes/level_01.scene.yaml"}, + Objects: []string{"lever_01"}, + }); err != nil { + t.Fatal(err) + } + threadID := ed.ActiveAgentThread().ID + + // Select Door in Inspector: reverted req2 MUST NOT override req1 attribution! + ed.SelectObject("Door") + attr, ok := ed.LastAgentChangeForObject("Door") + if !ok || attr.RequestID != req1.ID || attr.RequestTitle != "Door opens after two lever pulls" || attr.AgeLabel != "2 min ago" { + t.Fatalf("LastAgentChangeForObject(Door) = (%+v, %v)", attr, ok) + } + + var openedHistory editor.AgentHistorySelection + ed.OnOpenHistoryStep = func(sel editor.AgentHistorySelection) { + openedHistory = sel + } + + 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"})) + + // Inspector footer names the request that last changed Door and opens it when pressed. + footerText := app.Find("id:inspector-thread-footer-text").Text + wantFooter := "Changed in “Door opens after two lever pulls” · 2 min ago" + if footerText != wantFooter { + t.Fatalf("inspector-thread-footer-text = %q, want %q", footerText, wantFooter) + } + app.Press("id:inspector-thread-footer") + + if ed.RightRailTab() != editor.RightRailAgent { + t.Fatalf("after clicking inspector footer, RightRailTab = %v, want RightRailAgent", ed.RightRailTab()) + } + if ed.ActiveAgentThread().ID != threadID || ed.ExpandedAgentRequestID() != req1.ID { + t.Fatalf("after clicking inspector footer: thread=%q expanded=%q, want %q / %q", ed.ActiveAgentThread().ID, ed.ExpandedAgentRequestID(), threadID, req1.ID) + } + if !app.Exists("id:agent-request-detail-"+req1.ID) || !app.Exists("id:agent-jump-latest") { + t.Fatal("expanded earlier request detail and Jump to latest pill should both be visible") + } + + // Click "Open this step in History" from the expanded request. + app.Press("id:agent-open-history-" + req1.ID) + if ed.RightRailTab() != editor.RightRailHistory { + t.Fatalf("after Open in History, RightRailTab = %v, want RightRailHistory", ed.RightRailTab()) + } + if openedHistory.ThreadID != threadID || openedHistory.RequestID != req1.ID || openedHistory.StepID != "s1" { + t.Fatalf("openedHistory = %+v, want thread=%q req=%q step=s1", openedHistory, threadID, req1.ID) + } + if !app.Exists("id:agent-history-panel") { + t.Fatal("History panel did not render") + } + + // Return to thread from History and press "Jump to latest". + app.Press("id:history-open-thread-" + req1.ID) + if ed.RightRailTab() != editor.RightRailAgent || ed.ExpandedAgentRequestID() != req1.ID { + t.Fatalf("back to thread failed: tab=%v expanded=%q", ed.RightRailTab(), ed.ExpandedAgentRequestID()) + } + app.Press("id:agent-jump-latest") + if ed.ExpandedAgentRequestID() != "" || app.Exists("id:agent-jump-latest") { + t.Fatalf("Jump to latest did not collapse expanded request: expanded=%q", ed.ExpandedAgentRequestID()) + } + + // Press ⌘N in Agent scope to start a new empty thread (without opening Start Screen!). + app.Key("meta+n") + if ed.StartScreenOpen() { + t.Fatal("meta+n inside Agent panel unexpectedly opened Start Screen instead of creating a new thread") + } + if active := ed.ActiveAgentThread(); active == nil || len(active.Requests) != 0 { + t.Fatalf("after meta+n, active thread = %+v, want new empty thread", active) + } + if !app.Exists("id:agent-empty-thread") || !app.Exists("id:agent-empty-context-scene") || !app.Exists("id:agent-empty-context-brief") || !app.Exists("id:agent-empty-context-rules") || !app.Exists("id:agent-empty-context-viewport") { + t.Fatal("empty thread view missing expected always-read context chips") + } + if got := app.Find("id:agent-empty-context-scene").Children[0].Text; got != "level_01 · whole scene" { + t.Fatalf("scene context chip = %q, want level_01 · whole scene", got) + } + // Brief suggestions loaded from brief.yaml. + if !app.Exists("id:agent-brief-suggestion-0") { + t.Fatal("brief suggestion 0 missing") + } + suggText := app.Find("id:agent-brief-suggestion-0").Children[0].Text + if suggText != "Block out level_01 with three platforms and an exit door" { + t.Fatalf("brief suggestion 0 = %q", suggText) + } + + // Clicking a suggestion sends it and names the thread after it! + app.Press("id:agent-brief-suggestion-0") + if active := ed.ActiveAgentThread(); active == nil || active.Title != "Block out level_01 with three platforms and an exit door" || len(active.Requests) != 1 { + t.Fatalf("after clicking suggestion: active thread = %+v", active) + } +} + +func TestAgentThreadBriefSymlinkOutsideProjectRejected(t *testing.T) { + dir, _, _ := writeTwoSceneThreadProject(t) + outsideDir := t.TempDir() + outsideBrief := filepath.Join(outsideDir, "secret.yaml") + if err := os.WriteFile(outsideBrief, []byte("suggestions:\n - \"LEAKED_OUTSIDE_SUGGESTION\"\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Remove(filepath.Join(dir, "brief.yaml")); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outsideBrief, filepath.Join(dir, "brief.yaml")); err != nil { + t.Skipf("symlink unsupported: %v", err) + } + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + for _, s := range ed.AgentBriefSuggestions() { + if strings.Contains(s, "LEAKED_OUTSIDE_SUGGESTION") { + t.Fatalf("AgentBriefSuggestions read symlinked brief.yaml outside project root: %q", s) + } + } +} + +func TestAgentThreadYAMLStrictValidationAndRoundTrip(t *testing.T) { + valid := &editor.AgentThread{ + Version: editor.AgentThreadFileVersion, + ID: "door-lever-pulls", + Title: "Door opens after two lever pulls", + ScenePath: "scenes/level_01.scene.yaml", + SessionID: "sess_01", + CreatedAt: "2026-11-26T13:40:00Z", + UpdatedAt: "2026-11-26T14:18:00Z", + Requests: []editor.AgentThreadRequest{ + { + ID: "req-001", + Title: "Door opens after two lever pulls", + Prompt: "Keep the door shut until the lever is pulled twice.", + CreatedAt: "2026-11-26T13:40:00Z", + UpdatedAt: "2026-11-26T13:41:00Z", + Outcome: editor.AgentThreadOutcomeKept, + ChangesTotal: 3, + ChangesKept: 3, + Files: []string{"scenes/level_01.scene.yaml"}, + Objects: []string{"Door"}, + }, + }, + } + enc1, err := editor.EncodeAgentThreadYAML(valid) + if err != nil { + t.Fatalf("EncodeAgentThreadYAML: %v", err) + } + parsed, err := editor.ParseAgentThreadYAML(enc1) + if err != nil { + t.Fatalf("ParseAgentThreadYAML: %v", err) + } + enc2, err := editor.EncodeAgentThreadYAML(parsed) + if err != nil { + t.Fatalf("EncodeAgentThreadYAML round-trip: %v", err) + } + if !bytes.Equal(enc1, enc2) { + t.Fatalf("round-trip mismatch:\n--- enc1 ---\n%s\n--- enc2 ---\n%s", enc1, enc2) + } + + badCases := map[string]string{ + "empty": "", + "missingVer": "id: t1\ncreatedAt: \"2026-11-26T13:40:00Z\"\nupdatedAt: \"2026-11-26T13:40:00Z\"\n", + "wrongVer": "version: 99\nid: t1\ncreatedAt: \"2026-11-26T13:40:00Z\"\nupdatedAt: \"2026-11-26T13:40:00Z\"\n", + "unknownField": "version: 1\nid: t1\nextra: true\ncreatedAt: \"2026-11-26T13:40:00Z\"\nupdatedAt: \"2026-11-26T13:40:00Z\"\n", + "badID": "version: 1\nid: ../escape\ncreatedAt: \"2026-11-26T13:40:00Z\"\nupdatedAt: \"2026-11-26T13:40:00Z\"\n", + "badScenePath": "version: 1\nid: t1\nscenePath: ../outside.yaml\ncreatedAt: \"2026-11-26T13:40:00Z\"\nupdatedAt: \"2026-11-26T13:40:00Z\"\n", + "dupKey": "version: 1\nid: t1\nid: t2\ncreatedAt: \"2026-11-26T13:40:00Z\"\nupdatedAt: \"2026-11-26T13:40:00Z\"\n", + "anchor": "version: 1\nid: &a t1\ncreatedAt: \"2026-11-26T13:40:00Z\"\nupdatedAt: \"2026-11-26T13:40:00Z\"\n", + "keptGtTotal": "version: 1\nid: t1\ncreatedAt: \"2026-11-26T13:40:00Z\"\nupdatedAt: \"2026-11-26T13:40:00Z\"\nrequests:\n - id: r1\n prompt: hi\n createdAt: \"2026-11-26T13:40:00Z\"\n outcome: kept\n changesTotal: 2\n changesKept: 3\n", + "badOutcome": "version: 1\nid: t1\ncreatedAt: \"2026-11-26T13:40:00Z\"\nupdatedAt: \"2026-11-26T13:40:00Z\"\nrequests:\n - id: r1\n prompt: hi\n createdAt: \"2026-11-26T13:40:00Z\"\n outcome: mystery\n", + "trailingDoc": "version: 1\nid: t1\ncreatedAt: \"2026-11-26T13:40:00Z\"\nupdatedAt: \"2026-11-26T13:40:00Z\"\n---\nversion: 1\n", + } + for name, src := range badCases { + if _, err := editor.ParseAgentThreadYAML([]byte(src)); err == nil { + t.Errorf("ParseAgentThreadYAML(%s) succeeded, want error", name) + } + } +} diff --git a/packages/game/editor/agent_threads_ui.go b/packages/game/editor/agent_threads_ui.go new file mode 100644 index 000000000..e60e9f1ea --- /dev/null +++ b/packages/game/editor/agent_threads_ui.go @@ -0,0 +1,1291 @@ +package editor + +import ( + "cmp" + "fmt" + + "github.com/nsgo-dev/game/packages/game/l10n" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/icons/lucide" + "github.com/nsgo-dev/nsgo/ui" +) + +// AgentThreadsView renders the Agent panel for the open scene's thread: status chip, thread +// switcher header (with ⌘N new thread and grouped scene switcher popover), folded earlier +// requests with History links, Jump to latest pill, empty-thread view with always-read context +// and brief suggestions, live turns, and the prompt composer. +func AgentThreadsView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { + return AgentPanelView(cx, ed, rev) +} + +func agentThreadHeaderBar(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], switcherBtnRef *core.Ref) core.Node { + newShortcut := FormatShortcut("mod+n", cx.Env().OS()) + return core.View{ + TestID: "agent-thread-header", + StyleFunc: func() core.Style { + p := ed.SpecPalette(cx) + return core.Style{ + Height: core.Pt(specHeaderHeight), + FlexShrink: 0, + Direction: core.Row, + AlignItems: core.AlignCenter, + Padding: core.Symmetric(0, 8), + Gap: 4, + Background: p.Panel, + Borders: core.Edges{Bottom: 1}, + BorderColor: p.Line, + } + }, + Children: []core.Node{ + core.View{ + Ref: switcherBtnRef, + TestID: "agent-thread-switcher-trigger", + Role: core.RoleButton, + LabelFunc: func() string { + _ = rev.Get() + active := ed.ActiveAgentThread() + title := ed.T("threads.newThread") + if active != nil && active.Title != "" { + title = active.Title + } + return ed.T("threads.switcherTriggerLabel", l10n.Param("title", title)) + }, + StyleFunc: func() core.Style { + p := ed.SpecPalette(cx) + bg := core.Color(0) + if ed.AgentSwitcherOpen() { + bg = p.LineRaised + } + return core.Style{ + Height: core.Pt(specButtonHeight), + FlexGrow: 1, + FlexBasis: core.Pt(0), + MinWidth: core.Pt(0), + Direction: core.Row, + AlignItems: core.AlignCenter, + Padding: core.Symmetric(0, 8), + Gap: 8, + CornerRadius: specRadiusButton, + Background: bg, + Hover: &core.Style{Background: specHoverOverlay(p)}, + FocusVisible: p.FocusRing(2), + } + }, + OnPress: func(core.PressEvent) { + ed.ToggleAgentSwitcher() + }, + Children: []core.Node{ + specDynamicIcon(func() *core.SVG { return lucide.MessageSquare() }, 14, func() core.Color { + return ed.SpecPalette(cx).TextFaint + }), + core.Text{ + TestID: "agent-thread-title", + ContentFunc: func() string { + _ = rev.Get() + if active := ed.ActiveAgentThread(); active != nil && active.Title != "" { + return active.Title + } + return ed.T("threads.newThread") + }, + MaxLines: 1, + StyleFunc: func() core.Style { + p := ed.SpecPalette(cx) + return core.Style{ + FlexGrow: 1, + FlexShrink: 1, + FontSize: 12.5, + FontWeight: core.FontWeightMedium, + Color: p.TextPrimary, + } + }, + }, + specDynamicIcon(func() *core.SVG { + _ = rev.Get() + if ed.AgentSwitcherOpen() { + return lucide.ChevronUp() + } + return lucide.ChevronDown() + }, 12, func() core.Color { + return ed.SpecPalette(cx).TextFaint + }), + }, + }, + ui.Tooltip{ + Text: specShortcutTip(ed.T("threads.newThread"), newShortcut), + Trigger: core.View{ + TestID: "agent-thread-new", + Role: core.RoleButton, + Label: specShortcutTip(ed.T("threads.newThread"), newShortcut), + StyleFunc: func() core.Style { + p := ed.SpecPalette(cx) + return core.Style{ + Width: core.Pt(28), + Height: core.Pt(28), + FlexShrink: 0, + CornerRadius: specRadiusControl, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Hover: &core.Style{Background: specHoverOverlay(p)}, + FocusVisible: p.FocusRing(2), + } + }, + OnPress: func(core.PressEvent) { + ed.NewAgentThread() + }, + Children: []core.Node{ + specDynamicIcon(func() *core.SVG { return lucide.SquarePen() }, 14, func() core.Color { + return ed.SpecPalette(cx).TextMuted + }), + }, + }, + }, + }, + } +} + +func agentThreadSwitcherPopover(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { + newShortcut := FormatShortcut("mod+n", cx.Env().OS()) + groupsMemo := core.NewMemo(cx, func() string { + _ = rev.Get() + return fmt.Sprintf("%d|%s|%s|%v", ed.agentThreads.rev, ed.agentThreads.switcherQuery, ed.agentThreads.activeThreadID, cx.Dark()) + }) + + return core.View{ + TestID: "agent-thread-switcher", + StyleFunc: func() core.Style { + p := ed.SpecPalette(cx) + return core.Style{ + Position: core.Absolute, + Top: core.Pt(4), + Left: core.Pt(8), + Right: core.Pt(8), + Bottom: core.Pt(8), + CornerRadius: specRadiusCard, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + Overflow: core.Hidden, + } + }, + Children: []core.Node{ + core.View{ + StyleFunc: func() core.Style { + p := ed.SpecPalette(cx) + return core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Padding: core.All(8), + Gap: 8, + Borders: core.Edges{Bottom: 1}, + BorderColor: p.LineRaised, + } + }, + Children: []core.Node{ + core.View{ + Style: core.Style{FlexGrow: 1, FlexBasis: core.Pt(0), MinWidth: core.Pt(0)}, + Children: []core.Node{ + ui.Input{ + TestID: "agent-thread-search", + Label: ed.T("threads.searchPlaceholder"), + Placeholder: ed.T("threads.searchPlaceholder"), + Value: func() string { + _ = rev.Get() + return ed.AgentSwitcherQuery() + }, + OnChange: func(v string) { + ed.SetAgentSwitcherQuery(v) + }, + OnFocus: func() { ed.noteTextInputFocus(true) }, + OnBlur: func() { ed.noteTextInputFocus(false) }, + }, + }, + }, + core.View{ + TestID: "agent-thread-new-btn", + Role: core.RoleButton, + Label: specShortcutTip(ed.T("threads.newButton"), newShortcut), + StyleFunc: func() core.Style { + p := ed.SpecPalette(cx) + return core.Style{ + Height: core.Pt(28), + FlexShrink: 0, + Direction: core.Row, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Padding: core.Symmetric(0, 8), + Gap: 6, + CornerRadius: specRadiusControl, + Background: p.LineRaised, + Hover: &core.Style{Background: specHoverOverlay(p)}, + FocusVisible: p.FocusRing(2), + } + }, + OnPress: func(core.PressEvent) { + ed.NewAgentThread() + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("threads.newButton"), + StyleFunc: func() core.Style { + return core.Style{FontSize: 11.5, FontWeight: core.FontWeightMedium, Color: ed.SpecPalette(cx).TextPrimary} + }, + }, + core.Text{ + Content: newShortcut, + StyleFunc: func() core.Style { + return core.Style{FontSize: 11, FontFamily: core.FontMonospace, Color: ed.SpecPalette(cx).TextMuted} + }, + }, + }, + }, + }, + }, + ui.ScrollView{ + Style: core.Style{ + FlexGrow: 1, + FlexBasis: core.Pt(0), + }, + ContentStyle: core.Style{ + Padding: core.Edges{Top: 4, Right: 4, Bottom: 8, Left: 4}, + Gap: 2, + }, + Children: []core.Node{ + core.Dynamic(func(cx *core.Scope) core.Node { + _ = groupsMemo.Get() + p := ed.SpecPalette(cx) + groups := ed.AgentThreadGroups(ed.AgentSwitcherQuery()) + if len(groups) == 0 { + return core.View{ + Style: core.Style{Padding: core.All(12)}, + Children: []core.Node{ + core.Text{ + TestID: "agent-thread-switcher-empty", + Content: ed.T("threads.switcherEmpty"), + Style: core.Style{FontSize: 12, Color: p.TextFaint}, + }, + }, + } + } + var rows []core.Node + for gi, g := range groups { + groupTestID := fmt.Sprintf("agent-thread-group-%d", gi) + rows = append(rows, core.View{ + TestID: groupTestID, + Style: core.Style{Padding: core.Edges{Top: 10, Right: 8, Bottom: 4, Left: 8}}, + Children: []core.Node{ + core.Text{ + Content: g.Heading, + Style: core.Style{ + FontSize: 11, + FontWeight: core.FontWeightSemibold, + LetterSpacing: 0.7, + Color: p.TextFaint, + }, + }, + }, + }) + for _, item := range g.Threads { + it := item + rowBg := core.Color(0) + if it.Current { + rowBg = p.Accent.Fill + } + rows = append(rows, core.View{ + TestID: "agent-thread-item-" + it.ID, + Role: core.RoleButton, + Label: it.Title + " · " + it.Meta, + Style: core.Style{ + Padding: core.All(8), + Gap: 2, + CornerRadius: specRadiusControl, + Background: rowBg, + Hover: &core.Style{Background: specHoverOverlay(p)}, + FocusVisible: p.FocusRing(-2), + }, + OnPress: func(core.PressEvent) { + ed.report(ed.SelectAgentThread(it.ID)) + }, + Children: []core.Node{ + core.Text{ + Content: it.Title, + MaxLines: 1, + Style: core.Style{ + FontSize: 12.5, + FontWeight: core.FontWeightMedium, + Color: p.TextPrimary, + }, + }, + core.Text{ + Content: it.Meta, + MaxLines: 1, + Style: core.Style{ + FontSize: 11.5, + Color: p.TextFaint, + }, + }, + }, + }) + } + } + return core.View{Style: core.Style{Gap: 2}, Children: rows} + }), + }, + }, + core.View{ + TestID: "agent-thread-switcher-footer", + StyleFunc: func() core.Style { + p := ed.SpecPalette(cx) + return core.Style{ + Height: core.Pt(30), + FlexShrink: 0, + Direction: core.Row, + AlignItems: core.AlignCenter, + Padding: core.Symmetric(0, 12), + Borders: core.Edges{Top: 1}, + BorderColor: p.LineRaised, + } + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("threads.storageFooter"), + StyleFunc: func() core.Style { + return core.Style{ + FontSize: 11, + FontFamily: core.FontMonospace, + Color: ed.SpecPalette(cx).TextFaint, + } + }, + }, + }, + }, + }, + } +} + +func agentEmptyThreadBody(cx *core.Scope, ed *Editor, p SpecPalette) core.Node { + items := ed.AgentAlwaysReadItems() + chips := make([]core.Node, 0, len(items)) + for _, it := range items { + bg := core.Color(0) + fg := p.TextFaint + borderW := core.Points(1) + if it.Primary { + bg = p.LineRaised + fg = p.TextPrimary + borderW = 0 + } + chips = append(chips, core.View{ + TestID: "agent-empty-context-" + it.ID, + Style: core.Style{ + Height: core.Pt(22), + Direction: core.Row, + AlignItems: core.AlignCenter, + Padding: core.Symmetric(0, 8), + CornerRadius: specRadiusControl, + Background: bg, + BorderWidth: borderW, + BorderColor: p.LineRaised, + JustifyContent: core.JustifyCenter, + }, + Children: []core.Node{ + core.Text{ + Content: it.Label, + Style: core.Style{ + FontSize: 11.5, + Color: fg, + }, + }, + }, + }) + } + + suggestions := ed.AgentBriefSuggestions() + suggNodes := make([]core.Node, 0, len(suggestions)) + for i, text := range suggestions { + prompt := text + suggNodes = append(suggNodes, core.View{ + TestID: fmt.Sprintf("agent-brief-suggestion-%d", i), + Role: core.RoleButton, + Label: prompt, + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Padding: core.All(12), + Gap: 12, + CornerRadius: specRadiusCard, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + Hover: &core.Style{Background: specHoverOverlay(p)}, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + _, err := ed.SendAgentRequest(prompt) + ed.report(err) + }, + Children: []core.Node{ + core.Text{ + Content: prompt, + Style: core.Style{ + FlexGrow: 1, + FlexShrink: 1, + FontSize: 12.5, + LineHeight: 18, + Color: p.TextSecondary, + }, + }, + specIcon(lucide.ArrowRight, 14, p.TextFaint), + }, + }) + } + + emptyChildren := []core.Node{ + core.View{ + Style: core.Style{Gap: 8}, + Children: []core.Node{ + core.Text{ + TestID: "agent-empty-reads-heading", + Content: ed.T("threads.empty.readsHeading"), + Style: core.Style{ + FontSize: 12.5, + LineHeight: 19, + Color: p.TextSecondary, + }, + }, + core.View{ + Style: core.Style{Direction: core.Row, Wrap: core.Wrap, Gap: 4}, + Children: chips, + }, + }, + }, + core.View{ + Style: core.Style{Gap: 8}, + Children: append([]core.Node{ + core.Text{ + TestID: "agent-empty-brief-heading", + Content: ed.T("threads.empty.fromBrief"), + Style: core.Style{ + FontSize: 11, + FontWeight: core.FontWeightSemibold, + LetterSpacing: 0.7, + Color: p.TextFaint, + }, + }, + }, suggNodes...), + }, + } + if ed.AgentStatus() != AgentStatusConnected { + emptyChildren = append(emptyChildren, agentEmptyStateCard(ed, p)) + } + + return ui.ScrollView{ + TestID: "agent-empty-thread", + Style: core.Style{ + FlexGrow: 1, + FlexBasis: core.Pt(0), + }, + ContentStyle: core.Style{ + Padding: core.Edges{Top: 20, Right: 16, Bottom: 16, Left: 16}, + Gap: 16, + }, + Children: emptyChildren, + } +} + +func agentThreadConversationBody(cx *core.Scope, ed *Editor, p SpecPalette, t *AgentThread, turns []AgentTurn, openReq *AgentOpenRequest, openReqRef *core.Ref) core.Node { + expandedID := ed.ExpandedAgentRequestID() + var nodes []core.Node + if ready := ed.ReadyToReviewTurns(); len(ready) > 0 { + nodes = append(nodes, agentReadyToReviewBanner(ed, p, len(ready))) + } + queued := ed.AgentQueuedRequests() + limitReached := ed.AgentWeeklyLimitReached() + if limitReached { + nodes = append(nodes, agentLimitReachedCard(ed, p)) + if len(queued) > 0 { + nodes = append(nodes, agentQueuedRequestsView(ed, queued, limitReached, p)) + } + } + + earlier := t.Requests[:len(t.Requests)-1] + latest := t.Requests[len(t.Requests)-1] + + if len(earlier) > 0 { + heading := ed.T("threads.earlierRequestsMany", l10n.Param("count", len(earlier))) + if len(earlier) == 1 { + heading = ed.T("threads.earlierRequestsOne") + } + nodes = append(nodes, core.Text{ + TestID: "agent-earlier-requests-heading", + Content: heading, + Style: core.Style{ + FontSize: 11, + FontWeight: core.FontWeightSemibold, + LetterSpacing: 0.7, + Color: p.TextFaint, + Padding: core.Edges{Bottom: 4}, + }, + }) + for _, req := range earlier { + r := req + isOpen := expandedID == r.ID + rowBg := core.Color(0) + if isOpen { + rowBg = p.Raised + } + iconBg := p.Added.Fill + iconFg := p.Added.Fg + iconSVG := lucide.Check + if r.Outcome == AgentThreadOutcomeReverted { + iconBg = p.LineRaised + iconFg = p.TextMuted + iconSVG = lucide.Undo2 + } + meta := ed.formatRequestOutcomeShort(r) + if clk := formatRequestClockTime(r.CreatedAt); clk != "" { + meta += " · " + clk + } + reqTitle := cmp.Or(r.Title, deriveThreadTitle(r.Prompt)) + + nodes = append(nodes, core.View{ + TestID: "agent-request-row-" + r.ID, + Role: core.RoleButton, + Label: reqTitle + " · " + meta, + Style: core.Style{ + Height: core.Pt(specRowHeight), + FlexShrink: 0, + Direction: core.Row, + AlignItems: core.AlignCenter, + Padding: core.Symmetric(0, 8), + Gap: 8, + CornerRadius: specRadiusControl, + Background: rowBg, + Hover: &core.Style{Background: specHoverOverlay(p)}, + FocusVisible: p.FocusRing(-2), + }, + OnPress: func(core.PressEvent) { + ed.ToggleAgentRequestExpanded(r.ID) + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(16), + Height: core.Pt(16), + FlexShrink: 0, + CornerRadius: 8, + Background: iconBg, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + }, + Children: []core.Node{ + specIcon(iconSVG, 10, iconFg), + }, + }, + core.Text{ + Content: reqTitle, + MaxLines: 1, + Style: core.Style{ + FlexGrow: 1, + FlexShrink: 1, + FontSize: 12.5, + Color: p.TextSecondary, + }, + }, + core.Text{ + Content: meta, + MaxLines: 1, + Style: core.Style{ + FlexShrink: 0, + FontSize: 11.5, + Color: p.TextFaint, + }, + }, + }, + }) + + if isOpen { + detailChildren := []core.Node{ + core.Text{ + Content: r.Prompt, + Style: core.Style{ + FontSize: 12.5, + LineHeight: 18, + Color: p.TextSecondary, + }, + }, + } + if r.Detail != "" { + detailChildren = append(detailChildren, core.Text{ + Content: r.Detail, + Style: core.Style{ + FontSize: 11.5, + LineHeight: 17, + Color: p.TextFaint, + }, + }) + } + for _, st := range r.Steps { + step := st + detailChildren = append(detailChildren, core.View{ + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: 6}, + Children: []core.Node{ + agentStepGlyph(p, step.Status), + core.Text{ + Content: step.Label, + MaxLines: 1, + Style: core.Style{ + FlexGrow: 1, + FlexShrink: 1, + FontSize: 11.5, + Color: p.TextMuted, + }, + }, + }, + }) + } + firstStepID := "" + if len(r.Steps) > 0 { + firstStepID = r.Steps[len(r.Steps)-1].ID + } + detailChildren = append(detailChildren, core.View{ + TestID: "agent-open-history-" + r.ID, + Role: core.RoleButton, + Label: ed.T("threads.openInHistory"), + Style: core.Style{ + AlignSelf: core.AlignStart, + Padding: core.Symmetric(2, 0), + CornerRadius: 4, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.report(ed.OpenHistoryStep(t.ID, r.ID, firstStepID)) + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("threads.openInHistory"), + Style: core.Style{ + FontSize: 11.5, + FontWeight: core.FontWeightMedium, + Color: p.Accent.Fg, + }, + }, + }, + }) + nodes = append(nodes, core.View{ + TestID: "agent-request-detail-" + r.ID, + Style: core.Style{ + Margin: core.Edges{Top: 2, Bottom: 6, Left: 24}, + Padding: core.Symmetric(8, 12), + Gap: 5, + CornerRadius: specRadiusButton, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + }, + Children: detailChildren, + }) + } + } + + // Divider between folded earlier requests and the latest request. + nodes = append(nodes, core.View{ + Style: core.Style{ + Height: core.Pt(1), + Background: p.Line, + Margin: core.Symmetric(8, 0), + }, + }) + } + + // Latest request unfolded. + latestNodes := []core.Node{ + core.View{ + TestID: "agent-latest-prompt", + Style: core.Style{ + AlignSelf: core.AlignEnd, + MaxWidth: core.Pt(300), + Padding: core.Symmetric(8, 12), + CornerRadius: specRadiusCard, + Background: p.Accent.Fill, + BorderWidth: 1, + BorderColor: p.LineRaised, + }, + Children: []core.Node{ + core.Text{ + Content: latest.Prompt, + Style: core.Style{ + FontSize: 12.5, + LineHeight: 18, + Color: p.TextPrimary, + }, + }, + }, + }, + } + + if len(latest.Steps) > 0 { + stepNodes := make([]core.Node, 0, len(latest.Steps)) + for _, st := range latest.Steps { + step := st + stepNodes = append(stepNodes, core.View{ + TestID: "agent-step-" + step.ID, + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: 8}, + Children: []core.Node{ + agentStepGlyph(p, step.Status), + core.Text{ + Content: step.Label, + Style: core.Style{ + FlexGrow: 1, + FlexShrink: 1, + FontSize: 12, + Color: p.TextFaint, + }, + }, + }, + }) + } + latestNodes = append(latestNodes, core.View{ + Style: core.Style{Gap: 8}, + Children: stepNodes, + }) + } else if latest.Outcome == AgentThreadOutcomePending { + // <300ms gray placeholder step before the agent reports its first real step. + sceneFile := "scene.yaml" + if t.ScenePath != "" { + sceneFile = t.ScenePath + } + latestNodes = append(latestNodes, core.View{ + TestID: "agent-step-placeholder", + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: 8}, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(14), + Height: core.Pt(14), + CornerRadius: 7, + BorderWidth: 2, + BorderColor: p.TextFaint, + FlexShrink: 0, + }, + }, + core.Text{ + Content: ed.T("threads.readingPlaceholder", l10n.Param("file", sceneFile)), + Style: core.Style{ + FontSize: 12, + Color: p.TextFaint, + }, + }, + }, + }) + } + + if latest.Reply != "" { + latestNodes = append(latestNodes, core.Text{ + TestID: "agent-latest-reply", + Content: latest.Reply, + Style: core.Style{ + FontSize: 12.5, + LineHeight: 19, + Color: p.TextSecondary, + }, + }) + } + + if latest.Outcome == AgentThreadOutcomePending && latest.ChangesTotal > 0 { + summary := ed.T("threads.reviewCard.summary", l10n.Param("changes", latest.ChangesTotal), l10n.Param("files", max(len(latest.Files), 1))) + latestNodes = append(latestNodes, core.View{ + TestID: "agent-latest-review-card", + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Padding: core.Edges{Top: 8, Right: 8, Bottom: 8, Left: 12}, + Gap: 8, + CornerRadius: specRadiusCard, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + }, + Children: []core.Node{ + core.Text{ + Content: summary, + Style: core.Style{ + FlexGrow: 1, + FlexShrink: 1, + FontSize: 12.5, + FontWeight: core.FontWeightMedium, + Color: p.TextPrimary, + }, + }, + core.View{ + TestID: "agent-latest-keep", + Role: core.RoleButton, + Label: ed.T("threads.action.keep"), + Style: core.Style{ + Height: core.Pt(specButtonHeight), + Padding: core.Symmetric(0, 12), + CornerRadius: specRadiusButton, + Background: p.Accent.Fg, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.report(ed.KeepAgentRequest(t.ID, latest.ID)) + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("threads.action.keep"), + Style: core.Style{ + FontSize: 12.5, + FontWeight: core.FontWeightSemibold, + Color: p.Accent.OnFill, + }, + }, + }, + }, + core.View{ + TestID: "agent-latest-revert", + Role: core.RoleButton, + Label: ed.T("threads.action.revert"), + Style: core.Style{ + Height: core.Pt(specButtonHeight), + Padding: core.Symmetric(0, 12), + CornerRadius: specRadiusButton, + Background: p.LineRaised, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Hover: &core.Style{Background: specHoverOverlay(p)}, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.report(ed.RevertAgentRequest(t.ID, latest.ID)) + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("threads.action.revert"), + Style: core.Style{ + FontSize: 12.5, + Color: p.TextSecondary, + }, + }, + }, + }, + }, + }) + } else if latest.Outcome == AgentThreadOutcomeKept || latest.Outcome == AgentThreadOutcomeReverted { + latestNodes = append(latestNodes, core.View{ + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, JustifyContent: core.JustifySpaceBetween, Gap: 8}, + Children: []core.Node{ + core.Text{ + TestID: "agent-latest-outcome", + Content: ed.formatRequestOutcomeShort(latest), + Style: core.Style{FontSize: 11.5, Color: p.TextFaint}, + }, + core.View{ + TestID: "agent-open-history-" + latest.ID, + Role: core.RoleButton, + Label: ed.T("threads.openInHistory"), + Style: core.Style{ + CornerRadius: 4, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + stepID := "" + if len(latest.Steps) > 0 { + stepID = latest.Steps[len(latest.Steps)-1].ID + } + ed.report(ed.OpenHistoryStep(t.ID, latest.ID, stepID)) + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("threads.openInHistory"), + Style: core.Style{FontSize: 11.5, FontWeight: core.FontWeightMedium, Color: p.Accent.Fg}, + }, + }, + }, + }, + }) + } + + nodes = append(nodes, core.View{ + TestID: "agent-latest-request", + Style: core.Style{Gap: 12}, + Children: latestNodes, + }) + for ti, turn := range turns { + nodes = append(nodes, agentTurnView(ed, ti, turn, p)) + } + if ed.HasAgentPanelCard() { + nodes = append(nodes, agentReviewPanelCards(ed, p, turns)...) + } + if ed.DataTableReviewPending() { + nodes = append(nodes, agentPendingDataTableReviewCard(ed, p)) + } + if openReq != nil { + nodes = append(nodes, agentOpenRequestCard(ed, openReq, openReqRef, p)) + } + if !limitReached && len(queued) > 0 { + nodes = append(nodes, agentQueuedRequestsView(ed, queued, limitReached, p)) + } + + bodyChildren := []core.Node{ + ui.ScrollView{ + TestID: "agent-thread-scroll", + Style: core.Style{ + FlexGrow: 1, + FlexBasis: core.Pt(0), + }, + ContentStyle: core.Style{ + Padding: core.Edges{Top: 12, Right: 16, Bottom: 48, Left: 16}, + Gap: 4, + }, + Children: nodes, + }, + } + + if expandedID != "" { + bodyChildren = append(bodyChildren, core.View{ + TestID: "agent-jump-latest", + Role: core.RoleButton, + Label: ed.T("threads.jumpToLatest"), + Style: core.Style{ + Position: core.Absolute, + Bottom: core.Pt(12), + Left: core.Pt(112), + Height: core.Pt(28), + Direction: core.Row, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Padding: core.Symmetric(0, 12), + Gap: 6, + CornerRadius: 14, + Background: p.LineRaised, + BorderWidth: 1, + BorderColor: p.Line, + Hover: &core.Style{Background: specHoverOverlay(p)}, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.JumpToLatestAgentRequest() + }, + Children: []core.Node{ + specIcon(lucide.ArrowDown, 12, p.TextPrimary), + core.Text{ + Content: ed.T("threads.jumpToLatest"), + Style: core.Style{ + FontSize: 11.5, + FontWeight: core.FontWeightMedium, + Color: p.TextPrimary, + }, + }, + }, + }) + } + + return core.View{ + Style: core.Style{ + FlexGrow: 1, + FlexBasis: core.Pt(0), + Overflow: core.Hidden, + }, + Children: bodyChildren, + } +} + +func agentStepGlyph(p SpecPalette, status AgentThreadStepStatus) core.Node { + switch status { + case AgentThreadStepDone: + return core.View{ + Style: core.Style{ + Width: core.Pt(14), + Height: core.Pt(14), + CornerRadius: 7, + Background: p.Added.Fill, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + }, + Children: []core.Node{specIcon(lucide.Check, 9, p.Added.Fg)}, + } + case AgentThreadStepFailed: + return core.View{ + Style: core.Style{ + Width: core.Pt(14), + Height: core.Pt(14), + CornerRadius: 7, + Background: p.Removed.Fill, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + }, + Children: []core.Node{specIcon(lucide.X, 9, p.Removed.Fg)}, + } + case AgentThreadStepRunning: + return core.View{ + Style: core.Style{ + Width: core.Pt(14), + Height: core.Pt(14), + CornerRadius: 7, + BorderWidth: 2, + BorderColor: p.Agent.Edge, + FlexShrink: 0, + }, + } + default: + return core.View{ + Style: core.Style{ + Width: core.Pt(14), + Height: core.Pt(14), + CornerRadius: 7, + BorderWidth: 2, + BorderColor: p.TextFaint, + FlexShrink: 0, + }, + } + } +} + +// AgentHistoryView renders the right-rail History timeline combining agent steps and manual edits, +// highlighting the step opened via "Open this step in History". +func AgentHistoryView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { + historyKey := core.NewMemo(cx, func() string { + _ = rev.Get() + sel := ed.SelectedHistoryStep() + return fmt.Sprintf("%d|%d|%s|%s|%s|%v", ed.agentThreads.rev, ed.History.Index(), sel.ThreadID, sel.RequestID, sel.StepID, cx.Dark()) + }) + + return core.View{ + TestID: "agent-history-panel", + Role: core.RoleRegion, + Label: ed.T("threads.history.title"), + StyleFunc: func() core.Style { + p := ed.SpecPalette(cx) + return core.Style{ + FlexGrow: 1, + FlexBasis: core.Pt(0), + Background: p.Panel, + Overflow: core.Hidden, + } + }, + Children: []core.Node{ + core.View{ + StyleFunc: func() core.Style { + p := ed.SpecPalette(cx) + return core.Style{ + Height: core.Pt(specHeaderHeight), + FlexShrink: 0, + Direction: core.Row, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifySpaceBetween, + Padding: core.Symmetric(0, 14), + Borders: core.Edges{Bottom: 1}, + BorderColor: p.Line, + } + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("threads.history.title"), + StyleFunc: func() core.Style { + return core.Style{FontSize: 13, FontWeight: core.FontWeightSemibold, Color: ed.SpecPalette(cx).TextPrimary} + }, + }, + core.Text{ + Content: ed.T("threads.history.subtitle"), + StyleFunc: func() core.Style { + return core.Style{FontSize: 11.5, Color: ed.SpecPalette(cx).TextFaint} + }, + }, + }, + }, + ui.ScrollView{ + Style: core.Style{FlexGrow: 1, FlexBasis: core.Pt(0)}, + ContentStyle: core.Style{Padding: core.Symmetric(14, 16), Gap: 6}, + Children: []core.Node{ + core.Dynamic(func(cx *core.Scope) core.Node { + _ = historyKey.Get() + p := ed.SpecPalette(cx) + entries := ed.AgentHistoryEntries() + rows := make([]core.Node, 0, len(entries)) + for i, en := range entries { + entry := en + dotFill := p.Panel + dotBorder := p.TextFaint + switch entry.Kind { + case "now": + dotFill = p.Accent.Fg + dotBorder = p.Accent.Edge + case "agent": + dotBorder = p.Agent.Edge + case "saved": + dotBorder = p.Added.Edge + } + rowBg := core.Color(0) + rowBorder := core.Color(0) + rowBW := core.Points(0) + if entry.Highlighted { + rowBg = p.Accent.Fill + rowBorder = p.Accent.Edge + rowBW = 1 + } + var actions []core.Node + if entry.ThreadID != "" { + actions = append(actions, core.View{ + TestID: "history-open-thread-" + entry.RequestID, + Role: core.RoleButton, + Label: ed.T("threads.history.backToThread"), + Style: core.Style{ + AlignSelf: core.AlignStart, + Margin: core.Edges{Top: 4}, + CornerRadius: 4, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.report(ed.OpenAgentRequest(entry.ThreadID, entry.RequestID)) + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("threads.history.backToThread"), + Style: core.Style{FontSize: 11.5, FontWeight: core.FontWeightMedium, Color: p.Accent.Fg}, + }, + }, + }) + } + var lineNode core.Node + if i < len(entries)-1 { + lineNode = core.View{ + Style: core.Style{ + Width: core.Pt(1.5), + FlexGrow: 1, + MinHeight: core.Pt(24), + Background: p.LineRaised, + }, + } + } + rows = append(rows, core.View{ + TestID: "history-entry-" + entry.ID, + Style: core.Style{ + Direction: core.Row, + Gap: 12, + Padding: core.Symmetric(6, 8), + CornerRadius: specRadiusButton, + Background: rowBg, + BorderWidth: rowBW, + BorderColor: rowBorder, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{AlignItems: core.AlignCenter, Width: core.Pt(14), FlexShrink: 0, Padding: core.Edges{Top: 3}}, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(10), + Height: core.Pt(10), + CornerRadius: 5, + Background: dotFill, + BorderWidth: 1.5, + BorderColor: dotBorder, + }, + }, + lineNode, + }, + }, + core.View{ + Style: core.Style{FlexGrow: 1, FlexShrink: 1, Gap: 2}, + Children: append([]core.Node{ + core.Text{ + Content: entry.Title, + Style: core.Style{FontSize: 12.5, FontWeight: core.FontWeightMedium, Color: p.TextPrimary}, + }, + core.Text{ + Content: entry.Meta, + Style: core.Style{FontSize: 11.5, Color: p.TextFaint}, + }, + }, actions...), + }, + }, + }) + } + return core.View{Style: core.Style{Gap: 4}, Children: rows} + }), + }, + }, + }, + } +} + +// inspectorThreadFooterView renders the pinned Inspector footer button linking the selected +// object to the agent request that last changed it ("Changed in ‘…’ · 2 min ago"). +func inspectorThreadFooterView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { + footerKey := core.NewMemo(cx, func() string { + _ = rev.Get() + if shouldShowRemoteInspector(ed) || ed.SelectedID == "" || len(ed.SelectedIDs()) > 1 { + return "" + } + attr, ok := ed.LastAgentChangeForObject(ed.SelectedID) + if !ok { + return "" + } + return fmt.Sprintf("%s|%s|%s|%s|%v", ed.SelectedID, attr.ThreadID, attr.RequestID, attr.AgeLabel, cx.Dark()) + }) + return core.Dynamic(func(cx *core.Scope) core.Node { + if footerKey.Get() == "" { + return nil + } + attr, ok := ed.LastAgentChangeForObject(ed.SelectedID) + if !ok { + return nil + } + p := ed.SpecPalette(cx) + label := ed.T("threads.inspectorFooter", + l10n.Param("title", attr.RequestTitle), + l10n.Param("age", attr.AgeLabel), + ) + return core.View{ + Style: core.Style{ + FlexShrink: 0, + Padding: core.All(10), + Borders: core.Edges{Top: 1}, + BorderColor: p.Line, + Background: p.Panel, + }, + Children: []core.Node{ + core.View{ + TestID: "inspector-thread-footer", + Role: core.RoleButton, + Label: label, + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + MinHeight: core.Pt(specButtonHeight), + Padding: core.Symmetric(6, 8), + Gap: 8, + CornerRadius: specRadiusButton, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + Hover: &core.Style{Background: specHoverOverlay(p)}, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.report(ed.OpenAgentRequest(attr.ThreadID, attr.RequestID)) + }, + Children: []core.Node{ + specIcon(lucide.MessageSquare, 14, p.TextMuted), + core.Text{ + TestID: "inspector-thread-footer-text", + Content: label, + MaxLines: 2, + Style: core.Style{ + FlexGrow: 1, + FlexShrink: 1, + FontSize: 11.5, + LineHeight: 16, + Color: p.TextSecondary, + }, + }, + }, + }, + }, + } + }) +} diff --git a/packages/game/editor/agent_ui.go b/packages/game/editor/agent_ui.go index 52cbcf1ec..86e70c033 100644 --- a/packages/game/editor/agent_ui.go +++ b/packages/game/editor/agent_ui.go @@ -12,9 +12,10 @@ import ( "github.com/nsgo-dev/nsgo/ui" ) -// RightRailView renders the editor's right sidebar: the Agent / Inspector tab bar when an agent is not disabled, -// keeping InspectorView active by default at 272 pt and showing AgentPanelView (380 pt) when the Agent tab is selected. -// When AgentModeNone is chosen, the Agent panel stays closed and only InspectorView renders. +// RightRailView renders the editor's right sidebar: TasksPanelView when Background Tasks are open, +// InspectorView alone when AgentModeNone is chosen, or the Agent / Inspector / History tab bar +// keeping InspectorView active by default at 272 pt and showing AgentPanelView or AgentHistoryView +// (380 pt) when selected. func RightRailView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { tasksOpenMemo := core.NewMemo(cx, func() bool { _ = rev.Get() @@ -55,32 +56,59 @@ func RightRailView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No return AgentPanelView(cx, ed, rev) }, Else: func(cx *core.Scope) core.Node { - return core.Dynamic(func(cx *core.Scope) core.Node { - p := SpecPaletteFor(darkMemo.Get()) - return core.View{ - TestID: "right-rail-inspector-wrap", - Style: core.Style{ - Width: core.Pt(272), - FlexShrink: 0, - Background: p.Panel, - Borders: core.Edges{Left: 1}, - BorderColor: p.Line, - }, - Children: []core.Node{ - rightRailTabBar(cx, ed, rev, p, false), - core.View{ + return core.Show{ + When: func() bool { + return tabMemo.Get() == RightTabHistory + }, + Then: func(cx *core.Scope) core.Node { + return core.Dynamic(func(cx *core.Scope) core.Node { + p := SpecPaletteFor(darkMemo.Get()) + return core.View{ + TestID: "right-rail-history-wrap", Style: core.Style{ - Direction: core.Row, - FlexGrow: 1, - FlexBasis: core.Pt(0), - MinHeight: core.Pt(0), - Overflow: core.Hidden, + Width: core.Pt(380), + FlexShrink: 0, + Background: p.Panel, + Borders: core.Edges{Left: 1}, + BorderColor: p.Line, + Overflow: core.Hidden, }, - Children: []core.Node{InspectorView(cx, ed, rev)}, - }, - }, - } - }) + Children: []core.Node{ + rightRailTabBar(cx, ed, rev, p, true), + AgentHistoryView(cx, ed, rev), + }, + } + }) + }, + Else: func(cx *core.Scope) core.Node { + return core.Dynamic(func(cx *core.Scope) core.Node { + p := SpecPaletteFor(darkMemo.Get()) + return core.View{ + TestID: "right-rail-inspector-wrap", + Style: core.Style{ + Width: core.Pt(272), + FlexShrink: 0, + Background: p.Panel, + Borders: core.Edges{Left: 1}, + BorderColor: p.Line, + }, + Children: []core.Node{ + rightRailTabBar(cx, ed, rev, p, false), + core.View{ + Style: core.Style{ + Direction: core.Row, + FlexGrow: 1, + FlexBasis: core.Pt(0), + MinHeight: core.Pt(0), + Overflow: core.Hidden, + }, + Children: []core.Node{InspectorView(cx, ed, rev)}, + }, + }, + } + }) + }, + } }, } }, @@ -183,6 +211,45 @@ func rightRailTabBar(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], p Spe trailing = compactAgentChip(ed, rev, p) } + historyBtn := core.View{ + TestID: "right-rail-tab-history", + Role: core.RoleButton, + Label: ed.T("threads.history.title"), + StyleFunc: func() core.Style { + _ = rev.Get() + var bg core.Color + if ed.RightRailTab() == RightTabHistory { + bg = p.Raised + } + return core.Style{ + Width: core.Pt(26), + Height: core.Pt(26), + FlexShrink: 0, + CornerRadius: 6, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Background: bg, + FocusVisible: p.FocusRing(2), + } + }, + OnPress: func(core.PressEvent) { + if ed.RightRailTab() == RightTabHistory { + ed.SetRightRailTab(RightTabAgent) + } else { + ed.SetRightRailTab(RightTabHistory) + } + }, + Children: []core.Node{ + specDynamicIcon(func() *core.SVG { return lucide.Clock() }, 14, func() core.Color { + _ = rev.Get() + if ed.RightRailTab() == RightTabHistory { + return p.TextPrimary + } + return p.TextMuted + }), + }, + } + return core.View{ TestID: "right-rail-header", Style: core.Style{ @@ -211,6 +278,7 @@ func rightRailTabBar(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], p Spe }, }, core.View{Style: core.Style{FlexGrow: 1}}, + historyBtn, trailing, }, } @@ -813,14 +881,29 @@ func AgentStatusChipView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) c } // AgentPanelView renders the Agent tab panel: 44 pt header with tabs and status chip, -// scrollable thread of user requests / streamed steps / open requests, and the labelled multiline composer. +// scene-grouped thread header and switcher popover, scrollable thread of persisted requests / +// live user turns / streamed steps / open requests or empty-thread orientation, and the labelled multiline composer. func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { composerFocused := core.NewSignal(cx, false) openReqRef := new(core.Ref) panelRef := new(core.Ref) + switcherBtnRef := new(core.Ref) ed.SetAgentPanelRef(panelRef) cx.Cleanup(func() { - ed.SetAgentPanelRef(nil) + if ed.focus.ctrl != nil && ed.focus.ctrl.agentPanelRef == panelRef { + ed.SetAgentPanelRef(nil) + } + }) + if ed.focus.ctrl != nil { + ed.focus.ctrl.registerCandidate(cx, RegionInspector, switcherBtnRef, func() bool { + return ed.RightRailTab() == RightTabAgent + }) + } + + cx.OnKeyWith("escape", core.KeyOptions{When: core.KeyAlways}, func() { + if ed.AgentSwitcherOpen() { + ed.SetAgentSwitcherOpen(false) + } }) // Shift+Enter inserts a newline while the composer is focused; plain Enter submits via SubmitBehaviorSubmit. @@ -843,7 +926,18 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N threadKey := core.NewMemo(cx, func() string { _ = rev.Get() var b strings.Builder - fmt.Fprintf(&b, "%s|%s|%d|%d|%s|%d|%d|", ed.ResolvedLanguage(), ed.AgentStatus(), len(ed.agent.turns), ed.AgentTurnSeq(), ed.review.outcome, ed.review.uiRev, len(ed.agent.queued)) + fmt.Fprintf(&b, "%s|%s|%d|%d|%s|%d|%d|%d|%s|%s|", + ed.ResolvedLanguage(), + ed.AgentStatus(), + len(ed.agent.turns), + ed.AgentTurnSeq(), + ed.review.outcome, + ed.review.uiRev, + len(ed.agent.queued), + ed.agentThreads.rev, + ed.agentThreads.activeThreadID, + ed.agentThreads.expandedRequestID, + ) for _, t := range ed.agent.turns { fmt.Fprintf(&b, "%s:%s:%d:%v:%v:%v:%s:%s:%d:%d:%d|", t.ID, t.Status, len(t.Steps), t.Done, t.Stopped, t.SkipPlan, t.ReviewState, t.CheckpointID, len(t.Summary), len(t.Reply), len(t.Error)) for _, st := range t.Steps { @@ -872,7 +966,7 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N return core.Dynamic(func(cx *core.Scope) core.Node { p := SpecPaletteFor(darkMemo.Get()) - threadBody := core.Dynamic(func(cx *core.Scope) core.Node { + bodyArea := core.Dynamic(func(cx *core.Scope) core.Node { _ = threadKey.Get() turns := ed.AgentTurns() openReq := ed.AgentOpenRequest() @@ -880,75 +974,57 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N dtPending := ed.DataTableReviewPending() queued := ed.AgentQueuedRequests() limitReached := ed.AgentWeeklyLimitReached() + active := ed.ActiveAgentThread() - var items []core.Node - if ready := ed.ReadyToReviewTurns(); len(ready) > 0 { - items = append(items, core.View{ - TestID: "agent-ready-to-review-banner", - Role: core.RoleStatus, + if active != nil && len(active.Requests) > 0 { + return agentThreadConversationBody(cx, ed, p, active, turns, openReq, openReqRef) + } + ready := ed.ReadyToReviewTurns() + if len(turns) > 0 || openReq != nil || len(ready) > 0 || hasReviewCard || dtPending || len(queued) > 0 || limitReached { + var items []core.Node + if len(ready) > 0 { + items = append(items, agentReadyToReviewBanner(ed, p, len(ready))) + } + if limitReached { + items = append(items, agentLimitReachedCard(ed, p)) + if len(queued) > 0 { + items = append(items, agentQueuedRequestsView(ed, queued, limitReached, p)) + } + } + for ti, turn := range turns { + items = append(items, agentTurnView(ed, ti, turn, p)) + } + if hasReviewCard { + items = append(items, agentReviewPanelCards(ed, p, turns)...) + } + if dtPending { + items = append(items, agentPendingDataTableReviewCard(ed, p)) + } + if openReq != nil { + items = append(items, agentOpenRequestCard(ed, openReq, openReqRef, p)) + } + if !limitReached && len(queued) > 0 { + items = append(items, agentQueuedRequestsView(ed, queued, limitReached, p)) + } + return ui.ScrollView{ + TestID: "agent-thread-scroll", Style: core.Style{ - Direction: core.Row, - AlignItems: core.AlignCenter, - Gap: 8, - CornerRadius: 10, - Background: p.Accent.Fill, - BorderWidth: 1, - BorderColor: p.Accent.Edge, - Padding: core.Symmetric(8, 12), + FlexGrow: 1, + FlexBasis: core.Pt(0), }, Children: []core.Node{ core.View{ + TestID: "agent-thread-list", Style: core.Style{ - Width: core.Pt(8), - Height: core.Pt(8), - CornerRadius: 4, - Background: p.Accent.Fg, - FlexShrink: 0, - }, - }, - core.Text{ - Content: ed.T("agent.automationReadyBanner", l10n.Param("count", fmt.Sprintf("%d", len(ready)))), - Style: core.Style{ - FontSize: 12, - FontWeight: 600, - Color: p.TextPrimary, + Gap: 14, + Padding: core.All(16), }, + Children: items, }, }, - }) - } - if limitReached { - items = append(items, agentLimitReachedCard(ed, p)) - if len(queued) > 0 { - items = append(items, agentQueuedRequestsView(ed, queued, limitReached, p)) } } - if len(turns) == 0 && openReq == nil && !hasReviewCard && !dtPending && len(queued) == 0 && !limitReached { - items = append(items, agentEmptyStateCard(ed, p)) - } - for ti, turn := range turns { - items = append(items, agentTurnView(ed, ti, turn, p)) - } - if hasReviewCard { - items = append(items, agentReviewPanelCards(ed, p, turns)...) - } - if dtPending { - items = append(items, agentPendingDataTableReviewCard(ed, p)) - } - if openReq != nil { - items = append(items, agentOpenRequestCard(ed, openReq, openReqRef, p)) - } - if !limitReached && len(queued) > 0 { - items = append(items, agentQueuedRequestsView(ed, queued, limitReached, p)) - } - return core.View{ - TestID: "agent-thread-list", - Style: core.Style{ - Gap: 14, - Padding: core.All(16), - }, - Children: items, - } + return agentEmptyThreadBody(cx, ed, p) }) return core.View{ @@ -966,13 +1042,25 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N }, Children: []core.Node{ rightRailTabBar(cx, ed, rev, p, true), - ui.ScrollView{ - TestID: "agent-thread-scroll", + agentThreadHeaderBar(cx, ed, rev, switcherBtnRef), + core.View{ Style: core.Style{ FlexGrow: 1, FlexBasis: core.Pt(0), + Overflow: core.Hidden, + }, + Children: []core.Node{ + bodyArea, + core.Show{ + When: func() bool { + _ = rev.Get() + return ed.AgentSwitcherOpen() + }, + Then: func(cx *core.Scope) core.Node { + return agentThreadSwitcherPopover(cx, ed, rev) + }, + }, }, - Children: []core.Node{threadBody}, }, agentComposerView(cx, ed, rev, p, composerFocused), }, @@ -980,6 +1068,42 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N }) } +func agentReadyToReviewBanner(ed *Editor, p SpecPalette, count int) core.Node { + return core.View{ + TestID: "agent-ready-to-review-banner", + Role: core.RoleStatus, + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + CornerRadius: 10, + Background: p.Accent.Fill, + BorderWidth: 1, + BorderColor: p.Accent.Edge, + Padding: core.Symmetric(8, 12), + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(8), + Height: core.Pt(8), + CornerRadius: 4, + Background: p.Accent.Fg, + FlexShrink: 0, + }, + }, + core.Text{ + Content: ed.T("agent.automationReadyBanner", l10n.Param("count", fmt.Sprintf("%d", count))), + Style: core.Style{ + FontSize: 12, + FontWeight: 600, + Color: p.TextPrimary, + }, + }, + }, + } +} + func agentEmptyStateCard(ed *Editor, p SpecPalette) core.Node { connected := ed.AgentStatus() == AgentStatusConnected heading := "Ask the agent to edit this scene" diff --git a/packages/game/editor/commands.go b/packages/game/editor/commands.go index bb0d91c9f..4b4355c48 100644 --- a/packages/game/editor/commands.go +++ b/packages/game/editor/commands.go @@ -128,6 +128,7 @@ const ( CmdReviewPeekBefore = "review.peekBefore" CmdReviewKeep = "review.keep" CmdReviewRevertAll = "review.revertAll" + CmdNewAgentThread = "agent.newThread" ) var ( @@ -334,6 +335,22 @@ func (e *Editor) initBuiltinCommands() { return nil }, }, + { + ID: CmdNewAgentThread, + Label: "New Agent Thread", + Description: "Start a new empty agent thread for the open scene", + Category: "Agent", + Keywords: []string{"new", "thread", "agent", "chat", "session"}, + Scope: ScopeAgent, + Shortcut: "mod+n", + Enabled: func() bool { + return !e.Playing() && e.RightRailTab() == RightRailAgent + }, + Run: func() error { + e.NewAgentThread() + return nil + }, + }, { ID: CmdOpenProject, Label: "Open Project...", @@ -2110,6 +2127,7 @@ var builtinCommandKeys = map[string][3]string{ 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"}, } // Commands returns all currently active commands in deterministic order: diff --git a/packages/game/editor/demo.go b/packages/game/editor/demo.go index e694bf175..58b4dd18c 100644 --- a/packages/game/editor/demo.go +++ b/packages/game/editor/demo.go @@ -179,6 +179,7 @@ func (e *Editor) OpenDemo() error { e.ProjectPath = "" e.projectSaved = nil e.projectSavedOnce = false + e.resetAgentThreadsForDemo() e.clip = nil e.clipMeta = clipMeta{} e.clipScene = nil diff --git a/packages/game/editor/editorcmd/agent_threads_screenshot_test.go b/packages/game/editor/editorcmd/agent_threads_screenshot_test.go new file mode 100644 index 000000000..412303ea9 --- /dev/null +++ b/packages/game/editor/editorcmd/agent_threads_screenshot_test.go @@ -0,0 +1,267 @@ +package editorcmd_test + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/project" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +// TestAgentThreadsMacOSScreenshots renders the Agent Threads UI on the real native macOS host +// across folded/expanded thread view, grouped thread switcher popover, empty-thread view, +// Inspector footer attribution, and Spec Light theme for visual verification beside +// docs/design/editor/Threads.dc.html and Spec.dc.html. +func TestAgentThreadsMacOSScreenshots(t *testing.T) { + dir := t.TempDir() + scenesDir := filepath.Join(dir, "scenes") + if err := os.MkdirAll(scenesDir, 0o755); err != nil { + t.Fatal(err) + } + level1Doc := &sceneformat.SceneDoc{ + Version: sceneformat.CurrentVersion, + Name: "level_01", + VirtualWidth: 640, + VirtualHeight: 360, + BackgroundColor: "#1a1f2a", + Layers: []sceneformat.LayerDoc{ + { + Name: "actors", + Space: sceneformat.SpaceWorld, + Order: 10, + Objects: []sceneformat.ObjectDoc{ + {ID: "Player", Name: "Player", X: 132, Y: 350}, + {ID: "Knight", Name: "Knight", X: 444, Y: 286}, + { + ID: "Door", + Name: "Door", + X: 632, + Y: 356, + Properties: map[string]any{ + "locked": true, + "opens_after_pulls": 2, + }, + }, + {ID: "lever_01", Name: "lever_01", X: 598, Y: 372}, + {ID: "slime_01", Name: "slime_01", X: 228, Y: 376}, + {ID: "slime_02", Name: "slime_02", X: 292, Y: 376}, + {ID: "slime_03", Name: "slime_03", X: 512, Y: 300}, + }, + }, + }, + } + bossDoc := &sceneformat.SceneDoc{ + Version: sceneformat.CurrentVersion, + Name: "boss_room", + VirtualWidth: 640, + VirtualHeight: 360, + BackgroundColor: "#1a1f2a", + Layers: []sceneformat.LayerDoc{ + { + Name: "actors", + Space: sceneformat.SpaceWorld, + Order: 10, + Objects: []sceneformat.ObjectDoc{ + {ID: "boss_spawn", Name: "boss_spawn", X: 320, Y: 220}, + }, + }, + }, + } + l1Bytes, err := sceneformat.Encode(level1Doc) + if err != nil { + t.Fatal(err) + } + bossBytes, err := sceneformat.Encode(bossDoc) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(scenesDir, "level_01.scene.yaml"), l1Bytes, 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(scenesDir, "boss_room.scene.yaml"), bossBytes, 0o644); err != nil { + t.Fatal(err) + } + proj := &project.File{ + Version: project.CurrentVersion, + Name: "dungeon-run", + ID: "dev.nsgo.dungeonrun", + AppVersion: "0.1.0", + Window: project.Window{Width: 640, Height: 360}, + Autoload: &project.Autoload{ + MainScene: "level_01", + Scenes: []project.Entry{ + {Name: "level_01", Path: "scenes/level_01.scene.yaml"}, + {Name: "boss_room", Path: "scenes/boss_room.scene.yaml"}, + }, + }, + } + projBytes, err := project.Encode(proj) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, project.FileName), projBytes, 0o644); err != nil { + t.Fatal(err) + } + briefYAML := `suggestions: + - "Block out level_01 with three platforms and an exit door" + - "Add a slime that patrols the floor and costs the Knight one heart" + - "Set up the HUD: three hearts and a coin counter" +` + if err := os.WriteFile(filepath.Join(dir, "brief.yaml"), []byte(briefYAML), 0o644); err != nil { + t.Fatal(err) + } + + now := time.Date(2026, 11, 26, 14, 20, 0, 0, time.UTC) + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + ed.Now = func() time.Time { return now } + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + ed.SetAgentMCPConnected(true, "MCP") + + // Seed threads matching docs/design/editor/Threads.dc.html. + now = time.Date(2026, 11, 25, 13, 0, 0, 0, time.UTC) + _, _ = ed.SendAgentRequestWith(editor.AgentSendRequest{ + Title: "Spikes under the plank", + Prompt: "Place spikes under the wooden plank.", + Outcome: editor.AgentThreadOutcomeReverted, + ChangesTotal: 2, + }) + ed.NewAgentThread() + now = time.Date(2026, 11, 26, 13, 20, 0, 0, time.UTC) + _, _ = ed.SendAgentRequestWith(editor.AgentSendRequest{ + Title: "Slimes and a coin trail", + Prompt: "Put three slimes and a coin trail toward the door.", + Outcome: editor.AgentThreadOutcomeKept, + ChangesTotal: 6, + ChangesKept: 5, + }) + ed.NewAgentThread() + now = time.Date(2026, 11, 26, 13, 40, 0, 0, time.UTC) + r1, _ := ed.SendAgentRequestWith(editor.AgentSendRequest{ + Title: "Door opens after two lever pulls", + Prompt: "Keep the door shut until the lever is pulled twice, then let it open.", + Outcome: editor.AgentThreadOutcomeKept, + ChangesTotal: 3, + ChangesKept: 3, + Objects: []string{"Door", "lever_01"}, + Detail: "Door.locked, Door.opens_after_pulls, lever_01.pulls", + Steps: []editor.AgentThreadStep{ + {ID: "s1", Label: "Set Door.opens_after_pulls = 2 and wired lever_01", Status: editor.AgentThreadStepDone, Objects: []string{"Door"}}, + }, + }) + now = time.Date(2026, 11, 26, 13, 52, 0, 0, time.UTC) + _, _ = ed.SendAgentRequestWith(editor.AgentSendRequest{ + Title: "Click sound on the lever", + Prompt: "Add a click sound when the lever moves.", + Outcome: editor.AgentThreadOutcomeKept, + ChangesTotal: 2, + ChangesKept: 2, + Objects: []string{"lever_01"}, + Detail: "lever_01.sound, audio/sfx/lever_click.wav", + }) + now = time.Date(2026, 11, 26, 14, 5, 0, 0, time.UTC) + _, _ = ed.SendAgentRequestWith(editor.AgentSendRequest{ + Title: "Lever glows while in reach", + Prompt: "Make the lever glow while the Knight is within reach.", + Outcome: editor.AgentThreadOutcomeKept, + ChangesTotal: 2, + ChangesKept: 1, + Detail: "lever_01.glow kept · reach_radius 48 reverted", + }) + now = time.Date(2026, 11, 26, 14, 11, 0, 0, time.UTC) + _, _ = ed.SendAgentRequestWith(editor.AgentSendRequest{ + Title: "Door opens over 0.6 s", + Prompt: "Slow the door opening down to 0.6 s.", + Outcome: editor.AgentThreadOutcomeReverted, + ChangesTotal: 1, + Detail: "Door.open_time 0.25 → 0.6", + }) + now = time.Date(2026, 11, 26, 14, 20, 0, 0, time.UTC) + _, _ = ed.SendAgentRequestWith(editor.AgentSendRequest{ + Title: "Open the door with a short rumble and a small camera shake", + Prompt: "Open the door with a short rumble and a small camera shake.", + Outcome: editor.AgentThreadOutcomePending, + ChangesTotal: 3, + Files: []string{"prefabs/door.prefab.yaml", "scenes/level_01.scene.yaml"}, + Objects: []string{"Door"}, + Steps: []editor.AgentThreadStep{ + {ID: "st1", Label: "Read door.prefab.yaml and camera.yaml", Status: editor.AgentThreadStepDone}, + {ID: "st2", Label: "Added door_rumble.wav and a 0.3 s shake on open", Status: editor.AgentThreadStepDone}, + {ID: "st3", Label: "Played 6 s headless · door opens on the second pull", Status: editor.AgentThreadStepDone}, + }, + }) + doorThreadID := ed.ActiveAgentThread().ID + + // Project-wide thread + boss_room thread. + ed.NewProjectAgentThread() + now = time.Date(2026, 11, 23, 10, 0, 0, 0, time.UTC) + _, _ = ed.SendAgentRequestWith(editor.AgentSendRequest{ + Title: "Double jump for the Knight", + Prompt: "Add a double jump ability for the Knight.", + Outcome: editor.AgentThreadOutcomeKept, + Files: []string{"game.yaml", "prefabs/knight.prefab.yaml"}, + }) + _ = ed.OpenScene("scenes/boss_room.scene.yaml") + now = time.Date(2026, 11, 25, 14, 0, 0, 0, time.UTC) + _, _ = ed.SendAgentRequestWith(editor.AgentSendRequest{ + Title: "Torches around the boss arena", + Prompt: "Place flickering torches around the boss arena.", + Outcome: editor.AgentThreadOutcomeKept, + ChangesTotal: 4, + ChangesKept: 4, + }) + now = time.Date(2026, 11, 26, 14, 20, 0, 0, time.UTC) + _ = ed.OpenScene("scenes/level_01.scene.yaml") + _ = ed.SelectAgentThread(doorThreadID) + ed.SelectObject("Door") + ed.SetRightRailTab(editor.RightRailAgent) + ed.SetExpandedAgentRequestID(r1.ID) + + 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"})) + + // 1. Folded earlier requests + expanded request + "Open this step in History" + "Jump to latest" + latest pending card. + app.Screenshot("agent-threads-folded-expanded") + + // 2. Thread switcher popover open grouped by open scene, other scenes, and Project · no scene. + app.Post(func() { + ed.SetAgentSwitcherOpen(true) + }) + app.Settle() + app.Screenshot("agent-threads-switcher") + + // 3. Empty thread view with always-read context chips and FROM YOUR BRIEF suggestions. + app.Post(func() { + ed.NewAgentThread() + }) + app.Settle() + app.Screenshot("agent-threads-empty") + + // 4. Inspector footer linking Door to the request that last changed it. + app.Post(func() { + _ = ed.SelectAgentThread(doorThreadID) + ed.SetRightRailTab(editor.RightRailInspector) + ed.SelectObject("Door") + }) + app.Settle() + app.Screenshot("agent-threads-inspector-footer") + + // 5. Spec Light theme parity check on Agent threads + switcher. + app.Post(func() { + _ = ed.SetAppearance(editor.AppearanceLight) + ed.SetRightRailTab(editor.RightRailAgent) + ed.SetAgentSwitcherOpen(true) + }) + app.Settle() + app.Screenshot("agent-threads-light") +} diff --git a/packages/game/editor/editormcp/edit.go b/packages/game/editor/editormcp/edit.go index 339a21cba..685e823a4 100644 --- a/packages/game/editor/editormcp/edit.go +++ b/packages/game/editor/editormcp/edit.go @@ -183,7 +183,8 @@ func sceneEdit(ctx context.Context, c *Call) (*Result, error) { if title == "" { title = label } - return ed.RecordAgentTurn(editor.AgentTurnOptions{ + var editedIDs []string + err := ed.RecordAgentTurn(editor.AgentTurnOptions{ Title: title, UndoLabel: label, ChangeCount: len(args.Edits), @@ -196,10 +197,20 @@ func sceneEdit(ctx context.Context, c *Call) (*Result, error) { } if id != "" { res.Objects = append(res.Objects, id) + editedIDs = append(editedIDs, id) + } else if e.ID != "" { + editedIDs = append(editedIDs, e.ID) } } return nil }) + if err != nil { + return err + } + if len(editedIDs) > 0 { + ed.NoteAgentEditedObjects(editedIDs, []string{scenePath(ed, root)}, label) + } + return nil }) if err != nil { return nil, err diff --git a/packages/game/editor/editormcp/server_test.go b/packages/game/editor/editormcp/server_test.go index 0e7506cbf..56599e2d1 100644 --- a/packages/game/editor/editormcp/server_test.go +++ b/packages/game/editor/editormcp/server_test.go @@ -179,6 +179,27 @@ func TestSceneEditPlacesAnObjectAsOneUndoStep(t *testing.T) { } } +func TestSceneEditRecordsAttributionOnActiveAgentThread(t *testing.T) { + f := openFixture(t) + s := editormcp.New(f.ed, editormcp.Options{}) + t.Cleanup(func() { _ = s.Close() }) + cs := connect(t, s, nil) + + req, err := f.ed.SendAgentRequest("Move the hero right") + if err != nil { + t.Fatalf("SendAgentRequest: %v", err) + } + mustOK(t, call(t, cs, editormcp.ToolSceneEdit, map[string]any{ + "edits": []any{ + map[string]any{"op": "move", "id": "hero", "x": 120, "y": 40}, + }, + })) + attr, ok := f.ed.LastAgentChangeForObject("hero") + if !ok || attr.RequestID != req.ID || attr.RequestTitle != "Move the hero right" { + t.Fatalf("LastAgentChangeForObject(hero) = (%+v, %v), want req %q", attr, ok, req.ID) + } +} + // Each kind of edit reaches the editor's method for it. func TestSceneEditOps(t *testing.T) { f := openFixture(t) diff --git a/packages/game/editor/inspector.go b/packages/game/editor/inspector.go index 056adb9f1..4db98d16e 100644 --- a/packages/game/editor/inspector.go +++ b/packages/game/editor/inspector.go @@ -623,6 +623,8 @@ func renderInspectorView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) c TestID: "editor-inspector", Style: core.Style{ Width: core.Pt(272), + FlexGrow: 1, + FlexBasis: core.Pt(0), Background: specPanel, Borders: core.Edges{Left: 1}, BorderColor: specLine, @@ -752,6 +754,7 @@ func renderInspectorView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) c }, }, }, + inspectorThreadFooterView(cx, ed, rev), }, } } diff --git a/packages/game/editor/locales/en.yaml b/packages/game/editor/locales/en.yaml index a57cc7f89..f710c64fe 100644 --- a/packages/game/editor/locales/en.yaml +++ b/packages/game/editor/locales/en.yaml @@ -137,6 +137,7 @@ strings: cmd.bakeNavMesh3d.label: Bake 3D NavMesh cmd.buildRelease.desc: Open the Build and Release screen with readiness, pre-build checks, and release size comparison cmd.buildRelease.label: Build & Release Screen + cmd.category.agent: Agent cmd.category.edit: Edit cmd.category.file: File cmd.category.gizmo3d: 3D Gizmo @@ -194,6 +195,8 @@ strings: cmd.navMeshOverlay.label: Show 3D NavMesh Overlay cmd.navMeshPanel.desc: Toggle the 3D navigation mesh bake settings panel cmd.navMeshPanel.label: 3D NavMesh Bake Panel + cmd.newAgentThread.desc: Start a new empty agent thread for the open scene + cmd.newAgentThread.label: New Agent Thread cmd.newProject.desc: Open the Start Screen to create a new project from a template cmd.newProject.label: New Project... cmd.openProject.desc: Choose a project folder to open in the editor @@ -848,6 +851,7 @@ strings: sceneTree.ungroup: Ungroup sceneTree.unlock: Unlock sceneTree.unlockNamed: Unlock {id} + scope.agent: Agent scope.animation: Animation scope.global: Global scope.play: Play @@ -1182,6 +1186,57 @@ strings: tasks.sectionTitle: Tasks tasks.send: Send tasks.whenToStart: When to start + threads.action.keep: Keep + threads.action.revert: Revert + threads.age.hoursAgo: '{count} h ago' + threads.age.minutesAgo: '{count} min ago' + threads.age.now: now + threads.age.yesterday: yesterday + threads.composer.always: Always + threads.composer.label: Ask the agent + threads.composer.placeholder: Describe a change · @ to mention + threads.composer.send: Send + threads.context.viewportImage: Viewport image + threads.context.wholeScene: '{scene} · whole scene' + threads.earlierRequestsMany: '{count} EARLIER REQUESTS' + threads.earlierRequestsOne: 1 EARLIER REQUEST + threads.empty.fromBrief: FROM YOUR BRIEF + threads.empty.readsHeading: 'The agent reads these with every request:' + threads.group.openScene: '{scene} · OPEN SCENE' + threads.group.project: PROJECT · NO SCENE + threads.history.agentPrefix: Agent · {label} + threads.history.backToThread: Back to thread + threads.history.clean: saved + threads.history.now: Now + threads.history.openedStatus: Opened step in History + threads.history.saved: Saved + threads.history.subtitle: your edits and the agent's, one timeline + threads.history.title: History + threads.history.undoStep: Undo step {index} + threads.history.unsaved: unsaved + threads.history.youPrefix: You · {label} + threads.inspectorFooter: Changed in “{title}” · {age} + threads.jumpToLatest: Jump to latest + threads.meta.changesToReview: '{count} changes to review' + threads.meta.empty: new · no requests yet + threads.meta.inProgress: in progress + threads.meta.kept: kept + threads.meta.keptOf: kept {kept} of {total} + threads.meta.oneChangeToReview: 1 change to review + threads.meta.reverted: reverted + threads.newButton: New + threads.newThread: New thread + threads.openInHistory: Open this step in History + threads.readingPlaceholder: Reading {file}… + threads.reviewCard.summary: '{changes} changes · {files} files' + threads.searchPlaceholder: Search threads + threads.storageFooter: .nsgo/threads/ · ignored by git + threads.suggestion.blockOut: Block out {scene} with three platforms and an exit door + threads.suggestion.enemyPatrol: Add a slime that patrols the floor and costs the Knight one heart + threads.suggestion.hud: 'Set up the HUD: three hearts and a coin counter' + threads.switcherEmpty: No matching threads + threads.switcherTriggerLabel: 'Thread: {title}. Switch thread' + threads.tab.agent: Agent tilePalette.flipDiag: Flip diagonally tilePalette.flipHoriz: Flip horizontally tilePalette.flipVert: Flip vertically diff --git a/packages/game/editor/locales/zh.yaml b/packages/game/editor/locales/zh.yaml index 7b49f9cf9..bcd4b9889 100644 --- a/packages/game/editor/locales/zh.yaml +++ b/packages/game/editor/locales/zh.yaml @@ -137,6 +137,7 @@ strings: cmd.bakeNavMesh3d.label: 烘焙 3D 导航网格 cmd.buildRelease.desc: 打开包含就绪检查、构建前校验与版本体积对比的构建与发布界面 cmd.buildRelease.label: 构建与发布界面 + cmd.category.agent: 智能体 cmd.category.edit: 编辑 cmd.category.file: 文件 cmd.category.gizmo3d: 3D 操纵杆 @@ -194,6 +195,8 @@ strings: cmd.navMeshOverlay.label: 显示 3D 导航网格叠加层 cmd.navMeshPanel.desc: 切换 3D 导航网格烘焙设置面板 cmd.navMeshPanel.label: 3D 导航网格烘焙面板 + cmd.newAgentThread.desc: 为当前打开的场景新建一条空白智能体线程 + cmd.newAgentThread.label: 新建智能体线程 cmd.newProject.desc: 打开开始界面并从模板创建新项目 cmd.newProject.label: 新建项目… cmd.openProject.desc: 选择要在编辑器中打开的项目目录 @@ -848,6 +851,7 @@ strings: sceneTree.ungroup: 取消编组 sceneTree.unlock: 解锁 sceneTree.unlockNamed: 解锁 {id} + scope.agent: 智能体 scope.animation: 动画 scope.global: 全局 scope.play: 运行 @@ -1182,6 +1186,57 @@ strings: tasks.sectionTitle: 任务 tasks.send: 发送 tasks.whenToStart: 启动方式 + threads.action.keep: 保留 + threads.action.revert: 还原 + threads.age.hoursAgo: '{count} 小时前' + threads.age.minutesAgo: '{count} 分钟前' + threads.age.now: 刚刚 + threads.age.yesterday: 昨天 + threads.composer.always: 始终包含 + threads.composer.label: 向智能体提问 + threads.composer.placeholder: 描述修改内容 · 输入 @ 引用对象或文件 + threads.composer.send: 发送 + threads.context.viewportImage: 视口图像 + threads.context.wholeScene: '{scene} · 整个场景' + threads.earlierRequestsMany: '{count} 条较早请求' + threads.earlierRequestsOne: 1 条较早请求 + threads.empty.fromBrief: 来自项目简报 + threads.empty.readsHeading: 智能体每次请求都会读取以下内容: + threads.group.openScene: '{scene} · 当前场景' + threads.group.project: 项目 · 无场景 + threads.history.agentPrefix: 智能体 · {label} + threads.history.backToThread: 返回线程 + threads.history.clean: 已保存 + threads.history.now: 现在 + threads.history.openedStatus: 已在历史记录中打开该步骤 + threads.history.saved: 已保存 + threads.history.subtitle: 你和智能体的修改共用一条时间线 + threads.history.title: 历史记录 + threads.history.undoStep: 撤销步骤 {index} + threads.history.unsaved: 未保存 + threads.history.youPrefix: 你 · {label} + threads.inspectorFooter: 修改自“{title}” · {age} + threads.jumpToLatest: 跳到最新 + threads.meta.changesToReview: '{count} 项待审查修改' + threads.meta.empty: 新建 · 暂无请求 + threads.meta.inProgress: 进行中 + threads.meta.kept: 已保留 + threads.meta.keptOf: 已保留 {kept}/{total} 项 + threads.meta.oneChangeToReview: 1 项待审查修改 + threads.meta.reverted: 已还原 + threads.newButton: 新建 + threads.newThread: 新建线程 + threads.openInHistory: 在历史记录中打开此步骤 + threads.readingPlaceholder: 正在读取 {file}… + threads.reviewCard.summary: '{changes} 项修改 · {files} 个文件' + threads.searchPlaceholder: 搜索线程 + threads.storageFooter: .nsgo/threads/ · 已由 git 忽略 + threads.suggestion.blockOut: 用三个平台和一扇出口门搭建 {scene} 的白模 + threads.suggestion.enemyPatrol: 添加一只在地面巡逻并扣减骑士一颗心的史莱姆 + threads.suggestion.hud: 设置 HUD:三颗生命值和金币计数器 + threads.switcherEmpty: 没有匹配的线程 + threads.switcherTriggerLabel: 线程:{title}。切换线程 + threads.tab.agent: 智能体 tilePalette.flipDiag: 沿对角线翻转 tilePalette.flipHoriz: 水平翻转 tilePalette.flipVert: 垂直翻转 diff --git a/packages/game/editor/project.go b/packages/game/editor/project.go index 792e547f9..44782a00d 100644 --- a/packages/game/editor/project.go +++ b/packages/game/editor/project.go @@ -263,6 +263,7 @@ func (e *Editor) openProject(path, scene string, withScene bool) error { e.resetAgentReviewForProject() e.resetPermissionsForProject() e.syncDiskWatchTargets() + e.loadAgentThreadsForProject() e.resetTextInputFocus() e.resetProblemsForProject() e.loadAgentDocsForProject(filepath.Dir(path)) diff --git a/packages/game/editor/shortcuts.go b/packages/game/editor/shortcuts.go index 0aa83004b..1a97d9dca 100644 --- a/packages/game/editor/shortcuts.go +++ b/packages/game/editor/shortcuts.go @@ -22,6 +22,7 @@ const ( ScopeAnimation = "animation" ScopePlay = "play" ScopeReview = "review" + ScopeAgent = "agent" ) // scopeDisplayOrder lists built-in scopes in presentation order for Settings › Shortcuts and the ⌘/ sheet. @@ -35,6 +36,7 @@ var scopeDisplayOrder = []string{ ScopeReview, ScopeAnimation, ScopePlay, + ScopeAgent, } // ShortcutConflictError is returned by RebindShortcut when another command in the same scope @@ -81,6 +83,8 @@ func (e *Editor) CommandScopeLabel(scope string) string { return e.T("scope.play") case ScopeReview: return e.T("scope.review") + case ScopeAgent: + return e.T("scope.agent") default: return normalizeCommandScope(scope) } @@ -109,6 +113,8 @@ func (e *Editor) commandScopeSearchTerms(scope string) []string { terms = append(terms, "play", "run") case ScopeReview: terms = append(terms, "review", "agent", "diff", "keep", "revert", "notes", "round") + case ScopeAgent: + terms = append(terms, "agent", "thread", "threads") } return terms } @@ -505,6 +511,11 @@ func (e *Editor) shortcutScopePriority(scope string) int { return 4 } return 2 + case ScopeAgent: + if e.RightRailTab() == RightRailAgent || e.FocusInAgentPanel() || e.AgentSwitcherOpen() { + return 4 + } + return 0 case ScopeViewport2D: if e.ViewMode == ViewMode2D { return 3 diff --git a/packages/game/editor/state.go b/packages/game/editor/state.go index c707183be..9eff3abd9 100644 --- a/packages/game/editor/state.go +++ b/packages/game/editor/state.go @@ -552,6 +552,10 @@ type Editor struct { OnFocusAgentRequest func(req AgentOpenRequest) // OnAgentTurn, when set, is called whenever the author sends a request from the ⌘L in-place composer or Agent panel. OnAgentTurn func(AgentTurn) + // OnSendAgentRequest, when set, is called after SendAgentRequest / SendAgentRequestWith appends and persists a request on the active agent thread. + OnSendAgentRequest func(thread *AgentThread, req AgentThreadRequest) + // OnOpenHistoryStep, when set, is called when the author clicks "Open this step in History" on a folded request or step. + OnOpenHistoryStep func(sel AgentHistorySelection) // ProblemCheckDebounce controls the debounce delay before live problem checks run after edits (defaults to 80ms when <= 0). ProblemCheckDebounce time.Duration // OnAskAboutProblem, when set, is called when the author submits a question from "Ask about this problem…" with the problem attached. @@ -911,6 +915,8 @@ type Editor struct { inspectorFilter string // inspectorCollapsed tracks which titled inspector sections are collapsed by section ID. inspectorCollapsed map[string]bool + // agentThreads holds per-line-of-work agent threads grouped by scene, thread switcher UI state, and History step selection. + agentThreads agentThreadsState // inspectorScrub tracks an active live label-drag scrub in the inspector. inspectorScrub inspectorScrubState // composerDraft holds the current prompt text staged for the agent composer (e.g. via Ask to add). @@ -1593,6 +1599,7 @@ func (e *Editor) openYAMLWithLayers(data []byte, file string, layers *sceneforma // Clear triggers onChange -> afterMutate -> Rebuild + notify. e.History.Clear() e.syncActiveTab() + e.syncAgentThreadForOpenScene() return nil } @@ -1686,9 +1693,13 @@ func (e *Editor) SaveFile(path string) error { e.tabs[e.activeTab].placeholder = false } e.recordSceneDiskSnapshot(path, data) + prevScenePath := e.ScenePath e.syncScenePath() e.syncActiveTab() e.noteSavedHistoryFile(path) + if e.ScenePath != prevScenePath { + e.syncAgentThreadForOpenScene() + } e.saveViewStateQuietly() e.filesRev++ e.snapshotProjectTree() diff --git a/packages/game/editor/tabs.go b/packages/game/editor/tabs.go index 56e0dd917..1d664c0c5 100644 --- a/packages/game/editor/tabs.go +++ b/packages/game/editor/tabs.go @@ -518,6 +518,7 @@ func (e *Editor) SelectTab(index int) error { e.resetNavMeshForScene() e.tryAutoloadNavMesh3D() e.refreshOpenSceneSearch() + e.syncAgentThreadForOpenScene() e.Status = "Switched to " + e.SceneLabel() e.notify() return nil @@ -698,6 +699,7 @@ func (e *Editor) CloseTab(index int) error { e.resetNavMeshForScene() e.refreshOpenSceneSearch() e.clearSaveFailureForTab(closedID) + e.syncAgentThreadForOpenScene() e.Status = "Closed " + closedLabel e.notify() return nil @@ -742,6 +744,7 @@ func (e *Editor) CloseTab(index int) error { e.tryAutoloadNavMesh3D() e.clearSaveFailureForTab(closedID) e.refreshOpenSceneSearch() + e.syncAgentThreadForOpenScene() e.Status = "Closed " + closedLabel e.notify() return nil @@ -946,6 +949,7 @@ func (e *Editor) activateNewTab(doc *sceneformat.SceneDoc, saved []byte, filePat e.restoreViewState() e.syncActiveTab() e.refreshOpenSceneSearch() + e.syncAgentThreadForOpenScene() } // selectedObjectInstancesScene reports whether the active scene's selected object is a scene instance or an instanced child of one. diff --git a/packages/game/editor/testdata/agent_thread.yaml b/packages/game/editor/testdata/agent_thread.yaml new file mode 100644 index 000000000..559f54c9c --- /dev/null +++ b/packages/game/editor/testdata/agent_thread.yaml @@ -0,0 +1,59 @@ +# yaml-language-server: $schema=https://game.nsgo.dev/schemas/agent-thread.v1.json +version: 1 +id: door-lever-pulls +title: Door opens after two lever pulls +scenePath: scenes/level_01.scene.yaml +sessionId: sess_claude_01 +createdAt: "2026-11-26T13:40:00Z" +updatedAt: "2026-11-26T14:18:00Z" +requests: + - id: req-001 + title: Door opens after two lever pulls + prompt: Keep the door shut until the lever is pulled twice, then let it open. + createdAt: "2026-11-26T13:40:00Z" + updatedAt: "2026-11-26T13:41:00Z" + outcome: kept + changesTotal: 3 + changesKept: 3 + files: + - prefabs/door.prefab.yaml + - scenes/level_01.scene.yaml + objects: + - Door + - lever_01 + detail: Door.locked, Door.opens_after_pulls, lever_01.pulls + historyStep: 'Agent: Door opens after two lever pulls' + historyIndex: 1 + steps: + - id: step-001 + label: Read level_01.scene.yaml and door.prefab.yaml + status: done + files: + - prefabs/door.prefab.yaml + - scenes/level_01.scene.yaml + - id: step-002 + label: Set Door.opens_after_pulls to 2 and wired lever_01 + status: done + historyStep: 'Agent: Door opens after two lever pulls' + historyIndex: 1 + objects: + - Door + - lever_01 + - id: req-002 + title: Open the door with a short rumble and camera shake + prompt: Open the door with a short rumble and a small camera shake. + createdAt: "2026-11-26T14:18:00Z" + updatedAt: "2026-11-26T14:18:00Z" + outcome: pending + changesTotal: 3 + files: + - prefabs/door.prefab.yaml + - scenes/level_01.scene.yaml + objects: + - Door + steps: + - id: step-003 + label: Added door_rumble.wav and a 0.3 s shake on open + status: done + objects: + - Door diff --git a/packages/game/formats_test.go b/packages/game/formats_test.go index 9ae81bb7a..71405298d 100644 --- a/packages/game/formats_test.go +++ b/packages/game/formats_test.go @@ -121,6 +121,7 @@ var formatVersions = map[string]string{ "cloudsave/sqlstore.SchemaVersion": "", "cutscene.CurrentVersion": "cutscene", "cutscene.MinVersion": "cutscene", + "editor.AgentThreadFileVersion": "editor#agent-thread", "editor.AgentThreadVersion": "editor#thread", "editor.AutomationsVersion": "editor#automations", "editor.PermissionsVersion": "editor#permissions",