diff --git a/.agents/notes/implemented/feature/2026-11-26-editor-agent-live-steps.md b/.agents/notes/implemented/feature/2026-11-26-editor-agent-live-steps.md new file mode 100644 index 000000000..0ad05a548 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-26-editor-agent-live-steps.md @@ -0,0 +1,38 @@ +# Agent Note: Editor Agent Panel Live Steps, Permission Cards, and Stop + +Status: implemented + +## Problem + +When an AI agent drives the scene editor through `editormcp`, authors need to watch each step unfold in plain words, approve or deny gated actions (such as headless playtests or edits under a cautious profile) without losing manual editing or keyboard focus, add follow-up instructions to a running request, and stop the agent from anywhere (including inside a modal dialog) while preserving completed edits for review. Although `permissions.yaml` rule evaluation (`#1010`), You-only trust boundaries (`#1015`), and the Agent panel (`#1009`, `#1019`) already exist on `main`, `editormcp.Server` previously returned an immediate `PermissionError` on `Ask` when `Options.OnPermissionAsk` was nil rather than pausing on an interactive Agent panel permission card, lacked `agent_report_step`, per-request denial memory, mid-request `"Add to this request"` follow-ups, and unified `⌘.` Stop cancellation for waiting asks and in-flight tool calls. + +## Decision + +Integrate live step streaming, interactive permission cards, follow-ups, and Stop directly onto the existing `Editor` agent state (`packages/game/editor/agent.go`, `agent_live_steps.go`, `agent_ui.go`, `agent_live_steps_ui.go`), the existing versioned `permissions.yaml` engine (`packages/game/editor/permissions.go`), and `editormcp.Server` (`packages/game/editor/editormcp/agent.go`, `agent_live.go`, `server.go`): + +- **Unified `permissions.yaml` and You-only enforcement**: Reuse `permissions.yaml` (`editor.PermissionsVersion = 1`) and `checkYouOnlyTargets` as the single source of truth—no duplicate permissions schema or file format. Every mutating/running MCP call checks You-only targets first and evaluates `permissions.yaml` before opening any permission card or running a handler. +- **Non-blocking interactive MCP mediation & streaming**: When `Options.OnPermissionAsk` is nil and either a live Agent request is active (`Editor.HasActiveLiveAgentRequest`) or the server runs against a UI loop (`Options.Run != nil`), `editormcp.Server.runManagedToolCall` pauses `Ask` calls on the MCP goroutine (never blocking the editor UI goroutine) and renders a Spec `RoleAlertDialog` (`LiveRegionPolite`) card inside `AgentPanelView`. Headless inline callers without an active request keep returning `*PermissionError` immediately for compatibility with `#1010` callers. +- **Live steps & `agent_report_step`**: Starting a request immediately inserts a gray `AgentStepPlaceholder` step (guaranteed within 300 ms); tool calls stream plain-words steps with at most one active violet spinner and green checks when done. `agent_report_step` lets agents report steps in their own words with touched object IDs and drains queued `"Add to this request"` follow-ups. +- **No automatic retry after denial & safe Allow now**: Denying a card records `(action, target)` on the active request, renders `"You denied … · continued without it"` with `"Allow now"`, records the unchecked item (such as `"Not playtested"`) in the turn's review summary, and returns a non-fatal structured `PermissionDeniedResult` immediately on any repeated identical call in the same request without re-opening a card. Starting a new request clears per-request denials. Clicking `"Allow now"` runs the tool on demand inside a WaitGroup-tracked, server-cancellation-aware, `projectGen`-verified, You-only-checked goroutine. +- **Always persistence with Undo**: Choosing `"Always"` (`⌥↵` when focused) calls `Editor.ApproveAlwaysPermission`, inserting the escaped concrete `Allow` rule ahead of the matching `Ask` rule in `permissions.yaml` and showing the existing `"Always permission rule saved"` toast with **Show** and **Undo**. +- **Focus stability, Spec rule 05, and global Stop (`⌘.`)**: Permission cards never steal focus unless `Editor.ShouldFocusAgentPrompt()` is true; clicking the header `"Waiting for you"` chip focuses the card on demand. While focused, `⌘↵` allows once, `⌥↵` approves Always, `⌘⌫` denies, `↑`/`↓` cycle buttons, and `Esc` leaves the card unanswered while the agent keeps waiting. The working footer (`"Add to this request"` + `Stop`) mounts outside `threadBody`'s dynamic scope so streaming steps never remount or steal focus from the input. `Stop` and global `⌘.` (`OverModals: true`) cancel both CLI runners and live MCP requests, close `liveStopCh`, keep completed steps and edits pending for review (pausing autosave via `HasOpenReview()` until kept or reverted), and show the `"Agent stopped"` toast with **Review**; `Esc` never stops the agent. + +## Alternatives considered + +### Introducing a separate `.nsgo/permissions.yaml` and parallel `AgentPanelView` + +Strongest argument: Keeping `#1012` isolated from `#1009`/`#1010` would avoid touching `agent.go` and `permissions.go`. + +Rejected because `main` already ships `permissions.yaml`, `Settings › Permissions`, `You-only` holds, and `RightRailView`/`AgentPanelView`. Duplicating them would create two conflicting permission files, break `Settings › Permissions`, and bypass You-only boundaries. + +### Blocking on permission answers inside `Server.Editor` on the UI goroutine + +Strongest argument: Evaluating and waiting in one `Server.Editor` closure would simplify state transitions. + +Rejected because blocking the UI goroutine freezes the editor so the user could neither click Allow/Deny/Stop nor continue manual scene editing while the agent waits. Waiting on channels on the MCP goroutine keeps the editor responsive. + +## Consequences + +- **Benefits**: Authors watch every MCP tool call and `agent_report_step` live in plain words, answer Spec permission cards without focus theft, persist `"Always"` rules directly into the project's canonical `permissions.yaml`, steer running requests with `"Add to this request"` without input remounts, edit the scene concurrently, and stop safely with `⌘.` from anywhere including modal dialogs. +- **Costs**: Adds one new built-in read-only MCP tool (`agent_report_step`) to `editormcp.Server` and `editormcp.Proxy`, and couples `AgentTurn` review state into `HasOpenReview()` so unkept scene edits pause autosave until reviewed. +- **Verification**: Verified with `go tool nsgo check`, `gameschema -check`, `tools/changelog check`, `bun run verify-notes`, `-race` unit/UI tests in `packages/game/editor` (placeholder, live steps, input focus stability, Spec rule 05 card focus/shortcuts, `⌘.` inside modal dialogs, `Esc` non-stop/non-deny, autosave pause), scripted MCP client integration tests in `packages/game/editor/editormcp` (Allow once, Always + `permissions.yaml` + Undo, non-retried Deny + Allow now + new-request re-ask, follow-ups, Stop cancellation, You-only enforcement), and real macOS `nsgotest` screenshots in Dark and Light themes. diff --git a/changelog.d/editor-agent-live-steps-1012.md b/changelog.d/editor-agent-live-steps-1012.md new file mode 100644 index 000000000..9453211df --- /dev/null +++ b/changelog.d/editor-agent-live-steps-1012.md @@ -0,0 +1,3 @@ +### Added + +- Add live agent step streaming, interactive Spec permission cards (`Allow once`, `Always`, `Deny`) backed by `permissions.yaml`, `agent_report_step` MCP tool, `"Add to this request"` follow-ups, concurrent status-bar activity, and global `⌘.` / Stop cancellation with pending review preservation and `"Agent stopped"` toast in the editor Agent panel. diff --git a/docs/en/editor.md b/docs/en/editor.md index f9d22d318..9cd23abca 100644 --- a/docs/en/editor.md +++ b/docs/en/editor.md @@ -1593,7 +1593,6 @@ Every semantic overlay drawn over the 2D and 3D viewports passes through one sha - **Top-left toggle legend (`viewport-overlay-legend`)**: Every edit-mode viewport (both 2D and 3D) mounts the same top-left legend card (`viewportOverlayLegendView`) with six accessible `role="switch"` rows (**Selection**, **Agent working**, **Added**, **Changed**, **Removed**, **Problem**), each showing its drawn line style and second cue. Toggling any row (`Editor.ToggleOverlayKind`, `Editor.SetOverlayKindVisible`, `Editor.SetOverlayLegendKinds`) hides or shows that kind across all viewports immediately and persists `overlayLegend` in the per-user `EditorSettings` YAML file (`Editor.SettingsPath`, outside the project, never modifying project or scene files). - **Live scene overlay API and Problems object attribution**: Live agent edits, reviews, and plans attach overlays to objects (or removed ghost bounds) via `Editor.SetSceneOverlays`, `AddSceneOverlay`, `RemoveSceneOverlay`, and `ClearSceneOverlays` (`SceneOverlayEntry`). `assetcheck.Problem` now carries `Object` (also returned by `editormcp`'s `game_check`) for scene object, component, override, and connection diagnostics so Problems naming a live object in the open scene automatically draw the Spec **Problem** overlay on that object in both 2D and 3D viewports. - **Neutral viewport guides**: The camera frame, camera bounds, camera tether, tile grid, and snap grid use neutral `SpecPalette` tokens (`TextMuted` / `TextFaint` 1 px hairline and `2, 4` dotted lines) that no semantic legend kind uses. - ## Agent composer: @-mentions, context chips, and context meter (#1020) Inside the unified right-rail **Agent** tab (`RightRailView` / `AgentPanelView`, switchable with `⌘1` / `⌘2` via `CmdAgentTab` / `CmdInspectorTab`), `AgentComposerView` (`docs/design/editor/Threads.dc.html`, styled strictly with `Spec.dc.html` tokens) adds `@`-mentions, explicit context chips, exact hover previews, and a live context meter: @@ -1614,3 +1613,13 @@ The editor's main window (`main_layout_ui.go`, `ui.go`, `agent_ui.go`, `overlays - **32 px status bar (`mainStatusBarView`)**: renders muted text on `bg` with the active layer button (toggling Layers), live 2D pointer coordinates, current tool readout, problem count pill (opening Problems), Output, and Debugger. Secondary views previously hosted on the old toolbar (Settings, Audio Mixer, Input Map, Localization/Strings, Export, Library, Data Table, Project Search, Files, Assets, Animation, Particles, Material, HUD Layout, Terrain, NavMesh) remain reachable through the Command Palette (`⌘K`), Menu bar, Settings, and Status bar. - **Designed empty, loading, and error states (`WorkspaceState`, `SceneOpenError`)**: every region renders a dedicated state for `WorkspaceNoProject`, `WorkspaceNoScene`, `WorkspaceLoading` (`SetProjectLoading`), and `WorkspaceSceneError` (`SceneOpenError`, `RetryOpenScene`, `ClearSceneOpenError`). Opening a missing or malformed scene YAML renders an alert card with file path, line/column, message, fix guidance, **Retry**, and **Dismiss** instead of a blank viewport. - **Spec controls and keyboard navigation**: preserves Spec heights (`28 px` rows/tool buttons, `30–32 px` buttons, `44 px` header, `32 px` status bar, no interactive hit area under `28 × 28`), spacing (`4 / 8 / 12 / 16 / 24`), radii (`6 / 8`), `base.RadioGroup` / `base.Radio` and `base.Switch` semantics, 2 px Spec focus rings, accessible names, and `F6` cycling across all five regions (`Header`, `Scene tree`, `Viewport`, `Agent / Inspector`, `Status bar`). + +## Agent panel live steps, permission cards, and Stop (#1012) + +The **Agent** panel (`AgentPanelView` inside `RightRailView`, `⌘1` / `⌘2`) streams live progress, interactive permission cards, follow-up instructions, and global Stop cancellation using `docs/design/editor/Spec.dc.html` tokens (`Working.dc.html`, `Permissions.dc.html`, `Main.dc.html`, `AgentStates.dc.html`) on top of the project's `permissions.yaml` rules and You-only boundaries: + +- **Live steps and `agent_report_step`**: starting a request (`Editor.StartAgentRequest` or `Editor.SubmitAgentPrompt`) immediately renders a gray placeholder step (within 300 ms). As `editormcp.Server` executes tool calls, each step streams in plain words with a violet spinner on the single active step and a green check once done. Agents can also call `agent_report_step` (`text`, optional `objects`, optional `status`) to report steps in their own words, name touched scene object IDs, and receive queued `"Add to this request"` follow-ups. +- **Interactive permission cards over `permissions.yaml`**: when a tool call evaluates to `ask` against `permissions.yaml` (after You-only boundary enforcement), `editormcp.Server` pauses that call on its goroutine without blocking the editor UI and renders an `alertdialog` permission card (`LiveRegionPolite`) in the Agent panel showing the title, why the agent wants it, its effect (such as *"Nothing is saved."*), the rule preview and source, and **Allow once**, **Always**, and **Deny**. +- **Focus and keyboard rules (Spec rules 02, 04, 05)**: a permission card never steals focus unless focus is already inside the Agent panel (`Editor.ShouldFocusAgentPrompt`); clicking the header **Waiting for you** chip focuses it on demand. While focused, `⌘↵` allows once, `⌥↵` persists an **Always** rule to `permissions.yaml` via `Editor.ApproveAlwaysPermission` (with the **Always permission rule saved** toast offering **Show** and **Undo**) so future identical calls run without asking, `⌘⌫` denies, `↑`/`↓` cycle buttons, and `Esc` leaves the card unanswered while the agent keeps waiting. +- **No automatic retry after denial**: denying a permission card records its `(action, target)` key on the active request, renders *"You denied … · continued without it"* with an explicit **Allow now** action, notes the unchecked item in the turn's review summary (such as *"Not playtested"*), and immediately returns a structured non-fatal `denied` response for any repeated identical call in the same request without re-opening a card. Starting a new request clears per-request denials. +- **Add to this request, Stop (`⌘.`), and concurrent manual editing**: while the agent works or waits, manual edits stay available and the bottom status bar reports what the agent is doing (*"manual edits stay available"*). The working footer keeps the **Add to this request** input focus-stable while steps stream (`Editor.AddToAgentRequest`). Pressing **Stop** or `⌘.` from anywhere—modal dialogs included—cancels the running request and any waiting Ask (`Editor.StopAgent`), keeps completed steps and scene edits pending for review (pausing autosave until kept or reverted), and shows the **Agent stopped** toast with **Review**; `Esc` never stops the agent. diff --git a/docs/zh/editor.md b/docs/zh/editor.md index 916ba0425..6cc2b8eb1 100644 --- a/docs/zh/editor.md +++ b/docs/zh/editor.md @@ -1593,7 +1593,6 @@ func main() { - **左上角可切换图例(`viewport-overlay-legend`)**:所有编辑态视口(2D 与 3D)在左上角挂载同一张图例卡片(`viewportOverlayLegendView`),提供 6 行无障碍 `role="switch"` 开关(**选中**、**智能体处理中**、**已添加**、**已修改**、**已移除**、**问题**),每行都绘出对应线型与第二线索。切换任一行(`Editor.ToggleOverlayKind`、`Editor.SetOverlayKindVisible`、`Editor.SetOverlayLegendKinds`)会立即在所有视口隐藏或显示该类叠加层,并将 `overlayLegend` 持久化到项目之外的用户级 `EditorSettings` YAML 文件(`Editor.SettingsPath`,绝不修改项目或场景文件)。 - **实时场景叠加层接口与问题对象关联**:实时智能体编辑、审查与计划通过 `Editor.SetSceneOverlays`、`AddSceneOverlay`、`RemoveSceneOverlay` 和 `ClearSceneOverlays`(`SceneOverlayEntry`)将叠加层附加到场景对象或已移除幽灵边界上。`assetcheck.Problem` 现包含 `Object` 字段(同时通过 `editormcp` 的 `game_check` 返回),覆盖场景对象、组件、覆写与连接诊断,使问题面板中指向当前打开场景对象的诊断会自动在 2D 与 3D 视口中绘制 Spec **问题**叠加层。 - **中性视口参考线**:相机取景框、相机边界、相机连线、瓦片网格与对齐网格统一迁移到中性 `SpecPalette` 令牌(`TextMuted` / `TextFaint` 1 px 细线与 `2, 4` 点线),与所有语义图例线型完全区分。 - ## 智能体输入框:@-提及、上下文标签与上下文计量环(#1020) 在统一右侧栏的 **智能体** 标签页(`RightRailView` / `AgentPanelView`,可通过 `⌘1` / `⌘2` 经 `CmdAgentTab` / `CmdInspectorTab` 切换)中,`AgentComposerView`(对应 `docs/design/editor/Threads.dc.html`,严格遵循 `Spec.dc.html` 令牌)提供 `@`-提及、显式上下文标签、精确悬停预览与实时上下文计量环: @@ -1614,3 +1613,13 @@ func main() { - **32 px 状态栏(`mainStatusBarView`)**:在 `bg` 表面以弱化文本呈现左侧的活动图层按钮(可切换图层面板)、实时 2D 指针坐标与当前工具,以及右侧的问题数胶囊(打开问题面板)、输出(Output)与调试器(Debugger)。原工具栏中的其余面板(设置、混音器、输入映射、多语言、导出、资源库、数据表、项目搜索、文件、资源、动画、粒子、材质、HUD 布局、地形、导航网格)全部保留,可通过命令面板(`⌘K`)、菜单栏、设置窗口与状态栏访问。 - **空状态、加载状态与错误状态(`WorkspaceState`、`SceneOpenError`)**:各区域均为 `WorkspaceNoProject`、`WorkspaceNoScene`、`WorkspaceLoading`(`SetProjectLoading`)和 `WorkspaceSceneError`(`SceneOpenError`、`RetryOpenScene`、`ClearSceneOpenError`)提供专门的界面状态。打开缺失或 YAML 格式错误的场景文件时,视口会展示带有路径、行/列号、错误描述、修复建议、**重试**和**关闭**按钮的告警卡片,而非空白视口。 - **规范控件与键盘可达性**:遵循 Spec 尺寸(行与工具按钮 `28 px`、按钮 `30–32 px`、顶部栏 `44 px`、状态栏 `32 px`,无小于 `28 × 28` 的交互热区)、间距(`4 / 8 / 12 / 16 / 24`)、圆角(`6 / 8`)、`base.RadioGroup` / `base.Radio` 与 `base.Switch` 语义、2 px Spec 焦点环、完整无障碍名称,以及覆盖全部五个区域的 `F6` 循环导航(顶部栏、场景树、视口、智能体/检视器、状态栏)。 + +## 智能体面板实时步骤、权限确认卡与停止(#1012) + +**智能体**面板(`RightRailView` 中的 `AgentPanelView`,`⌘1` / `⌘2` 切换)基于项目的 `permissions.yaml` 规则与“仅限你操作”边界,使用 `docs/design/editor/Spec.dc.html` 令牌(`Working.dc.html`、`Permissions.dc.html`、`Main.dc.html`、`AgentStates.dc.html`)实时展示步骤进度、交互式权限确认卡、补充指令与全局停止控制: + +- **实时步骤流与 `agent_report_step`**:发起请求(`Editor.StartAgentRequest` 或 `Editor.SubmitAgentPrompt`)后会立即显示灰色占位步骤(保证 300 ms 内可见)。当 `editormcp.Server` 执行工具调用时,每一步都会以平实语言实时流式呈现:当前唯一进行中的步骤显示紫色旋转图标,完成后切换为绿色对勾。智能体也可以调用 `agent_report_step`(`text`、可选 `objects`、可选 `status`)用自己的话汇报步骤、列出涉及的场景对象 ID,并接收用户通过「补充到此请求」排队的追加指令。 +- **基于 `permissions.yaml` 的交互式权限确认卡**:在先通过“仅限你操作”边界检查后,当工具调用按 `permissions.yaml` 规则求值为 `ask` 时,`editormcp.Server` 会在其自身 goroutine 上暂停该调用而不阻塞编辑器 UI,并在智能体面板中渲染 `alertdialog`(`LiveRegionPolite`)权限确认卡,展示标题、请求原因、影响说明(例如 *“不会保存任何内容。”*)、规则预览与命中规则来源,以及**仅允许一次**、**始终允许**与**拒绝**按钮。 +- **焦点纪律与键盘规则(规范规则 02、04、05)**:除非焦点已在智能体面板内部(`Editor.ShouldFocusAgentPrompt`),否则权限确认卡绝不抢夺焦点;点击顶部**等待你确认**状态条可按需聚焦到卡片。卡片获得焦点时,`⌘↵` 仅允许一次,`⌥↵` 通过 `Editor.ApproveAlwaysPermission` 将**始终允许**规则持久化写入 `permissions.yaml`(并弹出带**查看**与**撤销**按钮的提示条),后续同类调用不再弹窗,`⌘⌫` 拒绝,`↑`/`↓` 切换按钮,`Esc` 保持卡片未回答状态而智能体继续等待。 +- **拒绝后永不自动重试**:拒绝权限确认卡会在当前请求中记录对应的 `(action, target)` 键,将该步骤显示为 *“你拒绝了 … · 已跳过继续”* 并提供显式的**立即允许**操作,在回合审查摘要中标明未检查项(例如 *“Not playtested”*),并对同一请求中重复发起的相同调用立即返回非致命的结构化 `denied` 结果而不再次弹出卡片。发起新请求时才会清除单次请求的拒绝记录。 +- **补充到此请求、停止(`⌘.`)与并发手动编辑**:智能体工作或等待期间,手动编辑始终可用,底部状态栏会实时显示智能体当前动作(*“manual edits stay available”*)。工作态页脚的「补充到此请求」输入框(`Editor.AddToAgentRequest`)在步骤流式更新时保持焦点稳定。从任何位置(包括模态对话框内)点击**停止**或按下 `⌘.` 都会立即取消运行中的请求与等待中的权限确认(`Editor.StopAgent`),保留已完成步骤与场景编辑等待审查(期间暂停自动保存,直到保留或还原),并弹出带**审查**操作的**代理已停止**提示条;`Esc` 绝不会停止智能体。 diff --git a/packages/game/editor/agent.go b/packages/game/editor/agent.go index 9eaadd653..1647ca5bd 100644 --- a/packages/game/editor/agent.go +++ b/packages/game/editor/agent.go @@ -220,22 +220,38 @@ func (p AgentPermissions) Rules() []AgentPermissionRule { type AgentStepStatus string const ( + // AgentStepPlaceholder is the gray placeholder step shown immediately upon starting a request (within 300 ms) before the first real step arrives. + AgentStepPlaceholder AgentStepStatus = "placeholder" AgentStepPending AgentStepStatus = "pending" AgentStepRunning AgentStepStatus = "running" AgentStepDone AgentStepStatus = "done" AgentStepWaiting AgentStepStatus = "waiting" AgentStepWarning AgentStepStatus = "warning" AgentStepInterrupted AgentStepStatus = "interrupted" - AgentStepFailed AgentStepStatus = "failed" + // AgentStepDenied is a step the user denied, shown with "You denied … · continued without it" and an explicit Allow now action. + AgentStepDenied AgentStepStatus = "denied" + // AgentStepBlocked is a step stopped by a Deny permission rule without prompting. + AgentStepBlocked AgentStepStatus = "blocked" + // AgentStepStopped is the terminal row added when the user stops the agent with Stop or Mod+. + AgentStepStopped AgentStepStatus = "stopped" + AgentStepFailed AgentStepStatus = "failed" ) // AgentStep is a single visible step in an agent turn's progress list. type AgentStep struct { - ID string - Title string - Detail string - ToolName string - Status AgentStepStatus + ID string + Title string + Detail string + ToolName string + Objects []string + Status AgentStepStatus + CanAllowNow bool + allowNowFunc func() + PermissionKey string + RuleSummary string + RuleIndex int + UncheckedNote string + StartedAt time.Time } const ( @@ -262,7 +278,7 @@ type AgentTurnContext struct { } // AgentTurn is one user request (in-place ⌘L, Agent panel composer, terminal-initiated MCP turn, or background automation run) -// and its attached context, streamed steps, and reply. +// and its attached context, streamed steps, follow-ups, pending review, and reply. type AgentTurn struct { ID string `json:"id"` Prompt string `json:"prompt"` @@ -277,6 +293,10 @@ type AgentTurn struct { Model string `json:"model,omitempty"` Steps []AgentStep `json:"steps,omitempty"` PlannedSteps []string `json:"plannedSteps,omitempty"` + FollowUps []AgentFollowUp `json:"followUps,omitempty"` + NotChecked []string `json:"notChecked,omitempty"` + StoppedBefore string `json:"stoppedBefore,omitempty"` + PendingReview *AgentPendingReview `json:"pendingReview,omitempty"` Summary string `json:"summary,omitempty"` Reply string `json:"reply,omitempty"` Error string `json:"error,omitempty"` @@ -302,6 +322,7 @@ type AgentTurn struct { CheckpointID string `json:"checkpointId,omitempty"` // checkpoint captured before the automation started ReviewState AgentReviewState `json:"reviewState,omitempty"` // lifecycle state for Ready to review / Kept / Dismissed / Failed + turnStartHistoryIdx int baselineDoc *sceneformat.SceneDoc baselineYAML string baselineFile string @@ -487,6 +508,21 @@ type agentState struct { externalBaselineFile string externalHistoryStart int externalBaselineIDs map[string]struct{} + + // Live MCP request streaming, permission card, follow-up, and Stop state (#1012). + liveRequestID uint64 + liveRequestActive bool + liveStopped bool + liveStopCh chan struct{} + liveStepSeq uint64 + liveAskSeq uint64 + livePendingAsk *agentPendingAskHandle + liveDeniedKeys map[string]bool + liveQueuedFollowUps []string + liveActivity string + liveFocusCardSeq uint64 + liveFocusReviewSeq uint64 + livePermCardFocused bool } func (a *agentState) setScope(cx *core.Scope) { @@ -610,6 +646,9 @@ func (e *Editor) stopAgentTimers() { e.stopAutomationRunsAndScheduler() e.agent.activeRetryNow = nil e.agent.activeTurnID = "" + e.resolvePendingLiveAskLocked(PermissionOutcomeStopped) + e.closeLiveStopChLocked() + e.agent.liveRequestActive = false e.agent.connectAPIKey = "" } @@ -661,6 +700,11 @@ func (e *Editor) resetAgentForProject() { e.agent.externalBaselineFile = "" e.agent.externalHistoryStart = 0 e.agent.externalBaselineIDs = nil + e.agent.liveStopped = false + e.agent.liveDeniedKeys = nil + e.agent.liveQueuedFollowUps = nil + e.agent.liveActivity = "" + e.agent.livePermCardFocused = false if e.agent.mode == AgentModeAPIKey && e.HasAgentAPIKey(DefaultAgentAPIKeyAccount) { if e.AgentWeeklyLimitReached() { e.agent.status = AgentStatusLimitReached @@ -1458,9 +1502,16 @@ func (e *Editor) AgentWaitingElapsed() string { return fmt.Sprintf("%d:%02d", secs/60, secs%60) } -// FocusOpenAgentRequest opens the Agent panel and focuses the open waiting request. +// FocusOpenAgentRequest opens the Agent panel and focuses the open waiting request or permission card. func (e *Editor) FocusOpenAgentRequest() { - if e == nil || e.agent.openRequest == nil { + if e == nil { + return + } + if e.agent.livePendingAsk != nil && !e.agent.livePendingAsk.resolved { + e.FocusPermissionCard() + return + } + if e.agent.openRequest == nil { return } if e.agent.mode != AgentModeNone { @@ -1507,7 +1558,15 @@ func (e *Editor) InsertAgentComposerNewline() { } func cloneAgentTurn(t AgentTurn) AgentTurn { - t.Steps = slices.Clone(t.Steps) + if len(t.Steps) > 0 { + steps := make([]AgentStep, len(t.Steps)) + for i, s := range t.Steps { + s.Objects = slices.Clone(s.Objects) + s.allowNowFunc = nil + steps[i] = s + } + t.Steps = steps + } if len(t.Images) > 0 { imgs := make([]AgentReferenceImage, len(t.Images)) for i, img := range t.Images { @@ -1516,6 +1575,13 @@ func cloneAgentTurn(t AgentTurn) AgentTurn { t.Images = imgs } t.PlannedSteps = slices.Clone(t.PlannedSteps) + t.FollowUps = slices.Clone(t.FollowUps) + t.NotChecked = slices.Clone(t.NotChecked) + if t.PendingReview != nil { + cp := *t.PendingReview + cp.NotChecked = slices.Clone(t.PendingReview.NotChecked) + t.PendingReview = &cp + } t.Context.SelectionIDs = slices.Clone(t.Context.SelectionIDs) t.Context.SelectionNames = slices.Clone(t.Context.SelectionNames) t.Context.ViewportPNG = slices.Clone(t.Context.ViewportPNG) @@ -1690,13 +1756,23 @@ func (e *Editor) AgentSessionID() string { return e.agent.sessionID } -// AgentWorking reports whether a composer request is currently running. +// AgentWorking reports whether an agent request (composer runner or live MCP session) is currently working or waiting for permission. func (e *Editor) AgentWorking() bool { - return e != nil && e.agent.activeRunCancel != nil + if e == nil { + return false + } + return e.agent.activeRunCancel != nil || e.agent.liveRequestActive || e.agent.status == AgentStatusWorking || e.agent.status == AgentStatusWaitingForYou } // RecordExternalAgentToolCall records a tool call executed by a terminal-started MCP session so its work appears as an agent turn in the panel. func (e *Editor) RecordExternalAgentToolCall(clientName, toolName, summary string, isErr bool) { + if e == nil || e.agent.mode == AgentModeNone { + return + } + // If a live MCP turn is active or was just stopped, live step streaming owns the steps. + if e.agent.liveRequestActive || e.agent.liveStopped { + return + } e.RecordAgentToolCall(AgentToolCallRecord{ ClientName: clientName, ToolName: toolName, @@ -1711,46 +1787,10 @@ func (e *Editor) SubmitAgentPrompt(prompt string) error { return e.SubmitAgentTaskPrompt(AgentTaskSceneEdit, prompt) } -// StopAgentRun cancels the currently running composer request, keeping completed steps visible, +// StopAgentRun cancels the currently running agent request, keeping completed steps visible, // recording done and not-done steps for Resume, and leaving changes unkept until reviewed. func (e *Editor) StopAgentRun() { - if e == nil || e.agent.activeRunCancel == nil { - return - } - if e.agent.activeRetryCancel != nil { - e.agent.activeRetryCancel() - e.agent.activeRetryCancel = nil - } - e.agent.activeRetryNow = nil - e.agent.activeRunID++ - cancel := e.agent.activeRunCancel - stoppedTurnID := e.agent.activeTurnID - e.agent.activeRunCancel = nil - e.agent.activeTurnID = "" - cancel() - if e.agent.openRequest != nil && stoppedTurnID != "" && - (e.agent.openRequest.ID == stoppedTurnID || e.waitingTurnTaskID() == stoppedTurnID) { - e.agent.openRequest = nil - e.clearWaitingTurnTaskID() - } - if n := len(e.agent.turns); n > 0 && !e.agent.turns[n-1].Done { - turn := &e.agent.turns[n-1] - turn.Stopped = true - turn.Done = true - turn.Status = "stopped" - turn.FinishedAt = e.nowTime() - if turn.ModelError != nil { - turn.ModelError.Retrying = false - } - e.populateStoppedTurnState(turn) - } - e.agent.turnChangeSeq++ - e.restoreIdleAgentStatus() - if stoppedTurnID != "" { - e.removeTurnNotificationTask(stoppedTurnID) - return - } - e.notify() + e.StopAgent() } func (e *Editor) findAgentTurn(turnID string) *AgentTurn { @@ -1790,10 +1830,18 @@ func (e *Editor) applyAgentEventForRun(runID uint64, turnID string, ev AgentEven e.agent.sessionID = ev.SessionID } case AgentEventStep: + dropTurnPlaceholder(turn) stepStatus := ev.StepStatus if stepStatus == "" { stepStatus = AgentStepRunning } + if stepStatus == AgentStepRunning { + for i := range turn.Steps { + if turn.Steps[i].Status == AgentStepRunning && (ev.StepID == "" || turn.Steps[i].ID != ev.StepID) { + turn.Steps[i].Status = AgentStepDone + } + } + } updated := false resolvedToolName := ev.ToolName if ev.StepID != "" { @@ -1822,13 +1870,17 @@ func (e *Editor) applyAgentEventForRun(runID uint64, turnID string, ev AgentEven stepID = fmt.Sprintf("%s-step-%d", turn.ID, len(turn.Steps)+1) } turn.Steps = append(turn.Steps, AgentStep{ - ID: stepID, - Title: ev.StepTitle, - Detail: ev.StepDetail, - ToolName: ev.ToolName, - Status: stepStatus, + ID: stepID, + Title: ev.StepTitle, + Detail: ev.StepDetail, + ToolName: ev.ToolName, + Status: stepStatus, + StartedAt: e.nowTime(), }) } + if stepStatus == AgentStepRunning && ev.StepTitle != "" { + e.agent.liveActivity = fmt.Sprintf("Agent: %s · manual edits stay available", ev.StepTitle) + } if ev.StepIndex > 0 { e.agent.workingStep = ev.StepIndex } else { @@ -1892,6 +1944,7 @@ func (e *Editor) applyAgentEventForRun(runID uint64, turnID string, ev AgentEven case AgentEventModelRecovered: turn.ModelError = nil case AgentEventDone: + dropTurnPlaceholder(turn) if ev.Text != "" && turn.Summary == "" { turn.Summary = ev.Text turn.Reply = ev.Text @@ -1927,8 +1980,11 @@ func (e *Editor) finishAgentRun(runID uint64, turnID string, err error, canceled if e.agent.activeTurnID == turnID { e.agent.activeTurnID = "" } + e.agent.liveRequestActive = false + e.agent.liveActivity = "" turn := e.findAgentTurn(turnID) if turn != nil && !turn.Done { + dropTurnPlaceholder(turn) turn.Done = true turn.FinishedAt = e.nowTime() if canceled { @@ -1963,6 +2019,9 @@ func (e *Editor) finishAgentRun(runID uint64, turnID string, err error, canceled if turn.Summary != "" && turn.Mismatch == nil { turn.Mismatch = CheckAgentSummaryAgainstDiff(turn.Summary, turn.Review, turn.mutations) } + if len(turn.NotChecked) > 0 && turn.PendingReview == nil { + turn.PendingReview = e.buildTurnPendingReviewLocked(turn, turn.Summary, false) + } } if e.agent.openRequest != nil && turnID != "" && (e.agent.openRequest.ID == turnID || e.waitingTurnTaskID() == turnID) { @@ -1971,7 +2030,7 @@ func (e *Editor) finishAgentRun(runID uint64, turnID string, err error, canceled } e.agent.turnChangeSeq++ e.restoreIdleAgentStatus() - if !e.HasUnkeptAgentTurnReview() { + if !e.HasUnkeptAgentTurnReview() && !e.HasPendingAgentTurnReview() { e.scheduleAutoSaveIfNeeded() } else { e.cancelAutoSaveTimer() diff --git a/packages/game/editor/agent_builtin.go b/packages/game/editor/agent_builtin.go index e5c4134c2..efc8f8536 100644 --- a/packages/game/editor/agent_builtin.go +++ b/packages/game/editor/agent_builtin.go @@ -634,6 +634,8 @@ func (e *Editor) submitAgentTaskPromptInternal(task AgentTaskKind, prompt string req.BriefImages = briefImgs req.Images = allImgs + e.resolvePendingLiveAskLocked(PermissionOutcomeStopped) + e.closeLiveStopChLocked() if fromComposer || text == strings.TrimSpace(e.composerDraft) || text == strings.TrimSpace(e.agent.composerText) { e.composerDraft = "" e.agent.composerText = "" @@ -648,6 +650,8 @@ func (e *Editor) submitAgentTaskPromptInternal(task AgentTaskKind, prompt string e.agentComposer.hoveredChipID = "" e.agent.turnSeq++ e.agent.turnChangeSeq++ + e.agent.liveRequestID++ + e.agent.liveStepSeq++ turnID := fmt.Sprintf("turn-%d", e.agent.turnSeq) agentKind := ExternalAgentAuto if !route.IsBuiltIn() { @@ -666,6 +670,10 @@ func (e *Editor) submitAgentTaskPromptInternal(task AgentTaskKind, prompt string cp.Data = nil turnImages[i] = cp } + startHist := 0 + if e.History != nil { + startHist = e.History.Index() + } e.agent.turns = append(e.agent.turns, AgentTurn{ ID: turnID, Prompt: text, @@ -676,11 +684,24 @@ func (e *Editor) submitAgentTaskPromptInternal(task AgentTaskKind, prompt string Task: task, Route: route, Model: model, - CreatedAt: now, - StartedAt: now, + Steps: []AgentStep{{ + ID: fmt.Sprintf("step-%d", e.agent.liveStepSeq), + Title: "Starting request…", + Status: AgentStepPlaceholder, + StartedAt: now, + }}, + CreatedAt: now, + StartedAt: now, + turnStartHistoryIdx: startHist, }) e.trimAgentTurnAttachments() e.initTurnBaseline(&e.agent.turns[len(e.agent.turns)-1]) + e.agent.liveRequestActive = true + e.agent.liveStopped = false + e.agent.liveStopCh = make(chan struct{}) + e.agent.liveDeniedKeys = make(map[string]bool) + e.agent.liveQueuedFollowUps = nil + e.agent.liveActivity = "Agent is working · manual edits stay available" e.agent.activeRunID++ runID := e.agent.activeRunID diff --git a/packages/game/editor/agent_live_steps.go b/packages/game/editor/agent_live_steps.go new file mode 100644 index 000000000..620eb2845 --- /dev/null +++ b/packages/game/editor/agent_live_steps.go @@ -0,0 +1,1194 @@ +package editor + +import ( + "errors" + "fmt" + "maps" + "slices" + "strings" + "time" +) + +const ( + maxLiveAgentStepsPerTurn = 512 + maxLiveAgentFollowUps = 64 + maxAgentStepTextBytes = 4096 + maxAgentFollowUpBytes = 32 << 10 + maxAgentStepObjects = 128 +) + +// AgentPermissionOutcome is the person's answer to an interactive Agent panel permission card (or Stop interrupting it). +type AgentPermissionOutcome string + +const ( + PermissionOutcomeAllowOnce AgentPermissionOutcome = "allow_once" + PermissionOutcomeAllowAlways AgentPermissionOutcome = "allow_always" + PermissionOutcomeDeny AgentPermissionOutcome = "deny" + PermissionOutcomeStopped AgentPermissionOutcome = "stopped" +) + +// AgentPermissionPrompt describes an open interactive permission card rendered inside the Agent panel. +type AgentPermissionPrompt struct { + ID string + StepID string + Title string + ShortAction string + Why string + Effect string + RuleSource string + RulePreview string + AlwaysLabel string + Tool string + PermissionKey string + Evaluation PermissionEvaluation + AskedAt time.Time +} + +// AgentFollowUp is an additional instruction sent via "Add to this request" while an agent request is running. +type AgentFollowUp struct { + Text string `json:"text"` + SentAt time.Time `json:"sentAt"` +} + +// AgentPendingReview summarizes completed steps and edits left pending for review after a turn finishes or is stopped. +type AgentPendingReview struct { + StepsDone int `json:"stepsDone"` + ChangesCount int `json:"changesCount"` + Summary string `json:"summary,omitempty"` + NotChecked []string `json:"notChecked,omitempty"` + Stopped bool `json:"stopped,omitempty"` + StoppedBefore string `json:"stoppedBefore,omitempty"` + Kept bool `json:"kept,omitempty"` + Reverted bool `json:"reverted,omitempty"` +} + +// AgentSessionSnapshot is an immutable snapshot of the active or most recent Agent panel turn and live permission card. +type AgentSessionSnapshot struct { + RequestID uint64 + TurnID string + Status AgentStatus + Stopped bool + Prompt string + Steps []AgentStep + PendingAsk *AgentPermissionPrompt + FollowUps []AgentFollowUp + Review *AgentPendingReview + Activity string + StartedAt time.Time + Elapsed time.Duration + WaitingElapsed time.Duration + DeniedKeysCount int +} + +type agentPendingAskHandle struct { + ask AgentPermissionPrompt + respCh chan AgentPermissionOutcome + resolved bool +} + +func cloneAgentPermissionPrompt(ask AgentPermissionPrompt) AgentPermissionPrompt { + if ask.Evaluation.Rule != nil { + cp := ask.Evaluation.Rule.Clone() + ask.Evaluation.Rule = &cp + } + return ask +} + +func dropTurnPlaceholder(turn *AgentTurn) { + if turn == nil || len(turn.Steps) == 0 { + return + } + out := turn.Steps[:0] + for _, s := range turn.Steps { + if s.Status != AgentStepPlaceholder { + out = append(out, s) + } + } + turn.Steps = out +} + +func completedTurnStepCount(turn *AgentTurn) int { + if turn == nil { + return 0 + } + n := 0 + for _, s := range turn.Steps { + if s.Status == AgentStepDone { + n++ + } + } + return n +} + +func (e *Editor) latestAgentTurnPtr() *AgentTurn { + if e == nil || len(e.agent.turns) == 0 { + return nil + } + return &e.agent.turns[len(e.agent.turns)-1] +} + +func (e *Editor) closeLiveStopChLocked() { + if e.agent.liveStopCh == nil { + return + } + select { + case <-e.agent.liveStopCh: + default: + close(e.agent.liveStopCh) + } +} + +func (e *Editor) resolvePendingLiveAskLocked(outcome AgentPermissionOutcome) { + if e.agent.livePendingAsk == nil || e.agent.livePendingAsk.resolved { + return + } + e.agent.livePendingAsk.resolved = true + select { + case e.agent.livePendingAsk.respCh <- outcome: + default: + } + e.agent.livePendingAsk = nil + e.agent.livePermCardFocused = false + if e.agent.openRequest != nil && strings.HasPrefix(e.agent.openRequest.ID, "ask-") { + e.agent.openRequest = nil + } +} + +// HasActiveLiveAgentRequest reports whether an interactive agent request (started via StartAgentRequest or SubmitAgentPrompt) is currently active. +func (e *Editor) HasActiveLiveAgentRequest() bool { + if e == nil { + return false + } + return e.agent.liveRequestActive || e.agent.activeRunCancel != nil +} + +// AgentStopped reports whether the most recent live request was stopped by the user and has not yet been superseded by a new request. +func (e *Editor) AgentStopped() bool { + if e == nil { + return false + } + return e.agent.liveStopped && !e.agent.liveRequestActive && e.agent.activeRunCancel == nil +} + +// PendingAgentPermissionAsk returns a copy of the currently open interactive permission card, or nil. +func (e *Editor) PendingAgentPermissionAsk() *AgentPermissionPrompt { + if e == nil || e.agent.livePendingAsk == nil || e.agent.livePendingAsk.resolved { + return nil + } + cp := cloneAgentPermissionPrompt(e.agent.livePendingAsk.ask) + return &cp +} + +// AgentStatusBarText returns the bottom status-bar message describing what the agent is currently doing +// while reminding the person that manual edits stay available, or empty when the agent is idle. +func (e *Editor) AgentStatusBarText() string { + if e == nil { + return "" + } + switch e.agent.status { + case AgentStatusWaitingForYou: + if e.agent.livePendingAsk != nil && !e.agent.livePendingAsk.resolved && e.agent.livePendingAsk.ask.ShortAction != "" { + return fmt.Sprintf("Waiting for you · %s · manual edits stay available", e.agent.livePendingAsk.ask.ShortAction) + } + if e.agent.openRequest != nil && e.agent.openRequest.Title != "" { + return fmt.Sprintf("Waiting for you · %s · manual edits stay available", e.agent.openRequest.Title) + } + return "Waiting for you · manual edits stay available" + case AgentStatusWorking: + if e.agent.liveActivity != "" { + return e.agent.liveActivity + } + return "Agent is working · manual edits stay available" + default: + return "" + } +} + +// AgentSession returns an immutable snapshot of the active or latest live Agent panel turn and permission state. +func (e *Editor) AgentSession() AgentSessionSnapshot { + if e == nil { + return AgentSessionSnapshot{Status: AgentStatusNotConnected} + } + now := e.nowTime() + snap := AgentSessionSnapshot{ + RequestID: e.agent.liveRequestID, + Status: e.AgentStatus(), + Stopped: e.AgentStopped(), + Activity: e.agent.liveActivity, + DeniedKeysCount: len(e.agent.liveDeniedKeys), + } + if turn := e.latestAgentTurnPtr(); turn != nil { + cp := cloneAgentTurn(*turn) + snap.TurnID = cp.ID + snap.Prompt = cp.Prompt + snap.Steps = cp.Steps + snap.FollowUps = cp.FollowUps + snap.Review = cp.PendingReview + snap.StartedAt = cp.StartedAt + if !cp.StartedAt.IsZero() && (snap.Status == AgentStatusWorking || snap.Status == AgentStatusWaitingForYou) { + snap.Elapsed = max(0, now.Sub(cp.StartedAt)) + } + } + if ask := e.PendingAgentPermissionAsk(); ask != nil { + snap.PendingAsk = ask + if !ask.AskedAt.IsZero() { + snap.WaitingElapsed = max(0, now.Sub(ask.AskedAt)) + } + } + return snap +} + +// StartAgentRequest begins a new live agent request in the Agent panel, clears prior per-request denials +// so the agent may ask again on a new request, and immediately displays a gray placeholder step (within 300 ms). +func (e *Editor) StartAgentRequest(prompt string) uint64 { + if e == nil { + return 0 + } + prompt = strings.TrimSpace(prompt) + if len(prompt) > maxAgentFollowUpBytes { + prompt = prompt[:maxAgentFollowUpBytes] + } + if e.agent.activeRunCancel != nil { + e.agent.activeRunID++ + cancel := e.agent.activeRunCancel + e.agent.activeRunCancel = nil + cancel() + } + e.resolvePendingLiveAskLocked(PermissionOutcomeStopped) + e.closeLiveStopChLocked() + + now := e.nowTime() + e.agent.liveRequestID++ + e.agent.turnSeq++ + e.agent.turnChangeSeq++ + e.agent.liveStepSeq++ + turnID := fmt.Sprintf("turn-%d", e.agent.turnSeq) + startHist := 0 + if e.History != nil { + startHist = e.History.Index() + } + clientName := "" + if c, ok := e.AgentPrimaryClient(); ok { + clientName = c.DisplayName + } + e.agent.turns = append(e.agent.turns, AgentTurn{ + ID: turnID, + Prompt: prompt, + Source: "panel", + Status: "running", + AgentName: clientName, + Steps: []AgentStep{{ + ID: fmt.Sprintf("step-%d", e.agent.liveStepSeq), + Title: "Starting request…", + Status: AgentStepPlaceholder, + StartedAt: now, + }}, + CreatedAt: now, + StartedAt: now, + turnStartHistoryIdx: startHist, + }) + e.trimAgentTurnAttachments() + e.initTurnBaseline(&e.agent.turns[len(e.agent.turns)-1]) + e.agent.liveRequestActive = true + e.agent.liveStopped = false + e.agent.liveStopCh = make(chan struct{}) + e.agent.liveDeniedKeys = make(map[string]bool) + e.agent.liveQueuedFollowUps = nil + e.agent.liveActivity = "Agent is working · manual edits stay available" + e.agent.status = AgentStatusWorking + e.agent.workingStep = 1 + e.agent.workingTotal = 0 + e.updateAgentAnnouncement() + e.notify() + if e.OnStartAgentRequest != nil && prompt != "" { + e.OnStartAgentRequest(prompt) + } + return e.agent.liveRequestID +} + +// EnsureAgentRequest returns the active request ID and stop channel, or starts an implicit live request +// when an external MCP client begins calling tools while the editor is idle. +func (e *Editor) EnsureAgentRequest(prompt string) (uint64, <-chan struct{}) { + if e == nil { + return 0, nil + } + if e.agent.liveRequestActive || e.agent.activeRunCancel != nil { + if e.agent.liveStopCh == nil { + e.agent.liveStopCh = make(chan struct{}) + } + return e.agent.liveRequestID, e.agent.liveStopCh + } + if e.AgentStopped() { + return e.agent.liveRequestID, e.agent.liveStopCh + } + id := e.StartAgentRequest(prompt) + return id, e.agent.liveStopCh +} + +func (e *Editor) ensureLiveTurnLocked() *AgentTurn { + turn := e.latestAgentTurnPtr() + if turn == nil || turn.Done || turn.Stopped { + e.StartAgentRequest("") + turn = e.latestAgentTurnPtr() + } + return turn +} + +// BeginAgentToolStep appends a new active running step (with spinner) for a tool call, +// removing the initial placeholder step and enforcing at most one running spinner at a time. +func (e *Editor) BeginAgentToolStep(tool, text, activity string, objects []string) string { + if e == nil { + return "" + } + turn := e.ensureLiveTurnLocked() + if turn == nil { + return "" + } + dropTurnPlaceholder(turn) + // Reuse an already-running step for the same tool (e.g., emitted by builtInAgentRunner + // immediately before invoking the MCP tool) instead of duplicating it. + if tool != "" && len(turn.Steps) > 0 { + last := &turn.Steps[len(turn.Steps)-1] + if last.Status == AgentStepRunning && last.ToolName == tool { + if t := strings.TrimSpace(text); t != "" { + last.Title = t + } + if cleanObjs := sanitizeStepObjects(objects); len(cleanObjs) > 0 { + last.Objects = cleanObjs + } + e.agent.liveRequestActive = true + e.agent.status = AgentStatusWorking + e.agent.workingStep = max(1, len(turn.Steps)) + if activity != "" { + e.agent.liveActivity = activity + } else if text != "" { + e.agent.liveActivity = fmt.Sprintf("Agent: %s · manual edits stay available", text) + } + e.agent.turnChangeSeq++ + e.updateAgentAnnouncement() + e.notify() + return last.ID + } + } + for i := range turn.Steps { + if turn.Steps[i].Status == AgentStepRunning { + turn.Steps[i].Status = AgentStepDone + } + } + e.agent.liveStepSeq++ + id := fmt.Sprintf("step-%d", e.agent.liveStepSeq) + if len(turn.Steps) >= maxLiveAgentStepsPerTurn { + turn.Steps = turn.Steps[len(turn.Steps)-maxLiveAgentStepsPerTurn+1:] + } + turn.Steps = append(turn.Steps, AgentStep{ + ID: id, + Title: strings.TrimSpace(text), + ToolName: tool, + Objects: sanitizeStepObjects(objects), + Status: AgentStepRunning, + StartedAt: e.nowTime(), + }) + e.agent.liveRequestActive = true + e.agent.status = AgentStatusWorking + e.agent.workingStep = max(1, len(turn.Steps)) + if activity != "" { + e.agent.liveActivity = activity + } else if text != "" { + e.agent.liveActivity = fmt.Sprintf("Agent: %s · manual edits stay available", text) + } + e.agent.turnChangeSeq++ + e.updateAgentAnnouncement() + e.notify() + return id +} + +// FinishAgentToolStep marks stepID done (or failed) with its plain-words result summary. +func (e *Editor) FinishAgentToolStep(stepID, text, detail string, objects []string, failed bool) { + if e == nil || stepID == "" { + return + } + turn := e.latestAgentTurnPtr() + if turn == nil { + return + } + for i := range turn.Steps { + if turn.Steps[i].ID != stepID { + continue + } + if turn.Steps[i].Status == AgentStepStopped || turn.Steps[i].Status == AgentStepDenied || turn.Steps[i].Status == AgentStepBlocked { + return + } + if strings.TrimSpace(text) != "" { + turn.Steps[i].Title = strings.TrimSpace(text) + } + if detail != "" { + turn.Steps[i].Detail = detail + } + if cleanObjs := sanitizeStepObjects(objects); len(cleanObjs) > 0 { + turn.Steps[i].Objects = cleanObjs + } + if failed { + turn.Steps[i].Status = AgentStepFailed + } else { + turn.Steps[i].Status = AgentStepDone + } + break + } + if e.agent.status == AgentStatusWorking { + e.agent.liveActivity = "Agent is working · manual edits stay available" + } + e.agent.turnChangeSeq++ + e.notify() +} + +// ReportAgentStep records a step reported directly by the agent in its own words (via agent_report_step), +// along with the scene object IDs it touches. +func (e *Editor) ReportAgentStep(text string, objects []string, running bool) string { + if e == nil { + return "" + } + text = strings.TrimSpace(text) + if text == "" || strings.IndexByte(text, 0) >= 0 { + return "" + } + if len(text) > maxAgentStepTextBytes { + text = text[:maxAgentStepTextBytes] + } + turn := e.ensureLiveTurnLocked() + if turn == nil { + return "" + } + dropTurnPlaceholder(turn) + if running { + for i := range turn.Steps { + if turn.Steps[i].Status == AgentStepRunning { + turn.Steps[i].Status = AgentStepDone + } + } + } + e.agent.liveStepSeq++ + id := fmt.Sprintf("step-%d", e.agent.liveStepSeq) + st := AgentStepDone + if running { + st = AgentStepRunning + e.agent.liveActivity = fmt.Sprintf("Agent: %s · manual edits stay available", text) + } + if len(turn.Steps) >= maxLiveAgentStepsPerTurn { + turn.Steps = turn.Steps[len(turn.Steps)-maxLiveAgentStepsPerTurn+1:] + } + turn.Steps = append(turn.Steps, AgentStep{ + ID: id, + Title: text, + ToolName: "agent_report_step", + Objects: sanitizeStepObjects(objects), + Status: st, + StartedAt: e.nowTime(), + }) + e.agent.workingStep = max(1, len(turn.Steps)) + e.agent.turnChangeSeq++ + e.updateAgentAnnouncement() + e.notify() + return id +} + +// RecordBlockedAgentStep records a step stopped by a Deny permission rule in the live Agent panel thread, +// keeping its RuleIndex so clicking it opens Settings › Permissions at the exact matching rule. +func (e *Editor) RecordBlockedAgentStep(tool, text string, eval PermissionEvaluation) string { + if e == nil { + return "" + } + turn := e.ensureLiveTurnLocked() + if turn == nil { + return "" + } + dropTurnPlaceholder(turn) + e.agent.liveStepSeq++ + id := fmt.Sprintf("step-%d", e.agent.liveStepSeq) + ruleSummary := eval.Reason + if eval.Rule != nil { + ruleSummary = eval.Rule.Summary() + } + if len(turn.Steps) >= maxLiveAgentStepsPerTurn { + turn.Steps = turn.Steps[len(turn.Steps)-maxLiveAgentStepsPerTurn+1:] + } + turn.Steps = append(turn.Steps, AgentStep{ + ID: id, + Title: strings.TrimSpace(text), + ToolName: tool, + RuleSummary: ruleSummary, + RuleIndex: eval.RuleIndex, + Status: AgentStepBlocked, + StartedAt: e.nowTime(), + }) + e.agent.turnChangeSeq++ + e.notify() + return id +} + +// BeginAgentPermissionAsk installs an open permission card inside the Agent panel for ask. +// If ask.PermissionKey was already denied in the active request, it returns (nil, stopCh, true) immediately +// without showing a card so denials are never retried automatically. +func (e *Editor) BeginAgentPermissionAsk(ask AgentPermissionPrompt) (respCh <-chan AgentPermissionOutcome, stopCh <-chan struct{}, alreadyDenied bool) { + if e == nil { + return nil, nil, false + } + if e.AgentStopped() { + ch := make(chan AgentPermissionOutcome, 1) + ch <- PermissionOutcomeStopped + return ch, e.agent.liveStopCh, false + } + turn := e.ensureLiveTurnLocked() + if e.agent.liveStopCh == nil { + e.agent.liveStopCh = make(chan struct{}) + } + if ask.PermissionKey != "" && e.agent.liveDeniedKeys[ask.PermissionKey] { + return nil, e.agent.liveStopCh, true + } + // If another ask is somehow still open, resolve it cleanly before replacing. + e.resolvePendingLiveAskLocked(PermissionOutcomeStopped) + + dropTurnPlaceholder(turn) + e.agent.liveAskSeq++ + if ask.ID == "" { + ask.ID = fmt.Sprintf("ask-%d", e.agent.liveAskSeq) + } + if ask.AskedAt.IsZero() { + ask.AskedAt = e.nowTime() + } + if ask.RulePreview == "" { + if rule := AlwaysRuleForEvaluation(ask.Evaluation); len(rule.Patterns) > 0 { + ask.RulePreview = rule.Summary() + } + } + if ask.RuleSource == "" { + ask.RuleSource = ask.Evaluation.Reason + } + if turn != nil && ask.StepID != "" { + for i := range turn.Steps { + if turn.Steps[i].ID == ask.StepID { + turn.Steps[i].Status = AgentStepWaiting + turn.Steps[i].Detail = "waiting for you" + turn.Steps[i].PermissionKey = ask.PermissionKey + break + } + } + } + ch := make(chan AgentPermissionOutcome, 1) + stored := cloneAgentPermissionPrompt(ask) + e.agent.livePendingAsk = &agentPendingAskHandle{ + ask: stored, + respCh: ch, + } + // Sync AgentOpenRequest so the header status chip renders "Waiting for you · M:SS". + e.agent.openRequest = &AgentOpenRequest{ + ID: stored.ID, + Title: stored.Title, + Body: stored.Why, + OpenedAt: stored.AskedAt, + } + e.agent.status = AgentStatusWaitingForYou + // Spec rule 05: only auto-focus the permission card when focus is already inside the Agent panel + // and neither a drag nor text input is active. + if e.ShouldFocusAgentPrompt() { + e.agent.liveFocusCardSeq++ + } + e.agent.turnChangeSeq++ + e.updateAgentAnnouncement() + e.notify() + return ch, e.agent.liveStopCh, false +} + +// CancelPendingAgentPermissionAsk dismisses the open permission card if its ID still matches askID +// (used when an MCP client cancels or disconnects while waiting on a permission card). +func (e *Editor) CancelPendingAgentPermissionAsk(askID string) { + if e == nil || askID == "" || e.agent.livePendingAsk == nil || e.agent.livePendingAsk.resolved { + return + } + if e.agent.livePendingAsk.ask.ID != askID { + return + } + stepID := e.agent.livePendingAsk.ask.StepID + e.resolvePendingLiveAskLocked(PermissionOutcomeStopped) + if turn := e.latestAgentTurnPtr(); turn != nil && stepID != "" { + for i := range turn.Steps { + if turn.Steps[i].ID == stepID && turn.Steps[i].Status == AgentStepWaiting { + turn.Steps[i].Status = AgentStepFailed + turn.Steps[i].Detail = "canceled" + break + } + } + } + if e.agent.liveRequestActive || e.agent.activeRunCancel != nil { + e.agent.status = AgentStatusWorking + } else { + e.restoreIdleAgentStatus() + } + e.agent.turnChangeSeq++ + e.updateAgentAnnouncement() + e.notify() +} + +// FocusPermissionCard opens the Agent panel and requests keyboard focus for the active permission card +// (for example when clicking the header "Waiting for you" chip). +func (e *Editor) FocusPermissionCard() { + if e == nil || e.agent.livePendingAsk == nil || e.agent.livePendingAsk.resolved { + return + } + if e.agent.mode != AgentModeNone { + e.agent.rightTab = RightTabAgent + } + e.agent.liveFocusCardSeq++ + e.agent.focusRequestCalled++ + if e.OnFocusAgentRequest != nil && e.agent.openRequest != nil { + e.OnFocusAgentRequest(*e.agent.openRequest) + } + e.notify() +} + +// AllowPermissionOnce approves the open permission card for this single call only. +func (e *Editor) AllowPermissionOnce() bool { + if e == nil || e.agent.livePendingAsk == nil || e.agent.livePendingAsk.resolved { + return false + } + ask := cloneAgentPermissionPrompt(e.agent.livePendingAsk.ask) + e.resolvePendingLiveAskLocked(PermissionOutcomeAllowOnce) + e.updateLiveAskStepRunningLocked(ask, "allowed once") + e.agent.status = AgentStatusWorking + e.agent.turnChangeSeq++ + e.updateAgentAnnouncement() + e.notify() + return true +} + +// AllowPermissionAlways inserts and persists the concrete Allow rule into permissions.yaml via ApproveAlwaysPermission +// (which also displays the "Always permission rule saved" toast with Show and Undo) and approves the waiting call. +func (e *Editor) AllowPermissionAlways() bool { + if e == nil || e.agent.livePendingAsk == nil || e.agent.livePendingAsk.resolved { + return false + } + ask := cloneAgentPermissionPrompt(e.agent.livePendingAsk.ask) + if _, err := e.ApproveAlwaysPermission(ask.Evaluation); err != nil { + e.report(err) + return false + } + e.resolvePendingLiveAskLocked(PermissionOutcomeAllowAlways) + e.updateLiveAskStepRunningLocked(ask, "allowed by your new rule") + e.agent.status = AgentStatusWorking + e.agent.turnChangeSeq++ + e.updateAgentAnnouncement() + e.notify() + return true +} + +// DenyPermission denies the open permission card, records the denial for this request so the agent +// will never retry it automatically, marks the step with "Allow now", and lets the agent continue. +func (e *Editor) DenyPermission() bool { + if e == nil || e.agent.livePendingAsk == nil || e.agent.livePendingAsk.resolved { + return false + } + ask := cloneAgentPermissionPrompt(e.agent.livePendingAsk.ask) + e.resolvePendingLiveAskLocked(PermissionOutcomeDeny) + if e.agent.liveDeniedKeys == nil { + e.agent.liveDeniedKeys = make(map[string]bool) + } + if ask.PermissionKey != "" { + e.agent.liveDeniedKeys[ask.PermissionKey] = true + } + deniedLabel, unchecked := deniedStepSummary(ask) + if turn := e.latestAgentTurnPtr(); turn != nil { + if unchecked != "" && !slices.Contains(turn.NotChecked, unchecked) { + turn.NotChecked = append(turn.NotChecked, unchecked) + } + for i := range turn.Steps { + if turn.Steps[i].ID == ask.StepID { + turn.Steps[i].Status = AgentStepDenied + turn.Steps[i].Title = deniedLabel + turn.Steps[i].Detail = "continued without it" + turn.Steps[i].CanAllowNow = true + turn.Steps[i].PermissionKey = ask.PermissionKey + turn.Steps[i].UncheckedNote = unchecked + break + } + } + } + e.agent.status = AgentStatusWorking + e.agent.liveActivity = "Agent is continuing without it · manual edits stay available" + e.agent.turnChangeSeq++ + e.updateAgentAnnouncement() + e.notify() + return true +} + +// AttachDeniedStepAllowNow binds the on-demand "Allow now" callback for a denied step. +func (e *Editor) AttachDeniedStepAllowNow(stepID string, fn func()) { + if e == nil || stepID == "" { + return + } + for ti := len(e.agent.turns) - 1; ti >= 0; ti-- { + turn := &e.agent.turns[ti] + for si := range turn.Steps { + if turn.Steps[si].ID == stepID { + turn.Steps[si].allowNowFunc = fn + turn.Steps[si].CanAllowNow = true + return + } + } + } +} + +// AllowDeniedStepNow lets the person explicitly approve and run a previously denied step from its step row. +func (e *Editor) AllowDeniedStepNow(stepID string) bool { + if e == nil || stepID == "" { + return false + } + for ti := len(e.agent.turns) - 1; ti >= 0; ti-- { + turn := &e.agent.turns[ti] + for si := range turn.Steps { + if turn.Steps[si].ID != stepID || turn.Steps[si].Status != AgentStepDenied { + continue + } + if key := turn.Steps[si].PermissionKey; key != "" { + delete(e.agent.liveDeniedKeys, key) + } + if note := turn.Steps[si].UncheckedNote; note != "" { + turn.NotChecked = slices.DeleteFunc(turn.NotChecked, func(s string) bool { return s == note }) + if turn.PendingReview != nil { + turn.PendingReview.NotChecked = slices.DeleteFunc(turn.PendingReview.NotChecked, func(s string) bool { return s == note }) + } + } + fn := turn.Steps[si].allowNowFunc + turn.Steps[si].Status = AgentStepRunning + turn.Steps[si].Detail = "allowed once, just now" + turn.Steps[si].CanAllowNow = false + e.agent.liveActivity = "Agent is running allowed step · manual edits stay available" + e.agent.turnChangeSeq++ + e.notify() + if fn != nil { + fn() + } + return true + } + } + return false +} + +// AddToAgentRequest appends additional instructions to the running or waiting request +// and queues them for the MCP client. +func (e *Editor) AddToAgentRequest(text string) error { + if e == nil { + return errors.New("editor: nil editor") + } + text = strings.TrimSpace(text) + if text == "" { + return nil + } + if strings.IndexByte(text, 0) >= 0 { + return errors.New("editor: follow-up instruction must not contain NUL bytes") + } + if len(text) > maxAgentFollowUpBytes { + return fmt.Errorf("editor: follow-up instruction exceeds maximum size (%d bytes)", maxAgentFollowUpBytes) + } + if !e.AgentWorking() { + return errors.New("editor: no active agent request") + } + if turn := e.latestAgentTurnPtr(); turn != nil { + if len(turn.FollowUps) < maxLiveAgentFollowUps { + turn.FollowUps = append(turn.FollowUps, AgentFollowUp{ + Text: text, + SentAt: e.nowTime(), + }) + } + } + if len(e.agent.liveQueuedFollowUps) < maxLiveAgentFollowUps { + e.agent.liveQueuedFollowUps = append(e.agent.liveQueuedFollowUps, text) + } + e.agent.turnChangeSeq++ + e.notify() + if e.OnAddToAgentRequest != nil { + e.OnAddToAgentRequest(text) + } + return nil +} + +// DrainAgentFollowUps returns and clears any instructions added via "Add to this request" since the last drain. +func (e *Editor) DrainAgentFollowUps() []string { + if e == nil || len(e.agent.liveQueuedFollowUps) == 0 { + return nil + } + out := slices.Clone(e.agent.liveQueuedFollowUps) + e.agent.liveQueuedFollowUps = nil + return out +} + +// CompleteAgentRequest finishes the active live request and prepares the summary/review card, +// explicitly noting anything that was skipped because the user denied it. +func (e *Editor) CompleteAgentRequest(summary string) { + if e == nil { + return + } + if e.AgentStopped() { + return + } + e.resolvePendingLiveAskLocked(PermissionOutcomeStopped) + e.agent.liveRequestActive = false + e.agent.liveActivity = "" + if turn := e.latestAgentTurnPtr(); turn != nil && !turn.Stopped { + dropTurnPlaceholder(turn) + for i := range turn.Steps { + if turn.Steps[i].Status == AgentStepRunning { + turn.Steps[i].Status = AgentStepDone + } + } + turn.Done = true + turn.Status = "done" + turn.FinishedAt = e.nowTime() + if summary != "" { + turn.Summary = summary + turn.Reply = summary + } + e.observeTurnSceneMutations(turn, max(1, len(turn.Steps))) + e.refreshTurnReview(turn) + if turn.Summary != "" && turn.Mismatch == nil { + turn.Mismatch = CheckAgentSummaryAgainstDiff(turn.Summary, turn.Review, turn.mutations) + } + turn.PendingReview = e.buildTurnPendingReviewLocked(turn, summary, false) + } + e.agent.turnChangeSeq++ + e.restoreIdleAgentStatus() + e.notify() +} + +// StopAgent stops the running or waiting agent request (triggered by the Stop button or Mod+. from anywhere, +// including inside modal dialogs). Completed steps and edits stay pending for review, and the +// "Agent stopped" toast offers Review. Esc never calls StopAgent. +func (e *Editor) StopAgent() bool { + if e == nil { + return false + } + wasActive := e.AgentWorking() + if !wasActive { + if e.OnStopAgent != nil { + e.OnStopAgent() + } + return false + } + + stoppedBefore := "" + if e.agent.livePendingAsk != nil && !e.agent.livePendingAsk.resolved { + if e.agent.livePendingAsk.ask.ShortAction != "" { + stoppedBefore = e.agent.livePendingAsk.ask.ShortAction + } else { + stoppedBefore = e.agent.livePendingAsk.ask.Title + } + } + + stoppedTurnID := e.agent.activeTurnID + e.agent.activeTurnID = "" + waitingTaskID := e.clearWaitingTurnTaskID() + if e.agent.activeRetryCancel != nil { + e.agent.activeRetryCancel() + e.agent.activeRetryCancel = nil + } + e.agent.activeRetryNow = nil + hadActiveRun := e.agent.activeRunCancel != nil + if e.agent.activeRunCancel != nil { + e.agent.activeRunID++ + cancel := e.agent.activeRunCancel + e.agent.activeRunCancel = nil + cancel() + } + e.resolvePendingLiveAskLocked(PermissionOutcomeStopped) + e.agent.openRequest = nil + e.closeLiveStopChLocked() + e.agent.liveRequestActive = false + e.agent.liveStopped = true + e.agent.liveActivity = "" + + if turn := e.latestAgentTurnPtr(); turn != nil && !turn.Done { + dropTurnPlaceholder(turn) + if hadActiveRun { + for i := range turn.Steps { + if turn.Steps[i].Status == AgentStepRunning || turn.Steps[i].Status == AgentStepWaiting { + if stoppedBefore == "" { + stoppedBefore = turn.Steps[i].Title + } + if turn.Steps[i].Status == AgentStepWaiting { + turn.Steps[i].Status = AgentStepPending + } + break + } + } + turn.Stopped = true + turn.StoppedBefore = stoppedBefore + turn.Done = true + turn.Status = "stopped" + turn.FinishedAt = e.nowTime() + if turn.ModelError != nil { + turn.ModelError.Retrying = false + } + e.populateStoppedTurnState(turn) + doneCount := completedTurnStepCount(turn) + stepLabel := "You stopped the agent" + if stoppedBefore != "" { + stepLabel = "You stopped before " + stoppedBefore + } + keptDetail := fmt.Sprintf("%d steps kept for review", doneCount) + if doneCount == 1 { + keptDetail = "1 step kept for review" + } + turn.PendingReview = e.buildTurnPendingReviewLocked(turn, fmt.Sprintf("%s · %s.", stepLabel, keptDetail), true) + } else { + for i := range turn.Steps { + if turn.Steps[i].Status == AgentStepRunning || turn.Steps[i].Status == AgentStepWaiting { + if stoppedBefore == "" { + stoppedBefore = turn.Steps[i].Title + } + turn.Steps = append(turn.Steps[:i], turn.Steps[i+1:]...) + break + } + } + doneCount := completedTurnStepCount(turn) + stepLabel := "You stopped the agent" + if stoppedBefore != "" { + stepLabel = "You stopped before " + stoppedBefore + } + keptDetail := fmt.Sprintf("%d steps kept for review", doneCount) + if doneCount == 1 { + keptDetail = "1 step kept for review" + } + e.agent.liveStepSeq++ + turn.Steps = append(turn.Steps, AgentStep{ + ID: fmt.Sprintf("step-%d", e.agent.liveStepSeq), + Title: stepLabel, + Detail: keptDetail, + Status: AgentStepStopped, + StartedAt: e.nowTime(), + }) + turn.Stopped = true + turn.StoppedBefore = stoppedBefore + turn.Done = true + turn.Status = "stopped" + turn.FinishedAt = e.nowTime() + if turn.ModelError != nil { + turn.ModelError.Retrying = false + } + e.observeTurnSceneMutations(turn, max(1, len(turn.Steps))) + e.refreshTurnReview(turn) + turn.PendingReview = e.buildTurnPendingReviewLocked(turn, fmt.Sprintf("%s · %s.", stepLabel, keptDetail), true) + } + } + + e.ShowToast(Toast{ + ID: "agent-stopped", + Kind: ToastInfo, + Message: e.T("agent.stoppedToast"), + ActionLabel: e.T("agent.review"), + OnAction: func() { + e.FocusAgentTurnReview() + }, + }) + e.agent.turnChangeSeq++ + e.restoreIdleAgentStatus() + if stoppedTurnID != "" { + e.removeTurnNotificationTask(stoppedTurnID) + } + if waitingTaskID != "" && waitingTaskID != stoppedTurnID { + e.removeTurnNotificationTask(waitingTaskID) + } + if stoppedTurnID == "" && waitingTaskID == "" { + e.notify() + } + if e.OnStopAgent != nil { + e.OnStopAgent() + } + return true +} + +// FocusAgentTurnReview opens the Agent panel and focuses the pending review card. +func (e *Editor) FocusAgentTurnReview() { + if e == nil { + return + } + if e.agent.mode != AgentModeNone { + e.agent.rightTab = RightTabAgent + } + e.agent.liveFocusReviewSeq++ + e.notify() +} + +// KeepPendingAgentTurnReview keeps the latest turn's pending agent changes, resumes autosave, and shows a confirmation toast with Undo. +func (e *Editor) KeepPendingAgentTurnReview() { + if e == nil || e.AgentActorActive() { + return + } + turn := e.latestAgentTurnPtr() + if turn == nil || turn.PendingReview == nil || turn.PendingReview.Kept || turn.PendingReview.Reverted { + return + } + turn.PendingReview.Kept = true + if turn.Review != nil { + turn.Review.Kept = true + turn.Review.Discarded = false + } + steps := turn.PendingReview.StepsDone + msg := fmt.Sprintf("Kept %d steps", steps) + if steps == 1 { + msg = "Kept 1 step" + } + e.ShowToast(Toast{ + ID: "agent-review-kept", + Kind: ToastSuccess, + Message: msg, + ActionLabel: e.T("permissions.toastUndo"), + OnAction: func() { + e.RevertPendingAgentTurnReview() + e.DismissToast() + }, + }) + e.agent.turnChangeSeq++ + e.scheduleAutoSaveIfNeeded() + e.notify() + e.triggerReviewKeptAutomations(e.ScenePath, "") +} + +// RevertPendingAgentTurnReview undoes scene edits made during the latest agent turn back to its starting history index. +func (e *Editor) RevertPendingAgentTurnReview() { + turn := e.latestAgentTurnPtr() + if turn == nil || turn.PendingReview == nil || turn.PendingReview.Reverted { + return + } + if e.History != nil { + target := turn.turnStartHistoryIdx + for e.History.Index() > target && e.Undo() { + } + } + turn.PendingReview.Kept = false + turn.PendingReview.Reverted = true + if turn.Review != nil { + turn.Review.Kept = false + turn.Review.Discarded = true + } + e.agent.turnChangeSeq++ + e.scheduleAutoSaveIfNeeded() + e.notify() +} + +// HasPendingAgentTurnReview reports whether the latest agent turn left unkept, unreverted scene edits pending review. +func (e *Editor) HasPendingAgentTurnReview() bool { + turn := e.latestAgentTurnPtr() + if turn == nil || turn.PendingReview == nil { + return false + } + if turn.Review != nil && (turn.Review.Kept || turn.Review.Discarded) { + return false + } + return !turn.PendingReview.Kept && !turn.PendingReview.Reverted && turn.PendingReview.ChangesCount > 0 +} + +// IsPermissionDenied reports whether permissionKey was already denied in the current active request. +func (e *Editor) IsPermissionDenied(permissionKey string) bool { + if e == nil || permissionKey == "" { + return false + } + return e.agent.liveDeniedKeys[permissionKey] +} + +// DeniedPermissionKeys returns a sorted copy of permission keys denied in the current request. +func (e *Editor) DeniedPermissionKeys() []string { + if e == nil || len(e.agent.liveDeniedKeys) == 0 { + return nil + } + return slices.Sorted(maps.Keys(e.agent.liveDeniedKeys)) +} + +func (e *Editor) setLivePermissionCardFocused(focused bool) { + if e == nil { + return + } + e.agent.livePermCardFocused = focused +} + +// PendingAgentPermissionCardFocused reports whether keyboard focus is currently inside the Agent panel's live permission card. +func (e *Editor) PendingAgentPermissionCardFocused() bool { + if e == nil || e.agent.livePendingAsk == nil || e.agent.livePendingAsk.resolved { + return false + } + return e.agent.livePermCardFocused +} + +func (e *Editor) updateLiveAskStepRunningLocked(ask AgentPermissionPrompt, detail string) { + if turn := e.latestAgentTurnPtr(); turn != nil { + for i := range turn.Steps { + if turn.Steps[i].ID == ask.StepID { + turn.Steps[i].Status = AgentStepRunning + turn.Steps[i].Detail = detail + break + } + } + } + if ask.Evaluation.Action == PermissionActionRun && (ask.Evaluation.Target == PermissionRunPlaytests || ask.Tool == "game_playtest") { + scene := "the scene" + if e.Doc != nil && e.Doc.Name != "" { + scene = e.Doc.Name + } + e.agent.liveActivity = fmt.Sprintf("Agent is playing %s headless · manual edits stay available", scene) + } else { + e.agent.liveActivity = "Agent is working · manual edits stay available" + } +} + +func (e *Editor) buildTurnPendingReviewLocked(turn *AgentTurn, summary string, stopped bool) *AgentPendingReview { + doneCount := completedTurnStepCount(turn) + changes := 0 + if e.History != nil { + if diff := e.History.Index() - turn.turnStartHistoryIdx; diff > 0 { + changes = diff + } + } + unchecked := slices.Clone(turn.NotChecked) + if summary == "" && len(unchecked) > 0 { + summary = fmt.Sprintf("Done, but not checked: %s.", strings.Join(unchecked, ", ")) + } + return &AgentPendingReview{ + StepsDone: doneCount, + ChangesCount: changes, + Summary: summary, + NotChecked: unchecked, + Stopped: stopped, + StoppedBefore: turn.StoppedBefore, + } +} + +func deniedStepSummary(ask AgentPermissionPrompt) (label, unchecked string) { + if ask.Evaluation.Action == PermissionActionRun && (ask.Evaluation.Target == PermissionRunPlaytests || ask.Tool == "game_playtest") { + return "You denied the playtest", "Not playtested" + } + if ask.Evaluation.Action == PermissionActionRun && (ask.Evaluation.Target == PermissionRunGameCheck || ask.Tool == "game_check") { + return "You denied game check", "Not checked" + } + if ask.ShortAction != "" { + return "You denied " + ask.ShortAction, "Skipped " + ask.ShortAction + } + return "You denied " + ask.Tool, "Skipped " + ask.Tool +} + +func sanitizeStepObjects(objects []string) []string { + if len(objects) == 0 { + return nil + } + limit := min(len(objects), maxAgentStepObjects) + out := make([]string, 0, limit) + seen := make(map[string]bool, limit) + for _, raw := range objects { + id := strings.TrimSpace(raw) + if id == "" || strings.IndexByte(id, 0) >= 0 || seen[id] { + continue + } + seen[id] = true + out = append(out, id) + if len(out) >= limit { + break + } + } + return out +} diff --git a/packages/game/editor/agent_live_steps_test.go b/packages/game/editor/agent_live_steps_test.go new file mode 100644 index 000000000..86eeaaecb --- /dev/null +++ b/packages/game/editor/agent_live_steps_test.go @@ -0,0 +1,355 @@ +package editor_test + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func TestAgentPanelPlaceholderLiveStepsAndInputFocusStability(t *testing.T) { + ed, err := editor.New(newFocusTestScene(), nil) + if err != nil { + t.Fatalf("editor.New: %v", err) + } + t.Cleanup(func() { _ = ed.Close() }) + ed.SetRightRailTab(editor.RightTabAgent) + + now := time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC) + ed.Now = func() time.Time { return now } + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, focusDesktopEnv, nsgotest.Size(1440, 900)) + app.Settle() + + // Starting a request immediately shows the gray placeholder step (guaranteed within 300 ms). + ed.StartAgentRequest("Put three slimes patrolling the lower floor.") + app.Settle() + if !app.Exists("id:agent-step-placeholder") { + t.Fatal("expected gray placeholder step immediately after starting request") + } + if !app.Exists("id:agent-composer-stop") || !app.Exists("id:agent-add-input") { + t.Fatal("expected Add to this request input and Stop button while working") + } + + // Focus "Add to this request" and verify streaming steps do NOT remount or steal focus from it. + app.Focus("id:agent-add-input") + app.Settle() + + s1 := ed.BeginAgentToolStep("scene_read", "Read level_01.scene.yaml", "Agent is reading level_01 · manual edits stay available", nil) + ed.FinishAgentToolStep(s1, "Read level_01.scene.yaml", "", nil, false) + s2 := ed.BeginAgentToolStep("scene_edit", "Placing 3 coins toward the door", "Agent is editing level_01 · manual edits stay available", []string{"coin_01", "coin_02", "coin_03"}) + app.Settle() + + if fv := focusedView(app); fv == nil || fv.Props.TestID != "agent-add-input" { + t.Fatalf("streaming steps stole focus from agent-add-input: got %v", fv) + } + if app.Exists("id:agent-step-placeholder") { + t.Fatal("placeholder step should disappear once real steps arrive") + } + snap := ed.AgentSession() + if len(snap.Steps) != 2 { + t.Fatalf("len(steps) = %d, want 2", len(snap.Steps)) + } + if snap.Steps[0].Status != editor.AgentStepDone || snap.Steps[1].Status != editor.AgentStepRunning { + t.Fatalf("step statuses = [%s, %s], want [done, running]", snap.Steps[0].Status, snap.Steps[1].Status) + } + ed.FinishAgentToolStep(s2, "Placed 3 coins toward the door", "", []string{"coin_01", "coin_02", "coin_03"}, false) + app.Settle() + + // Manual edits stay available while the agent works and status bar shows live activity. + if err := ed.MoveObject("hero", 200, 190); err != nil { + t.Fatalf("manual MoveObject failed while agent working: %v", err) + } + if !app.Exists("id:status-agent-activity") { + t.Fatal("expected status bar to report live agent activity while working") + } +} + +func TestPermissionCardFocusDisciplineAndShortcuts(t *testing.T) { + dir := t.TempDir() + ed, err := editor.New(newFocusTestScene(), nil) + if err != nil { + t.Fatalf("editor.New: %v", err) + } + t.Cleanup(func() { _ = ed.Close() }) + permPath := filepath.Join(dir, editor.PermissionsFileName) + if err := ed.LoadProjectPermissions(permPath); err != nil { + t.Fatalf("LoadProjectPermissions: %v", err) + } + if err := ed.SelectPermissionProfile(editor.PermissionProfileCautious); err != nil { + t.Fatalf("SelectPermissionProfile: %v", err) + } + ed.SetRightRailTab(editor.RightTabAgent) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, focusDesktopEnv, nsgotest.Size(1440, 900)) + app.Settle() + + // 1. Focus is outside Agent panel (in toolbar): permission card must NOT steal focus (Spec rule 05). + app.Focus("id:toolbar-play") + app.Settle() + + ed.StartAgentRequest("Check the slimes with a playtest.") + stepID := ed.BeginAgentToolStep("game_playtest", "Play 10 s headless", "Agent is playing level_01 headless · manual edits stay available", nil) + evalPlaytest := ed.EvaluatePermission(editor.PermissionRequest{ + Tool: "game_playtest", + Action: editor.PermissionActionRun, + Target: editor.PermissionRunPlaytests, + }) + askCh, _, denied := ed.BeginAgentPermissionAsk(editor.AgentPermissionPrompt{ + StepID: stepID, + Title: "Allow the agent to run the game?", + ShortAction: "the playtest", + Why: "It wants to play level_01 headless for 10 seconds.", + Effect: "Nothing is saved.", + RuleSource: evalPlaytest.Reason, + RulePreview: editor.AlwaysRuleForEvaluation(evalPlaytest).Summary(), + AlwaysLabel: "Always allow headless playtests", + Tool: "game_playtest", + PermissionKey: "run:playtests", + Evaluation: evalPlaytest, + }) + if denied { + t.Fatal("unexpected alreadyDenied on fresh request") + } + app.Settle() + + card := app.Find("id:agent-permission-card") + if card == nil { + t.Fatal("permission card not mounted") + } + if card.Props.Role != core.RoleAlertDialog { + t.Fatalf("permission card role = %v, want RoleAlertDialog", card.Props.Role) + } + if card.Props.LiveRegion != core.LiveRegionPolite { + t.Fatalf("permission card liveRegion = %v, want LiveRegionPolite", card.Props.LiveRegion) + } + if fv := focusedView(app); fv == nil || fv.Props.TestID != "toolbar-play" { + t.Fatalf("permission card stole focus from toolbar-play: got %v", fv) + } + + // Clicking header "Waiting for you" chip focuses the permission card. + app.Press("id:agent-status-chip") + app.Settle() + if fv := focusedView(app); fv == nil || fv.Props.TestID != "agent-perm-allow-once" { + t.Fatalf("clicking Waiting chip focused %v, want agent-perm-allow-once", fv) + } + + // Down / Up arrows cycle between permission card buttons. + app.Key("down") + app.Settle() + if fv := focusedView(app); fv == nil || fv.Props.TestID != "agent-perm-allow-always" { + t.Fatalf("down arrow focused %v, want agent-perm-allow-always", fv) + } + app.Key("up") + app.Settle() + if fv := focusedView(app); fv == nil || fv.Props.TestID != "agent-perm-allow-once" { + t.Fatalf("up arrow focused %v, want agent-perm-allow-once", fv) + } + + // Esc leaves the permission card unanswered and the agent keeps waiting (never denies or stops). + app.Key("escape") + app.Settle() + if snap := ed.AgentSession(); snap.Status != editor.AgentStatusWaitingForYou || snap.PendingAsk == nil { + t.Fatalf("Esc unexpectedly resolved permission card: status=%s pending=%v", snap.Status, snap.PendingAsk) + } + + // Refocus card and use Mod+Enter to Allow once. + app.Focus("id:agent-perm-allow-once") + app.Settle() + app.Key("mod+enter") + app.Settle() + select { + case out := <-askCh: + if out != editor.PermissionOutcomeAllowOnce { + t.Fatalf("outcome = %q, want allow_once", out) + } + default: + t.Fatal("Mod+Enter did not resolve permission ask") + } + + // 2. When focus is ALREADY inside Agent panel (on a non-input control, not typing), + // a new permission card takes focus and Mod+Backspace denies. + app.Focus("id:agent-composer-stop") + app.Settle() + step2 := ed.BeginAgentToolStep("game_check", "Run game check", "", nil) + evalCheck := ed.EvaluatePermission(editor.PermissionRequest{ + Tool: "game_check", + Action: editor.PermissionActionRun, + Target: editor.PermissionRunGameCheck, + }) + askCh2, _, _ := ed.BeginAgentPermissionAsk(editor.AgentPermissionPrompt{ + StepID: step2, + Title: "Allow the agent to run game check?", + ShortAction: "game check", + Why: "It wants to check for broken references.", + Effect: "Nothing is saved.", + RuleSource: evalCheck.Reason, + RulePreview: editor.AlwaysRuleForEvaluation(evalCheck).Summary(), + AlwaysLabel: "Always allow game check", + Tool: "game_check", + PermissionKey: "run:game check", + Evaluation: evalCheck, + }) + app.Settle() + if fv := focusedView(app); fv == nil || fv.Props.TestID != "agent-perm-allow-once" { + t.Fatalf("when focus already in Agent panel, expected card to take focus, got %v", fv) + } + app.Key("mod+backspace") + app.Settle() + select { + case out := <-askCh2: + if out != editor.PermissionOutcomeDeny { + t.Fatalf("outcome = %q, want deny", out) + } + default: + t.Fatal("Mod+Backspace did not deny focused permission card") + } + + // 3. Alt+Enter on a focused card chooses Always, persists permissions.yaml, and shows PermissionToast with Undo. + app.Focus("id:agent-composer-stop") + app.Settle() + step3 := ed.BeginAgentToolStep("game_playtest", "Play 10 s headless", "", nil) + askCh3, _, _ := ed.BeginAgentPermissionAsk(editor.AgentPermissionPrompt{ + StepID: step3, + Title: "Allow the agent to run the game?", + ShortAction: "the playtest", + Why: "It wants to play level_01 headless.", + Effect: "Nothing is saved.", + RuleSource: evalPlaytest.Reason, + RulePreview: editor.AlwaysRuleForEvaluation(evalPlaytest).Summary(), + AlwaysLabel: "Always allow headless playtests", + Tool: "game_playtest", + PermissionKey: "run:playtests", + Evaluation: evalPlaytest, + }) + app.Settle() + app.Key("alt+enter") + app.Settle() + select { + case out := <-askCh3: + if out != editor.PermissionOutcomeAllowAlways { + t.Fatalf("outcome = %q, want allow_always", out) + } + default: + t.Fatal("Alt+Enter did not approve Always on focused permission card") + } + if _, err := os.Stat(permPath); err != nil { + t.Fatalf("Always did not write permissions.yaml: %v", err) + } + toast, ok := ed.PermissionToast() + if !ok || !strings.Contains(toast.Message, "Always") { + t.Fatalf("expected Always permission toast, got %+v (ok=%v)", toast, ok) + } +} + +func TestStopFromInsideModalDialogAndEscNeverStops(t *testing.T) { + ed, err := editor.New(newFocusTestScene(), nil) + if err != nil { + t.Fatalf("editor.New: %v", err) + } + t.Cleanup(func() { _ = ed.Close() }) + ed.SetRightRailTab(editor.RightTabAgent) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, focusDesktopEnv, nsgotest.Size(1440, 900)) + app.Settle() + + ed.StartAgentRequest("Add slimes and playtest.") + s1 := ed.BeginAgentToolStep("scene_read", "Read level_01.scene.yaml", "", nil) + ed.FinishAgentToolStep(s1, "Read level_01.scene.yaml", "", nil, false) + if err := ed.MoveObject("hero", 300, 180); err != nil { + t.Fatalf("MoveObject: %v", err) + } + s2 := ed.BeginAgentToolStep("scene_edit", "Moved Hero", "", []string{"hero"}) + ed.FinishAgentToolStep(s2, "Moved Hero", "", []string{"hero"}, false) + s3 := ed.BeginAgentToolStep("game_playtest", "the playtest", "", nil) + _, stopCh, _ := ed.BeginAgentPermissionAsk(editor.AgentPermissionPrompt{ + StepID: s3, + Title: "Allow the agent to run the game?", + ShortAction: "the playtest", + Tool: "game_playtest", + Evaluation: editor.PermissionEvaluation{ + Action: editor.PermissionActionRun, + Target: editor.PermissionRunPlaytests, + }, + }) + app.Settle() + + // Esc outside a dialog MUST NOT stop the agent. + app.Key("escape") + app.Settle() + if !ed.AgentWorking() { + t.Fatal("Esc stopped the agent; Spec rule 02 says Esc never stops the agent") + } + + // Open a modal dialog (Shortcuts sheet via Cmd+/) and verify Esc closes dialog without stopping agent. + app.Key("meta+/") + app.Settle() + if !ed.ShortcutsSheetOpen() { + t.Fatal("expected Shortcuts Sheet modal to open") + } + app.Key("escape") + app.Advance(250 * time.Millisecond) + app.Settle() + if ed.ShortcutsSheetOpen() { + t.Fatal("expected Esc to close Shortcuts Sheet") + } + if !ed.AgentWorking() { + t.Fatal("Esc from modal stopped the agent; Esc must never stop the agent") + } + + // Open modal dialog again and press Mod+. from INSIDE the dialog -> MUST stop the agent! + app.Key("meta+/") + app.Settle() + if !ed.ShortcutsSheetOpen() { + t.Fatal("expected Shortcuts Sheet modal to reopen") + } + app.Key("mod+.") + app.Settle() + + select { + case <-stopCh: + default: + t.Fatal("Mod+. from inside modal dialog did not close request stop channel") + } + snap := ed.AgentSession() + if !snap.Stopped { + t.Fatalf("expected Stopped=true after Mod+., got %+v", snap) + } + if snap.Review == nil || !snap.Review.Stopped || snap.Review.StepsDone != 2 { + t.Fatalf("pending review after Stop = %+v, want Stopped=true StepsDone=2", snap.Review) + } + if !ed.HasPendingAgentTurnReview() || !ed.HasOpenReview() { + t.Fatalf("expected HasPendingAgentTurnReview && HasOpenReview to pause autosave until kept/reverted") + } + toast, ok := ed.ActiveToast() + if !ok || toast.Message != "Agent stopped" || toast.ActionLabel != "Review" { + t.Fatalf("toast after Stop = %+v (ok=%v), want Agent stopped with Review", toast, ok) + } + // Completed edits stay in the scene pending for review. + hero, _, _ := ed.FindObject("hero") + if hero == nil || hero.X != 300 { + t.Fatalf("completed edit lost after Stop: hero=%+v", hero) + } + + // Keeping review clears HasOpenReview; Reverting restores the scene. + ed.KeepPendingAgentTurnReview() + if ed.HasPendingAgentTurnReview() { + t.Fatal("HasPendingAgentTurnReview should be false after KeepPendingAgentTurnReview") + } + ed.RevertPendingAgentTurnReview() + hero, _, _ = ed.FindObject("hero") + if hero == nil || hero.X == 300 { + t.Fatalf("RevertPendingAgentTurnReview did not undo agent edit: hero=%+v", hero) + } +} diff --git a/packages/game/editor/agent_live_steps_ui.go b/packages/game/editor/agent_live_steps_ui.go new file mode 100644 index 000000000..8cb65f315 --- /dev/null +++ b/packages/game/editor/agent_live_steps_ui.go @@ -0,0 +1,984 @@ +package editor + +import ( + "fmt" + "math" + "strings" + + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/icons/lucide" + "github.com/nsgo-dev/nsgo/ui" +) + +func moveAgentCardFocus(refs []*core.Ref, delta int) { + idx := -1 + for i, r := range refs { + if r != nil && r.HoldsFocus() { + idx = i + break + } + } + next := 0 + if idx >= 0 { + next = (idx + delta + len(refs)) % len(refs) + } + if refMounted(refs[next]) { + refs[next].Focus() + } +} + +func agentRunningSpinnerIcon(col core.Color) core.Node { + return core.Canvas{ + Style: core.Style{Width: core.Pt(16), Height: core.Pt(16), FlexShrink: 0}, + Draw: func(d *core.Drawing, _ core.Size) { + d.SetStrokeColor(col).SetLineWidth(2).SetLineCap(core.CapRound) + d.BeginPath().Arc(8, 8, 6.2, -float32(math.Pi/2), float32(math.Pi), false).Stroke() + }, + } +} + +func agentLiveStepRow(ed *Editor, turnIdx, stepIdx int, step AgentStep, p SpecPalette) core.Node { + testID := fmt.Sprintf("agent-step-%d-%d", turnIdx, stepIdx) + if step.Status == AgentStepPlaceholder { + testID = "agent-step-placeholder" + } + + var badge core.Node + textCol := p.TextMuted + switch step.Status { + case AgentStepPlaceholder: + textCol = p.TextFaint + badge = core.View{ + Style: core.Style{ + Width: core.Pt(16), + Height: core.Pt(16), + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(10), + Height: core.Pt(10), + CornerRadius: 5, + Background: p.LineRaised, + }, + }, + }, + } + case AgentStepDone: + badge = core.View{ + Style: core.Style{ + Width: core.Pt(16), + Height: core.Pt(16), + CornerRadius: 8, + Background: p.Added.Fill, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.Check(), + Style: core.Style{ + Width: core.Pt(10), + Height: core.Pt(10), + Color: p.Added.Fg, + }, + }, + }, + } + case AgentStepRunning: + textCol = p.TextPrimary + badge = agentRunningSpinnerIcon(p.Agent.Fg) + case AgentStepWaiting: + textCol = p.TextPrimary + badge = core.View{ + Style: core.Style{ + Width: core.Pt(16), + Height: core.Pt(16), + CornerRadius: 8, + Background: p.Warning.Fill, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.Pause(), + Style: core.Style{ + Width: core.Pt(10), + Height: core.Pt(10), + Color: p.Warning.Fg, + }, + }, + }, + } + case AgentStepWarning: + textCol = p.TextSecondary + badge = core.View{ + Style: core.Style{ + Width: core.Pt(16), + Height: core.Pt(16), + CornerRadius: 8, + Background: p.Warning.Fill, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + }, + Children: []core.Node{ + core.Text{ + Content: "!", + Style: core.Style{ + FontSize: 10, + FontWeight: 700, + Color: p.Warning.Fg, + }, + }, + }, + } + case AgentStepInterrupted: + textCol = p.TextMuted + badge = core.View{ + Style: core.Style{ + Width: core.Pt(16), + Height: core.Pt(16), + CornerRadius: 8, + BorderWidth: 1.5, + BorderColor: p.TextFaint, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.Pause(), + Style: core.Style{ + Width: core.Pt(9), + Height: core.Pt(9), + Color: p.TextFaint, + }, + }, + }, + } + case AgentStepDenied: + textCol = p.TextPrimary + badge = core.View{ + Style: core.Style{ + Width: core.Pt(16), + Height: core.Pt(16), + CornerRadius: 8, + Background: p.LineRaised, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.X(), + Style: core.Style{ + Width: core.Pt(10), + Height: core.Pt(10), + Color: p.TextMuted, + }, + }, + }, + } + case AgentStepBlocked: + textCol = p.TextPrimary + badge = core.View{ + Style: core.Style{ + Width: core.Pt(16), + Height: core.Pt(16), + CornerRadius: 8, + Background: p.LineRaised, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.Lock(), + Style: core.Style{ + Width: core.Pt(10), + Height: core.Pt(10), + Color: p.TextSecondary, + }, + }, + }, + } + case AgentStepStopped: + textCol = p.TextPrimary + badge = core.View{ + Style: core.Style{ + Width: core.Pt(16), + Height: core.Pt(16), + CornerRadius: 8, + Background: p.LineRaised, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(6), + Height: core.Pt(6), + CornerRadius: 1.5, + Background: p.TextPrimary, + }, + }, + }, + } + case AgentStepFailed: + textCol = p.TextSecondary + badge = core.View{ + Style: core.Style{ + Width: core.Pt(16), + Height: core.Pt(16), + CornerRadius: 8, + Background: p.Removed.Fill, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + }, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.X(), + Style: core.Style{ + Width: core.Pt(10), + Height: core.Pt(10), + Color: p.Removed.Fg, + }, + }, + }, + } + default: + textCol = p.TextFaint + badge = core.View{ + Style: core.Style{ + Width: core.Pt(16), + Height: core.Pt(16), + CornerRadius: 8, + BorderWidth: 1.5, + BorderColor: p.LineRaised, + FlexShrink: 0, + }, + } + } + + label := step.Title + if label == "" { + label = step.ToolName + } + if step.Detail != "" { + label = label + " · " + step.Detail + } + + contentKids := []core.Node{ + core.Text{ + Content: label, + Style: core.Style{ + FontSize: 12.5, + LineHeight: 18, + Color: textCol, + }, + }, + } + if step.Status == AgentStepBlocked && step.RuleSummary != "" { + ruleIdx := step.RuleIndex + contentKids = append(contentKids, core.View{ + TestID: "agent-step-blocked-rule-" + step.ID, + Role: core.RoleLink, + Label: step.RuleSummary, + Focusable: func() bool { return true }, + Style: core.Style{ + Padding: core.Symmetric(6, 10), + CornerRadius: 8, + Background: p.Inset, + BorderWidth: 1, + BorderColor: p.Line, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.OpenPermissionsSettings(ruleIdx) + }, + Children: []core.Node{ + core.Text{ + Content: step.RuleSummary, + Style: core.Style{ + FontFamily: core.FontMonospace, + FontSize: 11.5, + Color: p.TextPrimary, + }, + }, + }, + }) + } + + rowKids := []core.Node{ + badge, + core.View{ + Style: core.Style{ + FlexGrow: 1, + FlexShrink: 1, + MinWidth: core.Pt(0), + Gap: 4, + }, + Children: contentKids, + }, + } + + if step.Status == AgentStepDenied && step.CanAllowNow { + stepID := step.ID + rowKids = append(rowKids, core.View{ + TestID: "agent-step-allow-now-" + stepID, + Role: core.RoleButton, + Label: ed.T("agent.allowNow"), + Focusable: func() bool { return true }, + Style: core.Style{ + Height: core.Pt(28), + FlexShrink: 0, + Padding: core.Symmetric(0, 8), + CornerRadius: 6, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.AllowDeniedStepNow(stepID) + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("agent.allowNow"), + Style: core.Style{ + FontSize: 12, + FontWeight: 500, + Color: p.Accent.Fg, + }, + }, + }, + }) + } + + if step.Status == AgentStepStopped { + rowKids = append(rowKids, core.View{ + TestID: "agent-step-review", + Role: core.RoleButton, + Label: ed.T("agent.review"), + Focusable: func() bool { return true }, + Style: core.Style{ + Height: core.Pt(28), + FlexShrink: 0, + Padding: core.Symmetric(0, 8), + CornerRadius: 6, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.FocusAgentTurnReview() + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("agent.review"), + Style: core.Style{ + FontSize: 12, + FontWeight: 500, + Color: p.Accent.Fg, + }, + }, + }, + }) + } + + return core.View{ + TestID: testID, + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + }, + Children: rowKids, + } +} + +func agentFollowUpBubble(p SpecPalette, testID, text string) core.Node { + return core.View{ + TestID: testID, + Style: core.Style{ + AlignSelf: core.AlignEnd, + MaxWidth: core.Pt(296), + Padding: core.Symmetric(8, 12), + CornerRadius: 12, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + }, + Children: []core.Node{ + core.Text{ + Content: text, + Style: core.Style{ + FontSize: 12.5, + LineHeight: 19, + Color: p.TextSecondary, + }, + }, + }, + } +} + +func agentPermissionCardView( + p SpecPalette, + ed *Editor, + ask AgentPermissionPrompt, + osKind core.OS, + cardRef, allowOnceRef, allowAlwaysRef, denyRef *core.Ref, +) core.Node { + bodyText := strings.TrimSpace(ask.Why) + if ask.Effect != "" { + if bodyText != "" { + bodyText += " " + ask.Effect + } else { + bodyText = ask.Effect + } + } + alwaysLabel := ask.AlwaysLabel + if alwaysLabel == "" { + alwaysLabel = ed.T("permissions.allowAlways") + } + + allowOnceHint := FormatShortcut("mod+enter", osKind) + allowAlwaysHint := FormatShortcut("alt+enter", osKind) + denyHint := FormatShortcut("mod+backspace", osKind) + + permButton := func(ref *core.Ref, testID, label, hint string, bg, border, fg, hintBg, hintFg core.Color, weight core.FontWeight, onPress func()) core.Node { + st := core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Height: core.Pt(32), + Padding: core.Edges{Left: 12, Right: 8}, + Gap: 8, + CornerRadius: 8, + Background: bg, + FocusVisible: p.FocusRing(2), + } + if border != core.Transparent { + st.BorderWidth = 1 + st.BorderColor = border + } + return core.View{ + Ref: ref, + TestID: testID, + Role: core.RoleButton, + Label: label, + Focusable: func() bool { return true }, + Style: st, + OnPress: func(core.PressEvent) { + onPress() + }, + Children: []core.Node{ + core.Text{ + Content: label, + Style: core.Style{ + FlexGrow: 1, + FontSize: 12.5, + FontWeight: weight, + Color: fg, + }, + }, + core.View{ + Style: core.Style{ + Height: core.Pt(20), + Padding: core.Symmetric(0, 6), + CornerRadius: 6, + Background: hintBg, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + }, + Children: []core.Node{ + core.Text{ + Content: hint, + Style: core.Style{ + FontFamily: core.FontMonospace, + FontSize: 11, + FontWeight: 500, + Color: hintFg, + }, + }, + }, + }, + }, + } + } + + ruleBoxKids := []core.Node{ + core.Text{ + Content: ed.T("agent.alwaysAddsRule"), + Style: core.Style{FontSize: 11.5, Color: p.TextFaint}, + }, + } + if ask.RulePreview != "" { + ruleBoxKids = append(ruleBoxKids, core.Text{ + TestID: "agent-perm-rule-preview", + Content: ask.RulePreview, + Style: core.Style{ + FontFamily: core.FontMonospace, + FontSize: 11.5, + Color: p.TextPrimary, + }, + }) + } + if ask.RuleSource != "" { + ruleBoxKids = append(ruleBoxKids, core.Text{ + TestID: "agent-perm-rule-source", + Content: ask.RuleSource, + Style: core.Style{FontSize: 11.5, LineHeight: 16, Color: p.TextFaint}, + }) + } + + return core.View{ + Ref: cardRef, + TestID: "agent-permission-card", + Role: core.RoleAlertDialog, + Label: ask.Title, + LiveRegion: core.LiveRegionPolite, + OnFocusIn: func() { + ed.setLivePermissionCardFocused(true) + }, + OnFocusOut: func() { + if cardRef == nil || !cardRef.HoldsFocus() { + ed.setLivePermissionCardFocused(false) + } + }, + Style: core.Style{ + CornerRadius: 12, + Background: p.Warning.Fill, + BorderWidth: 1, + BorderColor: p.Warning.Edge, + Padding: core.All(12), + Gap: 12, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: 8}, + Children: []core.Node{ + core.SVGView{ + SVG: lucide.Play(), + Style: core.Style{ + Width: core.Pt(14), + Height: core.Pt(14), + Color: p.Warning.Fg, + FlexShrink: 0, + }, + }, + core.Text{ + TestID: "agent-perm-title", + Content: ask.Title, + Style: core.Style{ + FontSize: 13.5, + FontWeight: 600, + Color: p.Warning.Fg, + FlexShrink: 1, + }, + }, + }, + }, + core.Text{ + TestID: "agent-perm-body", + Content: bodyText, + Style: core.Style{ + FontSize: 12.5, + LineHeight: 19, + Color: p.TextSecondary, + }, + }, + core.View{ + Style: core.Style{Gap: 8}, + Children: []core.Node{ + permButton( + allowOnceRef, "agent-perm-allow-once", ed.T("permissions.allowOnce"), allowOnceHint, + p.Accent.Fg, core.Transparent, p.Accent.OnFill, ui.Alpha(p.Accent.OnFill, 0.14), p.Accent.OnFill, 600, + func() { ed.AllowPermissionOnce() }, + ), + permButton( + allowAlwaysRef, "agent-perm-allow-always", alwaysLabel, allowAlwaysHint, + p.Raised, p.Warning.Edge, p.TextPrimary, p.LineRaised, p.TextSecondary, 500, + func() { ed.AllowPermissionAlways() }, + ), + permButton( + denyRef, "agent-perm-deny", ed.T("permissions.deny"), denyHint, + p.Warning.Fill, p.Warning.Edge, p.TextSecondary, p.Raised, p.TextSecondary, 400, + func() { ed.DenyPermission() }, + ), + }, + }, + core.View{ + TestID: "agent-perm-rule-info", + Style: core.Style{ + Padding: core.Symmetric(8, 12), + CornerRadius: 8, + Background: p.Inset, + Gap: 4, + }, + Children: ruleBoxKids, + }, + }, + } +} + +func agentTurnReviewCardView(p SpecPalette, ed *Editor, rev AgentPendingReview, osKind core.OS) core.Node { + headerText := fmt.Sprintf("%d steps pending review", rev.StepsDone) + if rev.StepsDone == 1 { + headerText = "1 step pending review" + } + if rev.ChangesCount > 0 { + headerText = fmt.Sprintf("%d changes · %d steps", rev.ChangesCount, rev.StepsDone) + } + + headerKids := []core.Node{ + core.Text{ + Content: headerText, + Style: core.Style{ + FlexGrow: 1, + FontSize: 12.5, + FontWeight: 600, + Color: p.TextPrimary, + }, + }, + } + for _, badge := range rev.NotChecked { + headerKids = append(headerKids, core.View{ + TestID: "agent-review-unchecked-badge", + Style: core.Style{ + Height: core.Pt(22), + Padding: core.Symmetric(0, 8), + CornerRadius: 6, + Background: p.Warning.Fill, + BorderWidth: 1, + BorderColor: p.Warning.Edge, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + }, + Children: []core.Node{ + core.Text{ + Content: badge, + Style: core.Style{ + FontSize: 11, + FontWeight: 500, + Color: p.Warning.Fg, + }, + }, + }, + }) + } + + kids := []core.Node{ + core.View{ + Style: core.Style{ + Direction: core.Row, + Wrap: core.Wrap, + AlignItems: core.AlignCenter, + Gap: 8, + Padding: core.Symmetric(10, 12), + Borders: core.Edges{Bottom: 1}, + BorderColor: p.Line, + }, + Children: headerKids, + }, + } + if rev.Summary != "" { + kids = append(kids, core.View{ + Style: core.Style{Padding: core.Symmetric(8, 12)}, + Children: []core.Node{ + core.Text{ + TestID: "agent-review-summary", + Content: rev.Summary, + Style: core.Style{ + FontSize: 12, + LineHeight: 18, + Color: p.TextSecondary, + }, + }, + }, + }) + } + + switch { + case rev.Kept: + kids = append(kids, core.View{ + Style: core.Style{Padding: core.Symmetric(8, 12)}, + Children: []core.Node{ + core.Text{ + Content: fmt.Sprintf("Kept · %s undoes", FormatShortcut("mod+z", osKind)), + Style: core.Style{FontSize: 12, Color: p.TextFaint}, + }, + }, + }) + case rev.Reverted: + kids = append(kids, core.View{ + Style: core.Style{Padding: core.Symmetric(8, 12)}, + Children: []core.Node{ + core.Text{ + Content: "Reverted · scene restored", + Style: core.Style{FontSize: 12, Color: p.TextFaint}, + }, + }, + }) + default: + kids = append(kids, core.View{ + Style: core.Style{ + Direction: core.Row, + Gap: 8, + Padding: core.All(12), + }, + Children: []core.Node{ + core.View{ + TestID: "agent-review-keep", + Role: core.RoleButton, + Label: ed.T("agent.keep"), + Focusable: func() bool { return true }, + Style: core.Style{ + FlexGrow: 1, + Height: core.Pt(30), + CornerRadius: 8, + Background: p.Accent.Fg, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.KeepPendingAgentTurnReview() + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("agent.keep"), + Style: core.Style{FontSize: 12.5, FontWeight: 600, Color: p.Accent.OnFill}, + }, + }, + }, + core.View{ + TestID: "agent-review-revert", + Role: core.RoleButton, + Label: ed.T("agent.revert"), + Focusable: func() bool { return true }, + Style: core.Style{ + Height: core.Pt(30), + Padding: core.Symmetric(0, 12), + CornerRadius: 8, + Background: p.LineRaised, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.RevertPendingAgentTurnReview() + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("agent.revert"), + Style: core.Style{FontSize: 12.5, FontWeight: 500, Color: p.TextPrimary}, + }, + }, + }, + }, + }) + } + + return core.View{ + TestID: "agent-review-card", + Style: core.Style{ + CornerRadius: 12, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + Overflow: core.Hidden, + }, + Children: kids, + } +} + +func agentWorkingFooterView(cx *core.Scope, ed *Editor, p SpecPalette, addDraft *core.Signal[string]) core.Node { + osKind := cx.Env().OS() + var addInputFocused bool + cx.Cleanup(func() { + if addInputFocused { + addInputFocused = false + ed.noteTextInputFocus(false) + } + }) + submitAdd := func(val string) { + txt := strings.TrimSpace(val) + if txt == "" { + return + } + if err := ed.AddToAgentRequest(txt); err != nil { + ed.report(err) + return + } + addDraft.Set("") + } + return core.View{ + TestID: "agent-composer", + Style: core.Style{ + Padding: core.All(12), + Gap: 8, + Borders: core.Edges{Top: 1}, + BorderColor: p.Line, + Background: p.Panel, + FlexShrink: 0, + }, + Children: []core.Node{ + SpecFocusWithinCard{ + TestID: "agent-add-card", + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Padding: core.Edges{Top: 6, Right: 6, Bottom: 6, Left: 12}, + Gap: 8, + }, + Children: []core.Node{ + core.Input{ + TestID: "agent-add-input", + Label: ed.T("agent.addPlaceholder"), + Placeholder: ed.T("agent.addPlaceholder"), + Value: addDraft.Get, + OnChange: addDraft.Set, + OnSubmit: submitAdd, + OnFocus: func() { + if !addInputFocused { + addInputFocused = true + ed.noteTextInputFocus(true) + } + }, + OnBlur: func() { + if addInputFocused { + addInputFocused = false + ed.noteTextInputFocus(false) + } + }, + Style: core.Style{ + FlexGrow: 1, + FlexBasis: core.Pt(0), + Height: core.Pt(28), + FontSize: 12.5, + Color: p.TextPrimary, + PlaceholderColor: p.TextFaint, + }, + }, + core.View{ + TestID: "agent-composer-stop", + Role: core.RoleButton, + Label: ed.T("agent.stop"), + Focusable: func() bool { return true }, + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + Height: core.Pt(30), + Padding: core.Symmetric(0, 12), + Gap: 6, + CornerRadius: 8, + Background: p.LineRaised, + FlexShrink: 0, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.StopAgent() + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(9), + Height: core.Pt(9), + CornerRadius: 2, + Background: p.TextPrimary, + }, + }, + core.Text{ + Content: ed.T("agent.stop"), + Style: core.Style{ + FontSize: 12, + FontWeight: 500, + Color: p.TextPrimary, + }, + }, + }, + }, + }, + }, + core.Text{ + TestID: "agent-footer-hint", + Content: fmt.Sprintf("%s · %s", FormatShortcut("mod+.", osKind), ed.T("agent.footerHint")), + Style: core.Style{ + FontSize: 11, + Color: p.TextFaint, + }, + }, + }, + } +} + +// agentStatusBarActivityView shows what the agent is currently doing in the bottom status bar +// while reminding the person that manual edits stay available. +func agentStatusBarActivityView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { + type activityKey struct { + text string + waiting bool + dark bool + } + actMemo := core.NewMemo(cx, func() activityKey { + _ = rev.Get() + return activityKey{ + text: ed.AgentStatusBarText(), + waiting: ed.AgentStatus() == AgentStatusWaitingForYou, + dark: ed.SpecPalette(cx).Dark, + } + }) + return core.Show{ + When: func() bool { + return actMemo.Get().text != "" + }, + Then: func(cx *core.Scope) core.Node { + return core.Dynamic(func(cx *core.Scope) core.Node { + k := actMemo.Get() + p := SpecPaletteFor(k.dark) + dotColor := p.Agent.Fg + if k.waiting { + dotColor = p.Warning.Fg + } + return core.View{ + TestID: "status-agent-activity", + Role: core.RoleStatus, + LiveRegion: core.LiveRegionPolite, + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 6, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(6), + Height: core.Pt(6), + CornerRadius: 3, + Background: dotColor, + FlexShrink: 0, + }, + }, + core.Text{ + TestID: "status-agent-activity-text", + Content: k.text, + Style: core.Style{ + FontSize: 11, + Color: p.TextMuted, + }, + }, + }, + } + }) + }, + } +} diff --git a/packages/game/editor/agent_states.go b/packages/game/editor/agent_states.go index 043be1e45..e66727c59 100644 --- a/packages/game/editor/agent_states.go +++ b/packages/game/editor/agent_states.go @@ -531,8 +531,8 @@ func (e *Editor) RecordAgentToolCall(rec AgentToolCallRecord) { var turn *AgentTurn activeComposer := false - if e.agent.activeRunCancel != nil && len(e.agent.turns) > 0 && !e.agent.turns[len(e.agent.turns)-1].Done { - // Active composer run owns the latest turn. + if (e.agent.activeRunCancel != nil || e.agent.liveRequestActive) && len(e.agent.turns) > 0 && !e.agent.turns[len(e.agent.turns)-1].Done { + // Active composer or live MCP request owns the latest turn. turn = &e.agent.turns[len(e.agent.turns)-1] activeComposer = true } else { @@ -703,13 +703,17 @@ func (e *Editor) recordConsecutiveToolFailure(turn *AgentTurn, toolName, callSum turn.FinishedAt = e.nowTime() e.agent.turnChangeSeq++ - // Cancel any active composer runner so the agent stops guessing immediately. + // Cancel any active composer runner or live MCP request so the agent stops guessing immediately. if e.agent.activeRunCancel != nil { e.agent.activeRunID++ cancel := e.agent.activeRunCancel e.agent.activeRunCancel = nil cancel() } + e.resolvePendingLiveAskLocked(PermissionOutcomeStopped) + e.closeLiveStopChLocked() + e.agent.liveRequestActive = false + e.agent.liveActivity = "" e.agent.workingStep = 0 e.agent.workingTotal = 0 e.SetAgentWaitingForYou(AgentOpenRequest{ @@ -768,6 +772,10 @@ func (e *Editor) KeepAgentPartial(turnID string) { turn.Review.Kept = true turn.Review.Discarded = false } + if turn.PendingReview != nil { + turn.PendingReview.Kept = true + turn.PendingReview.Reverted = false + } e.agent.turnChangeSeq++ e.scheduleAutoSaveIfNeeded() e.notify() @@ -1028,8 +1036,8 @@ func (e *Editor) markActiveTurnLost(reason string) { turn := &e.agent.turns[len(e.agent.turns)-1] now := e.nowTime() - // Only mark Lost if a composer run is actively running OR an external MCP turn was active recently with steps. - activeComposer := e.agent.activeRunCancel != nil && !turn.Done + // Only mark Lost if a composer/live run is actively running OR an external MCP turn was active recently with steps. + activeComposer := (e.agent.activeRunCancel != nil || e.agent.liveRequestActive) && !turn.Done activeExternal := turn.External && len(turn.Steps) > 0 && turn.Lost == nil && turn.Stuck == nil && now.Sub(turn.FinishedAt) <= 60*time.Second if !activeComposer && !activeExternal { return @@ -1041,6 +1049,10 @@ func (e *Editor) markActiveTurnLost(reason string) { e.agent.activeRunCancel = nil cancel() } + e.resolvePendingLiveAskLocked(PermissionOutcomeStopped) + e.closeLiveStopChLocked() + e.agent.liveRequestActive = false + e.agent.liveActivity = "" doneCount := 0 duringStep := 0 @@ -1329,6 +1341,15 @@ func (e *Editor) resumeTurnFromFirstNotDone(turn *AgentTurn) error { runner = defaultCLIAgentRunner() } + e.resolvePendingLiveAskLocked(PermissionOutcomeStopped) + e.closeLiveStopChLocked() + e.agent.liveRequestActive = true + e.agent.liveStopped = false + e.agent.liveStopCh = make(chan struct{}) + e.agent.liveDeniedKeys = make(map[string]bool) + e.agent.liveQueuedFollowUps = nil + e.agent.liveActivity = "Agent is working · manual edits stay available" + e.agent.activeRunID++ runID := e.agent.activeRunID ctx, cancel := context.WithCancel(context.Background()) @@ -1394,6 +1415,15 @@ func (e *Editor) continueExistingTurn(turn *AgentTurn, prompt, stepTitle string, }) e.agent.turnChangeSeq++ + e.resolvePendingLiveAskLocked(PermissionOutcomeStopped) + e.closeLiveStopChLocked() + e.agent.liveRequestActive = true + e.agent.liveStopped = false + e.agent.liveStopCh = make(chan struct{}) + e.agent.liveDeniedKeys = make(map[string]bool) + e.agent.liveQueuedFollowUps = nil + e.agent.liveActivity = "Agent is working · manual edits stay available" + e.agent.activeRunID++ runID := e.agent.activeRunID ctx, cancel := context.WithCancel(context.Background()) @@ -1867,6 +1897,10 @@ func (e *Editor) KeepAgentTurnDiffReview(turnID string) bool { } turn.Review.Kept = true turn.Review.Discarded = false + if turn.PendingReview != nil { + turn.PendingReview.Kept = true + turn.PendingReview.Reverted = false + } if turn.Partial != nil { turn.Partial.Kept = true turn.Partial.Pointing = false @@ -1909,6 +1943,10 @@ func (e *Editor) DiscardAgentTurnReview(turnID string) bool { turn.Review.Removed = nil turn.Review.PlusLines = 0 turn.Review.MinusLines = 0 + if turn.PendingReview != nil { + turn.PendingReview.Kept = false + turn.PendingReview.Reverted = true + } turn.baselineDoc = nil turn.baselineYAML = "" turn.lastSeenIDs = nil diff --git a/packages/game/editor/agent_threads_ui.go b/packages/game/editor/agent_threads_ui.go index f4ae74d8b..18db98b8b 100644 --- a/packages/game/editor/agent_threads_ui.go +++ b/packages/game/editor/agent_threads_ui.go @@ -493,7 +493,18 @@ func agentEmptyThreadBody(cx *core.Scope, ed *Editor, p SpecPalette) core.Node { } } -func agentThreadConversationBody(cx *core.Scope, ed *Editor, rev *core.Signal[uint64], p SpecPalette, t *AgentThread, turns []AgentTurn, openReq *AgentOpenRequest, openReqRef *core.Ref) core.Node { +func agentThreadConversationBody( + cx *core.Scope, + ed *Editor, + rev *core.Signal[uint64], + p SpecPalette, + osKind core.OS, + t *AgentThread, + turns []AgentTurn, + pendingAsk *AgentPermissionPrompt, + openReq *AgentOpenRequest, + openReqRef, cardRef, allowOnceRef, allowAlwaysRef, denyRef *core.Ref, +) core.Node { expandedID := ed.ExpandedAgentRequestID() var nodes []core.Node if ready := ed.ReadyToReviewTurns(); len(ready) > 0 { @@ -920,7 +931,7 @@ func agentThreadConversationBody(cx *core.Scope, ed *Editor, rev *core.Signal[ui Children: latestNodes, }) for ti, turn := range turns { - nodes = append(nodes, agentTurnView(ed, rev, ti, turn, p)) + nodes = append(nodes, agentTurnView(ed, rev, ti, turn, p, osKind)) } if ed.HasAgentPanelCard() { nodes = append(nodes, agentReviewPanelCards(ed, p, turns)...) @@ -937,7 +948,9 @@ func agentThreadConversationBody(cx *core.Scope, ed *Editor, rev *core.Signal[ui if activeRev := ed.ActiveAgentReview(); activeRev != nil { nodes = append(nodes, agentTurnReviewDrawer(ed, activeRev, p)) } - if openReq != nil && !strings.HasSuffix(openReq.ID, "-stuck") && !strings.HasSuffix(openReq.ID, "-reconnect-ask") { + if pendingAsk != nil { + nodes = append(nodes, agentPermissionCardView(p, ed, *pendingAsk, osKind, cardRef, allowOnceRef, allowAlwaysRef, denyRef)) + } else if openReq != nil && !strings.HasSuffix(openReq.ID, "-stuck") && !strings.HasSuffix(openReq.ID, "-reconnect-ask") { nodes = append(nodes, agentOpenRequestCard(ed, openReq, openReqRef, p)) } if !limitReached && len(limitQueued) > 0 { diff --git a/packages/game/editor/agent_ui.go b/packages/game/editor/agent_ui.go index 7ff7c977d..f01b3bd00 100644 --- a/packages/game/editor/agent_ui.go +++ b/packages/game/editor/agent_ui.go @@ -972,17 +972,24 @@ 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, // scene-grouped thread header and switcher popover, scrollable thread of persisted requests / -// live user turns / streamed steps / open requests or empty-thread orientation, and AgentComposerView -// (@-mentions, context chips, hover preview, and context meter). +// live user turns / streamed steps / permission cards / review summaries or empty-thread orientation, +// and AgentComposerView (@-mentions, context chips, hover preview, and context meter) or the +// working "Add to this request" + Stop footer. func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { + addDraft := core.NewSignal(cx, "") openReqRef := new(core.Ref) panelRef := new(core.Ref) switcherBtnRef := new(core.Ref) + cardRef := new(core.Ref) + allowOnceRef := new(core.Ref) + allowAlwaysRef := new(core.Ref) + denyRef := new(core.Ref) ed.SetAgentPanelRef(panelRef) cx.Cleanup(func() { if ed.focus.ctrl != nil && ed.focus.ctrl.agentPanelRef == panelRef { ed.SetAgentPanelRef(nil) } + ed.setLivePermissionCardFocused(false) }) if ed.focus.ctrl != nil { ed.focus.ctrl.registerCandidate(cx, RegionInspector, switcherBtnRef, func() bool { @@ -990,23 +997,91 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N }) } + pendingAskMemo := core.NewMemo(cx, func() bool { + _ = rev.Get() + return ed.PendingAgentPermissionAsk() != nil + }) + // Permission card keyboard shortcuts (Spec.dc.html "CARD · PERMISSION OR QUESTION FOCUSED"): + // Mod+Enter allows once, Alt+Enter adds Always rule, Mod+Backspace/Delete denies, + // Up/Down cycle choices. Mounted only while a permission ask is pending so it never + // shadows Scene Tree, Sketch, Review, or Composer shortcuts at rest. + permissionCardKeyScope := core.Show{ + When: pendingAskMemo.Get, + Then: func(cx *core.Scope) core.Node { + cardKeyOpts := core.KeyOptions{When: core.KeyNotEditing} + cx.OnKeyWith("mod+enter", cardKeyOpts, func() { + if ed.shortcutCaptureActive || ed.CapturingKey() { + return + } + if cardRef.HoldsFocus() { + ed.AllowPermissionOnce() + return + } + ed.dispatchBoundShortcut("mod+enter") + }) + cx.OnKeyWith("alt+enter", cardKeyOpts, func() { + if ed.shortcutCaptureActive || ed.CapturingKey() || !cardRef.HoldsFocus() { + return + } + ed.AllowPermissionAlways() + }) + cx.OnKeyWith("mod+backspace", cardKeyOpts, func() { + if ed.shortcutCaptureActive || ed.CapturingKey() { + return + } + if cardRef.HoldsFocus() { + ed.DenyPermission() + return + } + ed.dispatchBoundShortcut("mod+backspace") + }) + cx.OnKeyWith("mod+delete", cardKeyOpts, func() { + if ed.shortcutCaptureActive || ed.CapturingKey() || !cardRef.HoldsFocus() { + return + } + ed.DenyPermission() + }) + cx.OnKeyWith("down", cardKeyOpts, func() { + if ed.shortcutCaptureActive || ed.CapturingKey() || !cardRef.HoldsFocus() { + return + } + moveAgentCardFocus([]*core.Ref{allowOnceRef, allowAlwaysRef, denyRef}, +1) + }) + cx.OnKeyWith("up", cardKeyOpts, func() { + if ed.shortcutCaptureActive || ed.CapturingKey() || !cardRef.HoldsFocus() { + return + } + moveAgentCardFocus([]*core.Ref{allowOnceRef, allowAlwaysRef, denyRef}, -1) + }) + return nil + }, + } + cx.OnKeyWith("escape", core.KeyOptions{When: core.KeyAlways}, func() { + if ed.shortcutCaptureActive || ed.CapturingKey() { + return + } + if cardRef.HoldsFocus() { + // Spec rule 02 & CARD scope: Esc leaves the permission card unanswered; + // the agent keeps waiting and NEVER denies or stops. + if refMounted(panelRef) { + panelRef.Focus() + } + return + } if ed.AgentSwitcherOpen() { ed.SetAgentSwitcherOpen(false) + return } - }) - - // Esc cancels "Let me point" viewport picking, or stops an active agent run when not editing text or in a modal. - cx.OnKeyWith("escape", core.KeyOptions{When: core.KeyNotEditing}, func() { - if ed.CommandPaletteOpen() || ed.ConnectDialogOpen() || ed.SettingsOpen() || ed.AskInPlaceOpen() || ed.PermissionsDraftOpen() || ed.HistoryPreviewActive() || ed.AgentSwitcherOpen() || ed.MentionPickerOpen() || ed.ContextBreakdownOpen() { + if ed.CommandPaletteOpen() || ed.ConnectDialogOpen() || ed.SettingsOpen() || ed.AskInPlaceOpen() || ed.PermissionsDraftOpen() || ed.HistoryPreviewActive() || ed.MentionPickerOpen() || ed.ContextBreakdownOpen() { return } if ed.AgentPointingActive() { ed.CancelAgentPointing() return } - if ed.AgentWorking() && !ed.IsTyping() { - ed.StopAgentRun() + if ed.SketchActive() { + ed.FinishSketch() } }) focusSeqMemo := core.NewMemo(cx, func() uint64 { @@ -1019,6 +1094,24 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N } }) + focusCardSeqMemo := core.NewMemo(cx, func() uint64 { + _ = rev.Get() + return ed.agent.liveFocusCardSeq + }) + lastFocusedCardSeq := uint64(0) + cx.Effect(func() { + seq := focusCardSeqMemo.Get() + if seq == 0 || seq == lastFocusedCardSeq { + return + } + lastFocusedCardSeq = seq + cx.Post(func() { + if refMounted(allowOnceRef) { + allowOnceRef.Focus() + } + }) + }) + threadKey := core.NewMemo(cx, func() string { _ = rev.Get() var b strings.Builder @@ -1045,7 +1138,11 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N ed.AgentThreadID(), ) for _, t := range ed.agent.turns { - fmt.Fprintf(&b, "%s:%s:%d:%d:%v:%v:%v:%s:%s:%d:%d:%d", t.ID, t.Status, len(t.Steps), len(t.Images), t.Done, t.Stopped, t.SkipPlan, t.ReviewState, t.CheckpointID, len(t.Summary), len(t.Reply), len(t.Error)) + kept, revd, notChk := false, false, 0 + if t.PendingReview != nil { + kept, revd, notChk = t.PendingReview.Kept, t.PendingReview.Reverted, len(t.PendingReview.NotChecked) + } + fmt.Fprintf(&b, "%s:%s:%d:%d:%d:%v:%v:%v:%s:%s:%v:%v:%d:%d:%d:%d", t.ID, t.Status, len(t.Steps), len(t.Images), len(t.FollowUps), t.Done, t.Stopped, t.SkipPlan, t.ReviewState, t.CheckpointID, kept, revd, notChk, len(t.Summary), len(t.Reply), len(t.Error)) if t.Partial != nil { fmt.Fprintf(&b, ":P(%v,%v,%v,%v)", t.Partial.Pointing, t.Partial.Kept, t.Partial.TryingAnother, t.Partial.HasPoint) } @@ -1066,7 +1163,7 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N } b.WriteByte('|') for _, st := range t.Steps { - fmt.Fprintf(&b, "%s=%s;", st.ID, st.Status) + fmt.Fprintf(&b, "%s=%s:%v;", st.ID, st.Status, st.CanAllowNow) } if t.ModelError != nil { fmt.Fprintf(&b, "me=%d:%d:%d:%v:%s:%s;", t.ModelError.StatusCode, t.ModelError.RetryAttempt, t.ModelError.RetryTotal, t.ModelError.Retrying, t.ModelError.Headline, t.ModelError.AlternativeAgent) @@ -1075,7 +1172,9 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N for _, q := range ed.agent.queued { fmt.Fprintf(&b, "q=%s:%v;", q.ID, q.Offline) } - if ed.agent.openRequest != nil { + if ask := ed.PendingAgentPermissionAsk(); ask != nil { + fmt.Fprintf(&b, "ask:%s|", ask.ID) + } else if ed.agent.openRequest != nil { fmt.Fprintf(&b, "req:%s|", ed.agent.openRequest.ID) } if ed.DataTableReviewPending() { @@ -1084,11 +1183,17 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N return b.String() }) + workingMemo := core.NewMemo(cx, func() bool { + _ = rev.Get() + return ed.AgentWorking() + }) + darkMemo := core.NewMemo(cx, func() bool { _ = rev.Get() return ed.SpecPalette(cx).Dark }) + osKind := cx.Env().OS() tabBar := core.Dynamic(func(cx *core.Scope) core.Node { p := SpecPaletteFor(darkMemo.Get()) return rightRailTabBar(cx, ed, rev, p, true) @@ -1100,6 +1205,7 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N turns := ed.AgentTurns() composerTurns := ed.AgentThreadTurns() summary := ed.AgentThreadSummary() + pendingAsk := ed.PendingAgentPermissionAsk() openReq := ed.AgentOpenRequest() hasReviewCard := ed.HasAgentPanelCard() dtPending := ed.DataTableReviewPending() @@ -1117,10 +1223,10 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N offlineNodes := agentOfflineAndQueueSection(ed, p) if active != nil && len(active.Requests) > 0 { - return agentThreadConversationBody(cx, ed, rev, p, active, turns, openReq, openReqRef) + return agentThreadConversationBody(cx, ed, rev, p, osKind, active, turns, pendingAsk, openReq, openReqRef, cardRef, allowOnceRef, allowAlwaysRef, denyRef) } ready := ed.ReadyToReviewTurns() - if summary != "" || len(turns) > 0 || len(composerTurns) > 0 || openReq != nil || len(ready) > 0 || hasReviewCard || dtPending || len(queued) > 0 || limitReached || hasPendingTurn || len(offlineNodes) > 0 || activeRev != nil { + if summary != "" || len(turns) > 0 || len(composerTurns) > 0 || pendingAsk != nil || openReq != nil || len(ready) > 0 || hasReviewCard || dtPending || len(queued) > 0 || limitReached || hasPendingTurn || len(offlineNodes) > 0 || activeRev != nil { var items []core.Node if len(ready) > 0 { items = append(items, agentReadyToReviewBanner(ed, p, len(ready))) @@ -1135,7 +1241,7 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N items = append(items, agentComposerSummaryCard(ed, p, summary)) } for ti, turn := range turns { - items = append(items, agentTurnView(ed, rev, ti, turn, p)) + items = append(items, agentTurnView(ed, rev, ti, turn, p, osKind)) } if len(composerTurns) > 0 { items = append(items, agentComposerThreadNodes(ed, p, composerTurns)...) @@ -1155,7 +1261,9 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N if activeRev != nil { items = append(items, agentTurnReviewDrawer(ed, activeRev, p)) } - if openReq != nil && !strings.HasSuffix(openReq.ID, "-stuck") && !strings.HasSuffix(openReq.ID, "-reconnect-ask") { + if pendingAsk != nil { + items = append(items, agentPermissionCardView(p, ed, *pendingAsk, osKind, cardRef, allowOnceRef, allowAlwaysRef, denyRef)) + } else if openReq != nil && !strings.HasSuffix(openReq.ID, "-stuck") && !strings.HasSuffix(openReq.ID, "-reconnect-ask") { items = append(items, agentOpenRequestCard(ed, openReq, openReqRef, p)) } if !limitReached && len(limitQueued) > 0 { @@ -1182,11 +1290,25 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N return agentEmptyThreadBody(cx, ed, p) }) + footer := core.Show{ + When: workingMemo.Get, + Then: func(cx *core.Scope) core.Node { + return core.Dynamic(func(cx *core.Scope) core.Node { + p := SpecPaletteFor(darkMemo.Get()) + return agentWorkingFooterView(cx, ed, p, addDraft) + }) + }, + Else: func(cx *core.Scope) core.Node { + return AgentComposerView(cx, ed, rev) + }, + } + return core.View{ - TestID: "agent-panel", - Ref: panelRef, - Role: core.RoleRegion, - Label: "Agent panel", + TestID: "agent-panel", + Ref: panelRef, + Role: core.RoleRegion, + Label: "Agent panel", + Focusable: func() bool { return true }, StyleFunc: func() core.Style { p := SpecPaletteFor(darkMemo.Get()) return core.Style{ @@ -1199,6 +1321,7 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N } }, Children: []core.Node{ + permissionCardKeyScope, tabBar, agentThreadHeaderBar(cx, ed, rev, switcherBtnRef), core.View{ @@ -1221,7 +1344,7 @@ func AgentPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.N }, }, }, - AgentComposerView(cx, ed, rev), + footer, }, } } @@ -1331,7 +1454,7 @@ func agentEmptyStateCard(ed *Editor, p SpecPalette) core.Node { } } -func agentTurnView(ed *Editor, rev *core.Signal[uint64], turnIdx int, turn AgentTurn, p SpecPalette) core.Node { +func agentTurnView(ed *Editor, rev *core.Signal[uint64], turnIdx int, turn AgentTurn, p SpecPalette, osKind core.OS) core.Node { var children []core.Node if turn.Automation { stateLabel, stateFg, stateBg, stateEdge := automationReviewBadgeStyle(ed, turn.ReviewState, p) @@ -1454,7 +1577,7 @@ func agentTurnView(ed *Editor, rev *core.Signal[uint64], turnIdx int, turn Agent if len(turn.Steps) > 0 && turn.StoppedState == nil { stepNodes := make([]core.Node, 0, len(turn.Steps)) for si, step := range turn.Steps { - stepNodes = append(stepNodes, agentStepRow(turnIdx, si, step, p)) + stepNodes = append(stepNodes, agentLiveStepRow(ed, turnIdx, si, step, p)) } stepStyle := core.Style{ Gap: 8, @@ -1469,11 +1592,15 @@ func agentTurnView(ed *Editor, rev *core.Signal[uint64], turnIdx int, turn Agent }) } + for fi, fu := range turn.FollowUps { + children = append(children, agentFollowUpBubble(p, fmt.Sprintf("agent-followup-%d-%d", turnIdx, fi), fu.Text)) + } + replyText := turn.Summary if replyText == "" { replyText = turn.Reply } - if replyText != "" { + if replyText != "" && (turn.PendingReview == nil || turn.PendingReview.Summary != replyText) { children = append(children, core.View{ TestID: "agent-turn-reply-" + turn.ID, Children: []core.Node{ @@ -1531,6 +1658,8 @@ func agentTurnView(ed *Editor, rev *core.Signal[uint64], turnIdx int, turn Agent } if turn.StoppedState != nil { children = append(children, agentStoppedSection(ed, turnIdx, turn, p)...) + } else if turn.PendingReview != nil && (turn.Done || turn.Stopped) { + children = append(children, agentTurnReviewCardView(p, ed, *turn.PendingReview, osKind)) } else if turn.Stopped { children = append(children, core.Text{ TestID: fmt.Sprintf("agent-turn-stopped-%d", turnIdx), diff --git a/packages/game/editor/autosave.go b/packages/game/editor/autosave.go index 63969c925..3c92e180e 100644 --- a/packages/game/editor/autosave.go +++ b/packages/game/editor/autosave.go @@ -228,7 +228,7 @@ func (e *Editor) HasOpenReview() bool { if e.HasOpenTaskReview() { return true } - if e.AgentReviewOpen() || e.PermissionsDraftOpen() || e.AgentTurnPending() || e.HasPendingAgentTurn() || e.HasUnkeptAgentTurnReview() { + if e.AgentReviewOpen() || e.PermissionsDraftOpen() || e.AgentTurnPending() || e.HasPendingAgentTurn() || e.HasUnkeptAgentTurnReview() || e.HasPendingAgentTurnReview() { return true } if e.CutsceneReviewOpen() { diff --git a/packages/game/editor/commands.go b/packages/game/editor/commands.go index f10b33ad4..4c2bfcd01 100644 --- a/packages/game/editor/commands.go +++ b/packages/game/editor/commands.go @@ -3085,45 +3085,56 @@ func (e *Editor) bindShortcuts(cx *core.Scope, rev *core.Signal[uint64]) { continue } cx.OnKeyWith(key, core.KeyOptions{When: core.KeyNotEditing}, func() { - if e.shortcutCaptureActive || e.CapturingKey() { - return - } - active, ok := e.resolveShortcutCommand(key) - if !ok { - if key == "mod+enter" && - !e.PermissionsDraftOpen() && !e.StartScreenOpen() && !e.FirstRunFullScreenOpen() && - !e.ReviewOpen() && !e.MergeConflictOpen() && !e.DataTableReviewOpen() && !e.UsagesScreenOpen() && - !e.SettingsOpen() && !e.AssetGeneratorOpen() && !e.ConnectDialogOpen() && - !e.PendingTurnPromptOpen() && !e.BuildReleaseScreenOpen() && - e.AgentReviewOpen() && !e.Playing() { - _, err := e.KeepAllReviewChanges() - e.report(err) - } - return - } - if active.ID == CmdToolPaintTile && key == "b" && (e.TileReviewOpen() || e.ReviewOpen()) && e.ViewMode == ViewMode2D && !e.Playing() { - return - } - if active.ID == CmdReviewPeekBefore && key == "b" && e.ReviewOpen() { - // Holding B in ReviewScreenView is tracked continuously by core.KeyHeld(cx, "b"); - // do not flip peek on initial keydown so KeyDown/KeyUp works cleanly as a hold. - return - } - if active.ID == CmdPlayStop && e.Project != nil && e.ProjectPath != "" && !e.Playing() { - if !e.GameRunning() { - e.report(e.RunGame()) - } - return - } - if err := active.Run(); err != nil { - e.report(err) - } + e.dispatchBoundShortcut(key) }) } } }) } +func (e *Editor) dispatchBoundShortcut(key string) { + if e.shortcutCaptureActive || e.CapturingKey() { + return + } + if e.PendingAgentPermissionCardFocused() { + switch key { + case "mod+enter": + e.AllowPermissionOnce() + return + case "alt+enter": + e.AllowPermissionAlways() + return + case "mod+backspace", "mod+delete": + e.DenyPermission() + return + } + } + active, ok := e.resolveShortcutCommand(key) + if !ok { + if key == "mod+enter" { + e.handleGlobalModEnter() + } + return + } + if active.ID == CmdToolPaintTile && key == "b" && (e.TileReviewOpen() || e.ReviewOpen()) && e.ViewMode == ViewMode2D && !e.Playing() { + return + } + if active.ID == CmdReviewPeekBefore && key == "b" && e.ReviewOpen() { + // Holding B in ReviewScreenView is tracked continuously by core.KeyHeld(cx, "b"); + // do not flip peek on initial keydown so KeyDown/KeyUp works cleanly as a hold. + return + } + if active.ID == CmdPlayStop && e.Project != nil && e.ProjectPath != "" && !e.Playing() { + if !e.GameRunning() { + e.report(e.RunGame()) + } + return + } + if err := active.Run(); err != nil { + e.report(err) + } +} + // bindReviewShortcuts binds ScopeReview command shortcuts inside ReviewScreenView's own scope. // Keeping these bindings scoped to ReviewScreenView ensures they are active ONLY while Review // is open and automatically released when Review closes, preventing Review keys like 'x' or diff --git a/packages/game/editor/editorcmd/agent_working_screenshot_test.go b/packages/game/editor/editorcmd/agent_working_screenshot_test.go new file mode 100644 index 000000000..6ceffd0b6 --- /dev/null +++ b/packages/game/editor/editorcmd/agent_working_screenshot_test.go @@ -0,0 +1,154 @@ +package editorcmd_test + +import ( + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func agentScreenshotScene() *sceneformat.SceneDoc { + return &sceneformat.SceneDoc{ + Version: sceneformat.CurrentVersion, + Name: "level_01", + VirtualWidth: 640, + VirtualHeight: 360, + BackgroundColor: "#15181D", + Layers: []sceneformat.LayerDoc{ + { + Name: "actors", + Space: sceneformat.SpaceWorld, + Order: 0, + Objects: []sceneformat.ObjectDoc{ + {ID: "knight", Name: "Knight", X: 360, Y: 220}, + {ID: "slime_01", Name: "slime_01", X: 220, Y: 280}, + {ID: "slime_02", Name: "slime_02", X: 280, Y: 280}, + {ID: "slime_03", Name: "slime_03", X: 340, Y: 280}, + }, + }, + }, + } +} + +// TestAgentWorkingScreenshots captures real macOS native screenshots of the Agent panel +// matching docs/design/editor/Working.dc.html and Permissions.dc.html (Dark and Light themes). +func TestAgentWorkingScreenshots(t *testing.T) { + ed, err := editor.New(agentScreenshotScene(), nil) + if err != nil { + t.Fatalf("editor.New: %v", err) + } + t.Cleanup(func() { _ = ed.Close() }) + _ = ed.SetLanguage(editor.LanguageEnglish) + _ = ed.SetAppearance(editor.AppearanceDark) + _ = ed.SelectPermissionProfile(editor.PermissionProfileCautious) + ed.NotifyAgentMCPConnected(editor.AgentClientInfo{ + ID: "c1", + Name: "claude-code", + DisplayName: "Claude Code", + Transport: "stdio", + }) + ed.SetRightRailTab(editor.RightTabAgent) + + base := time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC) + now := base + ed.Now = func() time.Time { return now } + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900)) + app.Settle() + + evalPlaytest := ed.EvaluatePermission(editor.PermissionRequest{ + Tool: "game_playtest", + Action: editor.PermissionActionRun, + Target: editor.PermissionRunPlaytests, + }) + + // 1. Working + Permission Card (matching Working.dc.html). + app.Post(func() { + ed.StartAgentRequest("Put three slimes patrolling the lower floor and a short coin trail toward the door.") + s1 := ed.BeginAgentToolStep("scene_read", "Read level_01.scene.yaml, slime.prefab.yaml", "", nil) + ed.FinishAgentToolStep(s1, "Read level_01.scene.yaml, slime.prefab.yaml", "", nil, false) + s2 := ed.BeginAgentToolStep("scene_edit", "Placed 3 slimes on the 120 px floor span, x 220–340", "", []string{"slime_01", "slime_02", "slime_03"}) + ed.FinishAgentToolStep(s2, "Placed 3 slimes on the 120 px floor span, x 220–340", "", []string{"slime_01", "slime_02", "slime_03"}, false) + s3 := ed.BeginAgentToolStep("scene_edit", "Placed 3 coins toward the door", "", nil) + ed.FinishAgentToolStep(s3, "Placed 3 coins toward the door", "", nil, false) + s4 := ed.BeginAgentToolStep("game_check", "Ran game check", "", nil) + ed.FinishAgentToolStep(s4, "Ran game check", "no problems", nil, false) + s5 := ed.BeginAgentToolStep("game_playtest", "Play 10 s headless", "Agent is playing level_01 headless · manual edits stay available", nil) + ed.BeginAgentPermissionAsk(editor.AgentPermissionPrompt{ + StepID: s5, + Title: "Allow the agent to run the game?", + ShortAction: "the playtest", + Why: "It wants to play level_01 headless for 10 seconds to check the slimes stay on the floor.", + Effect: "Nothing is saved.", + RuleSource: evalPlaytest.Reason, + RulePreview: editor.AlwaysRuleForEvaluation(evalPlaytest).Summary(), + AlwaysLabel: "Always allow headless playtests", + Tool: "game_playtest", + PermissionKey: "run:playtests", + Evaluation: evalPlaytest, + }) + now = base.Add(32 * time.Second) + }) + app.Settle() + app.Screenshot("agent-working-permission-card") + + // 2. Denied + Not playtested summary (matching Permissions.dc.html Denied). + app.Post(func() { + ed.DenyPermission() + ed.CompleteAgentRequest("Done, but not playtested: couldn't confirm the slimes stay on the floor. Play it yourself with ⌘P, or allow the playtest above.") + }) + app.Settle() + app.Screenshot("agent-denied-summary") + + // 3. Stopped + "Agent stopped" toast with Review. + app.Post(func() { + ed.StartAgentRequest("Put three slimes patrolling the lower floor and a short coin trail toward the door.") + s1 := ed.BeginAgentToolStep("scene_read", "Read level_01.scene.yaml, slime.prefab.yaml", "", nil) + ed.FinishAgentToolStep(s1, "Read level_01.scene.yaml, slime.prefab.yaml", "", nil, false) + s2 := ed.BeginAgentToolStep("scene_edit", "Placed 3 slimes on the lower floor", "", []string{"slime_01", "slime_02", "slime_03"}) + ed.FinishAgentToolStep(s2, "Placed 3 slimes on the lower floor", "", []string{"slime_01", "slime_02", "slime_03"}, false) + s3 := ed.BeginAgentToolStep("game_check", "Ran game check", "", nil) + ed.FinishAgentToolStep(s3, "Ran game check", "no problems", nil, false) + s4 := ed.BeginAgentToolStep("game_playtest", "the playtest", "", nil) + ed.BeginAgentPermissionAsk(editor.AgentPermissionPrompt{ + StepID: s4, + Title: "Allow the agent to run the game?", + ShortAction: "the playtest", + Tool: "game_playtest", + Evaluation: evalPlaytest, + }) + ed.StopAgent() + }) + app.Settle() + app.Screenshot("agent-stopped-toast") + + // 4. Light theme parity check for Working + Permission Card. + app.Post(func() { + ed.DismissToast() + _ = ed.SetAppearance(editor.AppearanceLight) + ed.StartAgentRequest("Put three slimes patrolling the lower floor.") + s1 := ed.BeginAgentToolStep("scene_read", "Read level_01.scene.yaml", "", nil) + ed.FinishAgentToolStep(s1, "Read level_01.scene.yaml", "", nil, false) + s2 := ed.BeginAgentToolStep("game_playtest", "Play 10 s headless", "", nil) + ed.BeginAgentPermissionAsk(editor.AgentPermissionPrompt{ + StepID: s2, + Title: "Allow the agent to run the game?", + ShortAction: "the playtest", + Why: "It wants to play level_01 headless for 10 seconds.", + Effect: "Nothing is saved.", + RuleSource: evalPlaytest.Reason, + RulePreview: editor.AlwaysRuleForEvaluation(evalPlaytest).Summary(), + AlwaysLabel: "Always allow headless playtests", + Tool: "game_playtest", + PermissionKey: "run:playtests", + Evaluation: evalPlaytest, + }) + }) + app.Settle() + app.Screenshot("agent-working-light") +} diff --git a/packages/game/editor/editormcp/agent.go b/packages/game/editor/editormcp/agent.go index e609eff7c..335212921 100644 --- a/packages/game/editor/editormcp/agent.go +++ b/packages/game/editor/editormcp/agent.go @@ -12,6 +12,9 @@ import ( // Agent turn tool names exposed by editormcp alongside scene_read, scene_edit, selection_get, and viewport_image. const ( + // ToolAgentReportStep lets a connected agent report a live progress step in its own plain words + // along with the scene object IDs the step touches, and receive queued "Add to this request" follow-ups. + ToolAgentReportStep = "agent_report_step" // ToolAgentTurnGet returns the latest (or named) agent turn started from the ⌘L in-place composer or Agent panel, // with the user's prompt, skipPlan flag, selection object IDs, open scene path and YAML, and viewport PNG image. ToolAgentTurnGet = "agent_turn_get" @@ -20,6 +23,11 @@ const ( ) const ( + agentReportStepSchema = `{"type":"object","additionalProperties":false,"required":["text"],"properties":{` + + `"text":{"type":"string","minLength":1,"description":"Plain-words description of what the agent did or is doing, such as \"Placed 3 coins toward the door\""},` + + `"objects":{"type":"array","items":{"type":"string"},"description":"Optional scene object IDs this step touches"},` + + `"status":{"type":"string","enum":["running","done"],"description":"Whether this step is still running (spinner) or finished (check); defaults to done"}}}` + agentTurnGetSchema = `{"type":"object","additionalProperties":false,"properties":{` + `"turnId":{"type":"string","description":"Optional turn ID to read; defaults to the latest agent turn"},` + `"includeScene":{"type":"boolean","description":"Include the open scene YAML snapshot in structured output (defaults to true)"},` + @@ -33,6 +41,14 @@ const ( func agentTools() []Tool { return []Tool{ + { + Name: ToolAgentReportStep, + Title: "Report an agent step", + Description: "Report a live progress step in the Agent panel in plain words, optionally naming the scene object IDs it touches, and receive any follow-up instructions the person added to the running request.", + InputSchema: []byte(agentReportStepSchema), + Action: ActionRead, + Handler: agentReportStep, + }, { Name: ToolAgentTurnGet, Title: "Get the latest agent turn", diff --git a/packages/game/editor/editormcp/agent_live.go b/packages/game/editor/editormcp/agent_live.go new file mode 100644 index 000000000..d5ee4e3f4 --- /dev/null +++ b/packages/game/editor/editormcp/agent_live.go @@ -0,0 +1,735 @@ +package editormcp + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/nsgo-dev/game/packages/game/editor" +) + +const ( + maxReportStepTextBytes = 4096 + maxReportStepObjects = 128 +) + +// AgentReportStepResult is the structured payload returned by agent_report_step. +type AgentReportStepResult struct { + StepID string `json:"stepId"` + Text string `json:"text"` + Objects []string `json:"objects,omitempty"` + Status string `json:"status"` + FollowUps []string `json:"followUps,omitempty"` +} + +// PermissionDeniedResult is returned as non-fatal structured content when a tool call is denied +// by the person on an interactive Agent panel permission card so the agent continues without retrying it. +type PermissionDeniedResult struct { + Denied bool `json:"denied"` + AlreadyDenied bool `json:"alreadyDenied,omitempty"` + BlockedByRule bool `json:"blockedByRule,omitempty"` + ContinuedWithoutIt bool `json:"continuedWithoutIt,omitempty"` + Rule string `json:"rule,omitempty"` + Message string `json:"message"` +} + +func agentReportStep(ctx context.Context, c *Call) (*Result, error) { + var args struct { + Text string `json:"text"` + Objects []string `json:"objects"` + Status string `json:"status"` + } + if err := c.Decode(&args); err != nil { + return nil, fmt.Errorf("agent_report_step: %w", err) + } + text := strings.TrimSpace(args.Text) + if text == "" { + return nil, errors.New("agent_report_step: text must not be empty") + } + if strings.IndexByte(text, 0) >= 0 { + return nil, errors.New("agent_report_step: text must not contain NUL bytes") + } + if len(text) > maxReportStepTextBytes { + return nil, fmt.Errorf("agent_report_step: text exceeds maximum size (%d bytes)", maxReportStepTextBytes) + } + if len(args.Objects) > maxReportStepObjects { + return nil, fmt.Errorf("agent_report_step: objects exceeds maximum count (%d)", maxReportStepObjects) + } + for _, obj := range args.Objects { + if strings.IndexByte(obj, 0) >= 0 { + return nil, errors.New("agent_report_step: object IDs must not contain NUL bytes") + } + } + running := args.Status == "running" + if args.Status != "" && args.Status != "running" && args.Status != "done" { + return nil, fmt.Errorf("agent_report_step: invalid status %q (want running or done)", args.Status) + } + var ( + stepID string + followUps []string + stopped bool + ) + err := c.Editor(ctx, func(ed *editor.Editor) error { + if ed.AgentStopped() { + stopped = true + return nil + } + stepID = ed.ReportAgentStep(text, args.Objects, running) + followUps = ed.DrainAgentFollowUps() + return nil + }) + if err != nil { + return nil, err + } + if stopped { + return nil, errors.New("agent_report_step: the person stopped this request; stop working and leave changes for review") + } + status := "done" + if running { + status = "running" + } + res := AgentReportStepResult{ + StepID: stepID, + Text: text, + Objects: args.Objects, + Status: status, + FollowUps: followUps, + } + msg := fmt.Sprintf("Recorded step: %s", text) + if len(followUps) > 0 { + msg += "\nAdditional instructions from the person: " + strings.Join(followUps, " | ") + } + return &Result{Text: msg, Structured: res}, nil +} + +type toolStepMeta struct { + permKey string + runningText string + activity string + askTitle string + askShort string + askWhy string + askEffect string + alwaysLabel string +} + +func describeToolCall(ed *editor.Editor, t Tool, args json.RawMessage, eval editor.PermissionEvaluation) toolStepMeta { + scene := sceneName(ed, projectRoot(ed)) + if scene == "" { + scene = "the scene" + } + if ed != nil && ed.Doc != nil && ed.Doc.Name != "" && scene == "the open scene" { + scene = ed.Doc.Name + } + + var raw map[string]any + _ = json.Unmarshal(args, &raw) + strArg := func(key string) string { + if raw == nil { + return "" + } + s, _ := raw[key].(string) + return strings.TrimSpace(s) + } + + target := strings.TrimSpace(eval.Target) + if target == "" { + target = t.Name + } + runningText := t.Title + if runningText == "" { + runningText = t.Name + } + activity := fmt.Sprintf("Agent is running %s · manual edits stay available", t.Name) + askTitle := fmt.Sprintf("Allow the agent to run %s?", t.Name) + askShort := t.Name + askWhy := fmt.Sprintf("It wants to call %s on %s.", t.Name, scene) + askEffect := "Edits stay unsaved until you keep them." + alwaysLabel := fmt.Sprintf("Always allow %s", t.Name) + + switch t.Name { + case ToolSceneRead: + file := strArg("file") + if file == "" { + file = scene + } + runningText = "Read " + file + activity = fmt.Sprintf("Agent is reading %s · manual edits stay available", file) + askTitle = fmt.Sprintf("Allow the agent to read %s?", file) + askShort = "reading " + file + askWhy = fmt.Sprintf("It wants to read %s.", file) + askEffect = "Nothing is changed." + alwaysLabel = "Always allow reading " + file + case ToolSceneEdit: + file := strArg("file") + if file == "" { + file = scene + } + runningText = "Editing " + file + activity = fmt.Sprintf("Agent is editing %s · manual edits stay available", file) + askTitle = fmt.Sprintf("Allow the agent to edit %s?", file) + askShort = "editing " + file + askWhy = fmt.Sprintf("It wants to edit %s.", file) + askEffect = "Edits stay unsaved until you keep them." + alwaysLabel = "Always allow editing " + file + case ToolSelectionGet: + runningText = "Read selection" + activity = "Agent is checking the selection · manual edits stay available" + askEffect = "Nothing is changed." + case ToolViewportImage: + runningText = "Capture viewport image" + activity = "Agent is inspecting the viewport · manual edits stay available" + askEffect = "Nothing is changed." + case ToolGameCheck: + runningText = "Run game check" + activity = "Agent is running game check · manual edits stay available" + askTitle = "Allow the agent to run game check?" + askShort = "game check" + askWhy = "It wants to check the project for broken references and errors." + askEffect = "Nothing is saved." + alwaysLabel = "Always allow game check" + case ToolGamePlaytest: + runningText = "Play headless" + activity = fmt.Sprintf("Agent is playing %s headless · manual edits stay available", scene) + askTitle = "Allow the agent to run the game?" + askShort = "the playtest" + askWhy = fmt.Sprintf("It wants to play %s headless to verify its changes.", scene) + askEffect = "Nothing is saved." + alwaysLabel = "Always allow headless playtests" + case ToolStatesTest: + runningText = "Test state machine" + activity = "Agent is testing the state machine · manual edits stay available" + askTitle = "Allow the agent to test the state machine?" + askShort = "the state machine test" + askWhy = "It wants to run scripted input against the sprite state machine." + askEffect = "Nothing is saved." + alwaysLabel = "Always allow state machine tests" + default: + if eval.Action == editor.PermissionActionRun { + askEffect = "Nothing is saved." + if target != "" { + askShort = target + askTitle = fmt.Sprintf("Allow the agent to run %s?", target) + alwaysLabel = fmt.Sprintf("Always allow running %s", target) + } + } else if eval.Action != "" && target != "" { + askShort = fmt.Sprintf("%s %s", strings.ToLower(eval.Action.DisplayName()), target) + askTitle = fmt.Sprintf("Allow the agent to %s %s?", strings.ToLower(eval.Action.DisplayName()), target) + askWhy = fmt.Sprintf("It wants to %s %s.", strings.ToLower(eval.Action.DisplayName()), target) + alwaysLabel = fmt.Sprintf("Always allow %s %s", strings.ToLower(eval.Action.DisplayName()), target) + } + } + + permKey := "" + if eval.Action != "" { + permKey = string(eval.Action) + ":" + strings.ToLower(strings.TrimSpace(target)) + } + return toolStepMeta{ + permKey: permKey, + runningText: runningText, + activity: activity, + askTitle: askTitle, + askShort: askShort, + askWhy: askWhy, + askEffect: askEffect, + alwaysLabel: alwaysLabel, + } +} + +func summarizeToolCompletion(t Tool, meta toolStepMeta, res *Result) (text, detail string, objects []string) { + text = meta.runningText + switch t.Name { + case ToolSceneRead: + text = meta.runningText + case ToolSceneEdit: + if res != nil { + if er, ok := res.Structured.(EditResult); ok { + objects = er.Objects + if len(er.Objects) > 0 { + text = fmt.Sprintf("Edited %s", strings.Join(er.Objects, ", ")) + } else { + text = "Edited scene" + } + } + } + case ToolGameCheck: + text = "Ran game check" + if res != nil { + if chk, ok := res.Structured.(Check); ok { + switch len(chk.Problems) { + case 0: + detail = "no problems" + case 1: + detail = "1 problem" + default: + detail = fmt.Sprintf("%d problems", len(chk.Problems)) + } + } + } + case ToolGamePlaytest: + text = "Played headless" + if res != nil { + if pr, ok := res.Structured.(PlaytestRunResult); ok { + if pr.Passed { + detail = "all goals met" + } else { + detail = fmt.Sprintf("%d missed", pr.MissedCount) + } + } + } + } + return text, detail, objects +} + +// invokeHandlerWithCheckpoint wraps mutating MCP tool handlers in a per-turn checkpoint when no +// turn is already open (#1018) and applies post-call privacy checks. +func (s *Server) invokeHandlerWithCheckpoint(ctx context.Context, t Tool, c *Call) (res *Result, err error) { + startedTurn := false + if t.Action == ActionEdit && + t.Name != ToolCheckpointRestore && + t.Name != ToolAgentTurnReply && + t.Name != ToolTasksSubmit && + t.Name != ToolTasksControl && + t.Name != ToolPermissionsDraft && + t.Name != ToolGameDeleteFile { + kind := editor.CheckpointKindTurn + if c.onEditor { + kind = editor.CheckpointKindAutomation + } + _ = c.Editor(ctx, func(ed *editor.Editor) error { + if ed.Project != nil && ed.ProjectPath != "" && ed.ActiveTurnID() == "" { + if _, berr := ed.BeginCheckpointTurnWith(editor.CheckpointOptions{ + Who: editor.HistoryAuthorAgent, + Kind: kind, + Title: checkpointTitleForTool(t), + }); berr == nil { + startedTurn = true + } + } + return nil + }) + } + finished := false + if startedTurn { + defer func() { + cleanupCtx := context.WithoutCancel(ctx) + _ = c.Editor(cleanupCtx, func(ed *editor.Editor) error { + if !finished || err != nil { + _, _ = ed.FinishCheckpointTurnOnError("interrupted") + } else { + _, _ = ed.EndCheckpointTurn("") + } + return nil + }) + }() + } + res, err = t.Handler(ctx, c) + finished = true + if err == nil { + if perr := s.checkPrivacyPost(ctx, t, res, c.onEditor); perr != nil { + res, err = nil, perr + } + } + return res, err +} + +// runManagedToolCall enforces You-only boundaries and permission rules, streams live steps into the Agent panel, +// opens interactive non-blocking permission cards when appropriate, delivers queued follow-ups, and ties tool +// execution to the active request's Stop channel. +func (s *Server) runManagedToolCall(ctx context.Context, t Tool, args json.RawMessage, onEditor bool, session *mcp.ServerSession) (res *Result, managed bool, err error) { + if onEditor { + if err := s.checkPermission(ctx, t, args, true); err != nil { + return nil, false, err + } + if err := s.checkPrivacyPre(ctx, t, args, true); err != nil { + return nil, false, err + } + res, err = s.invokeHandlerWithCheckpoint(ctx, t, &Call{ + Args: args, + s: s, + onEditor: true, + session: session, + taskID: s.sessionTaskID(session), + }) + return res, false, err + } + if t.Name == ToolAgentReportStep { + if err := s.checkPrivacyPre(ctx, t, args, false); err != nil { + return nil, true, err + } + res, err = t.Handler(ctx, &Call{ + Args: args, + s: s, + onEditor: false, + session: session, + taskID: s.sessionTaskID(session), + }) + if err == nil { + if perr := s.checkPrivacyPost(ctx, t, res, false); perr != nil { + res, err = nil, perr + } + } + return res, true, err + } + if err := ctx.Err(); err != nil { + return nil, false, err + } + if t.Action != ActionRead && !t.Action.Valid() { + eval := editor.PermissionEvaluation{ + Decision: editor.PermissionDeny, + RuleIndex: -1, + Reason: fmt.Sprintf("Denied: tool %q has invalid action %q.", t.Name, t.Action), + Link: "Settings › Permissions", + Tool: t.Name, + } + s.recordPermissionDecision(eval) + return nil, false, permissionErrorFromEval(eval, "") + } + + var ( + meta toolStepMeta + eval editor.PermissionEvaluation + evaluated bool + summary string + reqID string + askOnly bool + useCallbackAsk bool + youOnlyErr *YouOnlyError + stopped bool + liveActive bool + stepID string + askID string + askCh <-chan editor.AgentPermissionOutcome + stopCh <-chan struct{} + reDenied bool + ) + + if err := s.Editor(ctx, func(ed *editor.Editor) error { + if ed.AgentStopped() { + stopped = true + return nil + } + liveActive = ed.HasActiveLiveAgentRequest() + interactiveAsk := s.onPermAsk == nil && (liveActive || s.run != nil) + + if t.Action == ActionRead { + if liveActive { + _, stopCh = ed.EnsureAgentRequest("") + meta = describeToolCall(ed, t, args, editor.PermissionEvaluation{}) + stepID = ed.BeginAgentToolStep(t.Name, meta.runningText, meta.activity, nil) + } + return nil + } + + // Enforce You-only trust boundary FIRST before any permission evaluation or live step. + reqs := permissionRequestsForTool(t, args, ed) + if yerr := checkYouOnlyTargets(t, args, reqs, ed); yerr != nil { + youOnlyErr = yerr + return nil + } + // game_delete_file proposes deletions in Review changes (never deletes directly on disk). + if t.Name == ToolGameDeleteFile { + if liveActive { + _, stopCh = ed.EnsureAgentRequest("") + meta = describeToolCall(ed, t, args, editor.PermissionEvaluation{Action: editor.PermissionActionDelete}) + stepID = ed.BeginAgentToolStep(t.Name, meta.runningText, meta.activity, nil) + } + return nil + } + + eval, summary = evaluateAllPermissionRequests(ed, reqs) + evaluated = true + meta = describeToolCall(ed, t, args, eval) + + switch eval.Decision { + case editor.PermissionDeny: + ed.RecordBlockedPermission(eval, summary) + if liveActive { + ed.RecordBlockedAgentStep(t.Name, "Blocked: "+meta.runningText, eval) + } + return nil + + case editor.PermissionAsk: + if !interactiveAsk { + if s.onPermAsk == nil { + req := ed.EnqueuePermissionRequest(eval, summary, nil) + reqID = req.ID + askOnly = true + } else { + useCallbackAsk = true + if liveActive { + _, stopCh = ed.EnsureAgentRequest("") + stepID = ed.BeginAgentToolStep(t.Name, meta.runningText, meta.activity, nil) + } + } + return nil + } + // Check per-request denial memory BEFORE opening a second permission card. + if meta.permKey != "" && ed.IsPermissionDenied(meta.permKey) { + reDenied = true + return nil + } + _, stopCh = ed.EnsureAgentRequest("") + liveActive = true + stepID = ed.BeginAgentToolStep(t.Name, meta.runningText, meta.activity, nil) + ask := editor.AgentPermissionPrompt{ + StepID: stepID, + Title: meta.askTitle, + ShortAction: meta.askShort, + Why: meta.askWhy, + Effect: meta.askEffect, + RuleSource: eval.Reason, + RulePreview: editor.AlwaysRuleForEvaluation(eval).Summary(), + AlwaysLabel: meta.alwaysLabel, + Tool: t.Name, + PermissionKey: meta.permKey, + Evaluation: clonePermissionEval(eval), + } + askCh, stopCh, _ = ed.BeginAgentPermissionAsk(ask) + if openAsk := ed.PendingAgentPermissionAsk(); openAsk != nil { + askID = openAsk.ID + } + return nil + + default: // PermissionAllow + if liveActive { + _, stopCh = ed.EnsureAgentRequest("") + stepID = ed.BeginAgentToolStep(t.Name, meta.runningText, meta.activity, nil) + } + return nil + } + }); err != nil { + return nil, liveActive, err + } + + if stopped { + return nil, true, fmt.Errorf("%s: stopped by the person; leave changes for review", t.Name) + } + if youOnlyErr != nil { + return nil, liveActive, youOnlyErr + } + if evaluated { + s.recordPermissionDecision(eval) + } + if evaluated && eval.Decision == editor.PermissionDeny { + return nil, liveActive, permissionErrorFromEval(eval, "") + } + if askOnly { + return nil, liveActive, permissionErrorFromEval(eval, reqID) + } + if reDenied { + msg := fmt.Sprintf("Permission for %s was already denied in this request. Do not retry it automatically; continue without this step.", t.Name) + return &Result{ + Text: msg, + Structured: PermissionDeniedResult{ + Denied: true, + AlreadyDenied: true, + ContinuedWithoutIt: true, + Message: msg, + }, + }, true, nil + } + + // Non-interactive OnPermissionAsk callback path (#1010). + if useCallbackAsk { + if err := ctx.Err(); err != nil { + return nil, liveActive, err + } + ans, askErr := s.onPermAsk(ctx, clonePermissionEval(eval)) + if askErr != nil { + return nil, liveActive, askErr + } + if err := ctx.Err(); err != nil { + return nil, liveActive, err + } + switch ans { + case PermissionAnswerAllowOnce: + case PermissionAnswerAllowAlways: + if err := s.Editor(ctx, func(ed *editor.Editor) error { + _, err := ed.ApproveAlwaysPermission(eval) + return err + }); err != nil { + return nil, liveActive, err + } + case PermissionAnswerDeny: + deniedEval := clonePermissionEval(eval) + deniedEval.Decision = editor.PermissionDeny + deniedEval.Reason = "Denied by you: " + eval.Reason + return nil, liveActive, permissionErrorFromEval(deniedEval, "") + default: + var pendingID string + if err := s.Editor(ctx, func(ed *editor.Editor) error { + req := ed.EnqueuePermissionRequest(eval, summary, nil) + pendingID = req.ID + return nil + }); err != nil { + return nil, liveActive, err + } + return nil, liveActive, permissionErrorFromEval(eval, pendingID) + } + } + + // Interactive Agent panel permission card wait (runs on MCP goroutine, never blocks UI). + if askCh != nil { + var outcome editor.AgentPermissionOutcome + select { + case outcome = <-askCh: + case <-stopCh: + outcome = editor.PermissionOutcomeStopped + case <-ctx.Done(): + if askID != "" { + s.notifyEditor(func(ed *editor.Editor) { + ed.CancelPendingAgentPermissionAsk(askID) + }) + } + return nil, true, ctx.Err() + case <-s.done: + return nil, true, errors.New("editormcp: the editor's server is closed") + } + switch outcome { + case editor.PermissionOutcomeDeny: + s.attachSafeAllowNow(stepID, t, args, meta, session) + msg := fmt.Sprintf("The person denied %s. Continue without this step and do not retry it unless they send a new request.", meta.askShort) + return &Result{ + Text: msg, + Structured: PermissionDeniedResult{ + Denied: true, + ContinuedWithoutIt: true, + Message: msg, + }, + }, true, nil + case editor.PermissionOutcomeStopped: + return nil, true, fmt.Errorf("%s: stopped by the person; changes so far stay pending for review", t.Name) + } + } + + // Tie tool execution to the request's stop channel so Stop / Mod+. cancels in-flight work immediately. + callCtx, cancel := context.WithCancel(ctx) + defer cancel() + if stopCh != nil { + go func() { + select { + case <-stopCh: + cancel() + case <-callCtx.Done(): + } + }() + } + + if err = s.checkPrivacyPre(callCtx, t, args, false); err == nil { + res, err = s.invokeHandlerWithCheckpoint(callCtx, t, &Call{ + Args: args, + s: s, + onEditor: false, + session: session, + taskID: s.sessionTaskID(session), + }) + } + + if stopCh != nil { + select { + case <-stopCh: + return nil, true, fmt.Errorf("%s: stopped by the person; changes so far stay pending for review", t.Name) + default: + } + } + + if stepID != "" { + var followUps []string + doneText, doneDetail, objs := summarizeToolCompletion(t, meta, res) + if err != nil { + doneDetail = err.Error() + } + _ = s.Editor(context.Background(), func(ed *editor.Editor) error { + ed.FinishAgentToolStep(stepID, doneText, doneDetail, objs, err != nil) + followUps = ed.DrainAgentFollowUps() + return nil + }) + if err == nil && len(followUps) > 0 && res != nil { + note := "\n[Additional instructions added to this request: " + strings.Join(followUps, " | ") + "]" + res.Text += note + } + } + + return res, liveActive || stepID != "", err +} + +// attachSafeAllowNow binds an on-demand "Allow now" callback on a denied step that: +// - never leaks goroutines past Server.Close (tracked by s.wg and cancelled on s.done), +// - refuses to run after the editor switches projects (projectGen check), +// - re-verifies You-only trust boundaries before invoking t.Handler. +func (s *Server) attachSafeAllowNow(stepID string, t Tool, args json.RawMessage, meta toolStepMeta, session *mcp.ServerSession) { + if stepID == "" { + return + } + argsCopy := append(json.RawMessage(nil), args...) + s.mu.Lock() + capturedGen := s.projectGen + s.mu.Unlock() + _ = s.Editor(context.Background(), func(ed *editor.Editor) error { + ed.AttachDeniedStepAllowNow(stepID, func() { + s.mu.Lock() + if s.closed || s.projectGen != capturedGen { + s.mu.Unlock() + return + } + s.wg.Add(1) + s.mu.Unlock() + + go func() { + defer s.wg.Done() + runCtx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { + select { + case <-s.done: + cancel() + case <-runCtx.Done(): + } + }() + + // Defense in depth: re-check You-only boundaries before executing on demand. + var yerr *YouOnlyError + if err := s.Editor(runCtx, func(ed *editor.Editor) error { + reqs := permissionRequestsForTool(t, argsCopy, ed) + yerr = checkYouOnlyTargets(t, argsCopy, reqs, ed) + return nil + }); err != nil { + return + } + var ( + res *Result + runErr error + ) + if yerr != nil { + runErr = yerr + } else if !s.isToolEnabled(t.Name) { + runErr = toolDisabledError(t.Name) + } else if perr := s.checkPrivacyPre(runCtx, t, argsCopy, false); perr != nil { + runErr = perr + } else { + res, runErr = s.invokeHandlerWithCheckpoint(runCtx, t, &Call{ + Args: argsCopy, + s: s, + onEditor: false, + session: session, + taskID: s.sessionTaskID(session), + }) + } + doneText, doneDetail, objs := summarizeToolCompletion(t, meta, res) + if runErr != nil { + doneDetail = runErr.Error() + } + _ = s.Editor(context.Background(), func(ed *editor.Editor) error { + ed.FinishAgentToolStep(stepID, doneText, doneDetail, objs, runErr != nil) + return nil + }) + }() + }) + return nil + }) +} diff --git a/packages/game/editor/editormcp/agent_live_steps_test.go b/packages/game/editor/editormcp/agent_live_steps_test.go new file mode 100644 index 000000000..736b1f398 --- /dev/null +++ b/packages/game/editor/editormcp/agent_live_steps_test.go @@ -0,0 +1,461 @@ +package editormcp_test + +import ( + "context" + "os" + "path/filepath" + "slices" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/editor/editormcp" + "github.com/nsgo-dev/game/packages/game/playtest" +) + +// editorLoop serializes all Editor calls onto a single goroutine, matching how a live UI runs +// editormcp.Server with Options.Run = cx.Post, so concurrent MCP calls are 100% race-free under -race. +type editorLoop struct { + ch chan func() + stop chan struct{} + done chan struct{} +} + +func newEditorLoop(t *testing.T) *editorLoop { + t.Helper() + l := &editorLoop{ + ch: make(chan func(), 64), + stop: make(chan struct{}), + done: make(chan struct{}), + } + go func() { + defer close(l.done) + for { + select { + case fn := <-l.ch: + fn() + case <-l.stop: + return + } + } + }() + t.Cleanup(func() { + close(l.stop) + <-l.done + }) + return l +} + +func (l *editorLoop) Post(fn func()) { + select { + case l.ch <- fn: + case <-l.stop: + } +} + +func (l *editorLoop) Do(fn func()) { + done := make(chan struct{}) + l.Post(func() { + defer close(done) + fn() + }) + select { + case <-done: + case <-l.stop: + } +} + +func startTestMCPServer(t *testing.T, ed *editor.Editor, opts editormcp.Options) (*editorLoop, *editormcp.Server) { + t.Helper() + loop := newEditorLoop(t) + opts.Run = loop.Post + var s *editormcp.Server + loop.Do(func() { + s = editormcp.New(ed, opts) + }) + t.Cleanup(func() { + loop.Do(func() { + _ = s.Close() + }) + }) + return loop, s +} + +func writePlaytestFixture(t *testing.T, dir string) { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, playtest.FileName), []byte(fixturePlaytestYAML), 0o644); err != nil { + t.Fatalf("write playtest.yaml: %v", err) + } +} + +func fakePlaytestRunner(_ context.Context, req editormcp.PlaytestRunRequest) (*playtest.Report, error) { + return &playtest.Report{ + Version: playtest.ReportVersion, + Scope: req.Config.Scope, + Bot: req.Config.Bot, + Rate: 60, + Speed: 1, + SeedCount: 1, + Passed: true, + Metrics: []playtest.MetricReport{ + { + Name: "finished", + Label: "Finished", + Aggregate: playtest.AggCount, + Value: 4, + Goal: &playtest.Goal{Summary: "clear the room", Source: "brief.yaml", Min: playtest.Float64(3)}, + Status: playtest.StatusMet, + }, + }, + Runs: []playtest.RunReport{ + {Index: 1, Seed: 1, Outcome: playtest.OutcomeFinished, Steps: 60, DurationSeconds: 1}, + }, + }, nil +} + +func waitForPendingAsk(t *testing.T, loop *editorLoop, ed *editor.Editor) *editor.AgentPermissionPrompt { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + var ask *editor.AgentPermissionPrompt + loop.Do(func() { + ask = ed.AgentSession().PendingAsk + }) + if ask != nil { + return ask + } + time.Sleep(5 * time.Millisecond) + } + t.Fatal("timed out waiting for permission card to appear") + return nil +} + +// Acceptance 1: A scripted MCP client drives a request: steps appear in order, an Ask shows a card, +// Allow once runs the tool, Deny skips it, shows "You denied …" with Allow now, and the agent's next +// identical call in the same request proceeds without retrying/showing a card; a new request may ask again. +func TestScriptedMCPClientLiveStepsAskAllowOnceAndDeny(t *testing.T) { + f := openFixture(t) + writePlaytestFixture(t, f.dir) + if err := f.ed.SelectPermissionProfile(editor.PermissionProfileCautious); err != nil { + t.Fatalf("SelectPermissionProfile: %v", err) + } + + var playtestRuns atomic.Int32 + loop, s := startTestMCPServer(t, f.ed, editormcp.Options{ + RunPlaytest: func(ctx context.Context, req editormcp.PlaytestRunRequest) (*playtest.Report, error) { + playtestRuns.Add(1) + return fakePlaytestRunner(ctx, req) + }, + }) + cs := connect(t, s, nil) + + loop.Do(func() { + f.ed.StartAgentRequest("Put a slime on the floor and check it.") + }) + + // Step 1: Read (allowed even under Cautious). + mustOK(t, call(t, cs, editormcp.ToolSceneRead, map[string]any{})) + + // Step 2: Agent reports a custom step with touched objects. + repRes := call(t, cs, editormcp.ToolAgentReportStep, map[string]any{ + "text": "Placed 3 coins toward the door", + "objects": []string{"hero"}, + }) + mustOK(t, repRes) + var repOut editormcp.AgentReportStepResult + structured(t, repRes, &repOut) + if repOut.Text != "Placed 3 coins toward the door" || !slices.Equal(repOut.Objects, []string{"hero"}) { + t.Fatalf("agent_report_step structured = %+v", repOut) + } + + // Step 3: game_check under Cautious shows Ask card -> Allow once runs it. + checkDone := make(chan *mcp.CallToolResult, 1) + go func() { + checkDone <- call(t, cs, editormcp.ToolGameCheck, map[string]any{}) + }() + ask := waitForPendingAsk(t, loop, f.ed) + if ask.Tool != editormcp.ToolGameCheck || !strings.Contains(ask.Effect, "Nothing is saved") { + t.Fatalf("unexpected game_check ask: %+v", ask) + } + var allowed bool + loop.Do(func() { allowed = f.ed.AllowPermissionOnce() }) + if !allowed { + t.Fatal("AllowPermissionOnce returned false") + } + mustOK(t, <-checkDone) + + // Step 4: game_playtest under Cautious shows Ask card -> Deny skips it. + ptDone := make(chan *mcp.CallToolResult, 1) + go func() { + ptDone <- call(t, cs, editormcp.ToolGamePlaytest, map[string]any{}) + }() + ask2 := waitForPendingAsk(t, loop, f.ed) + if ask2.Title != "Allow the agent to run the game?" || !strings.Contains(ask2.RuleSource, "Cautious") { + t.Fatalf("unexpected playtest ask: %+v", ask2) + } + var denied bool + loop.Do(func() { denied = f.ed.DenyPermission() }) + if !denied { + t.Fatal("DenyPermission returned false") + } + ptRes := <-ptDone + if ptRes.IsError { + t.Fatalf("denial should return a non-fatal structured response so the agent continues: %s", text(ptRes)) + } + var denyInfo editormcp.PermissionDeniedResult + structured(t, ptRes, &denyInfo) + if !denyInfo.Denied || !denyInfo.ContinuedWithoutIt { + t.Fatalf("deny structured = %+v", denyInfo) + } + if playtestRuns.Load() != 0 { + t.Fatalf("denied playtest still ran %d times", playtestRuns.Load()) + } + + // Verify step rows appear in order and step 3 shows "You denied the playtest" with CanAllowNow=true. + var snap editor.AgentSessionSnapshot + loop.Do(func() { snap = f.ed.AgentSession() }) + if len(snap.Steps) != 4 { + t.Fatalf("expected 4 steps in order, got %d: %+v", len(snap.Steps), snap.Steps) + } + if snap.Steps[0].ToolName != editormcp.ToolSceneRead || snap.Steps[0].Status != editor.AgentStepDone { + t.Fatalf("step 0 = %+v", snap.Steps[0]) + } + if snap.Steps[1].ToolName != editormcp.ToolAgentReportStep || snap.Steps[1].Title != "Placed 3 coins toward the door" { + t.Fatalf("step 1 = %+v", snap.Steps[1]) + } + if snap.Steps[2].ToolName != editormcp.ToolGameCheck || snap.Steps[2].Status != editor.AgentStepDone { + t.Fatalf("step 2 = %+v", snap.Steps[2]) + } + if snap.Steps[3].Status != editor.AgentStepDenied || !strings.Contains(snap.Steps[3].Title, "You denied the playtest") || !snap.Steps[3].CanAllowNow { + t.Fatalf("step 3 = %+v, want denied with Allow now", snap.Steps[3]) + } + + // Calling game_playtest AGAIN in the same request MUST NOT show a card and MUST NOT run it! + ptRetry := call(t, cs, editormcp.ToolGamePlaytest, map[string]any{}) + var retryInfo editormcp.PermissionDeniedResult + structured(t, ptRetry, &retryInfo) + if !retryInfo.Denied || !retryInfo.AlreadyDenied { + t.Fatalf("retry after denial = %+v, want alreadyDenied=true", retryInfo) + } + loop.Do(func() { + if f.ed.AgentSession().PendingAsk != nil { + t.Error("retried denied tool opened a second permission card in the same request") + } + }) + + // Agent's next call proceeds cleanly without being blocked by the earlier denial. + mustOK(t, call(t, cs, editormcp.ToolSelectionGet, map[string]any{})) + + // Completing the request records "Not playtested" in the summary. + var doneSnap editor.AgentSessionSnapshot + loop.Do(func() { + f.ed.CompleteAgentRequest("") + doneSnap = f.ed.AgentSession() + }) + if doneSnap.Review == nil || !slices.Contains(doneSnap.Review.NotChecked, "Not playtested") { + t.Fatalf("summary review after denial = %+v, want Not playtested", doneSnap.Review) + } + + // Clicking "Allow now" on the denied step runs the playtest on demand and clears "Not playtested". + deniedStepID := snap.Steps[3].ID + loop.Do(func() { + if !f.ed.AllowDeniedStepNow(deniedStepID) { + t.Errorf("AllowDeniedStepNow(%q) returned false", deniedStepID) + } + }) + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) && playtestRuns.Load() < 1 { + time.Sleep(5 * time.Millisecond) + } + if playtestRuns.Load() != 1 { + t.Fatalf("Allow now playtest runs = %d, want 1", playtestRuns.Load()) + } + + // A NEW request clears per-request denials so the agent MAY ask again. + loop.Do(func() { + f.ed.StartAgentRequest("Now run the playtest.") + }) + newReqDone := make(chan *mcp.CallToolResult, 1) + go func() { + newReqDone <- call(t, cs, editormcp.ToolGamePlaytest, map[string]any{}) + }() + waitForPendingAsk(t, loop, f.ed) + loop.Do(func() { f.ed.AllowPermissionOnce() }) + mustOK(t, <-newReqDone) + if playtestRuns.Load() != 2 { + t.Fatalf("expected playtest to run twice total, got %d", playtestRuns.Load()) + } +} + +// Acceptance 2: Always adds a rule to permissions.yaml and the next identical call runs without a card. +func TestAlwaysRulePersistsAndSkipsNextCard(t *testing.T) { + f := openFixture(t) + writePlaytestFixture(t, f.dir) + if err := f.ed.SelectPermissionProfile(editor.PermissionProfileCautious); err != nil { + t.Fatalf("SelectPermissionProfile: %v", err) + } + + var runs atomic.Int32 + loop, s := startTestMCPServer(t, f.ed, editormcp.Options{ + RunPlaytest: func(ctx context.Context, req editormcp.PlaytestRunRequest) (*playtest.Report, error) { + runs.Add(1) + return fakePlaytestRunner(ctx, req) + }, + }) + cs := connect(t, s, nil) + + loop.Do(func() { + f.ed.StartAgentRequest("Playtest level.") + }) + firstDone := make(chan *mcp.CallToolResult, 1) + go func() { + firstDone <- call(t, cs, editormcp.ToolGamePlaytest, map[string]any{}) + }() + waitForPendingAsk(t, loop, f.ed) + var approved bool + loop.Do(func() { approved = f.ed.AllowPermissionAlways() }) + if !approved { + t.Fatal("AllowPermissionAlways returned false") + } + mustOK(t, <-firstDone) + + // Verify permissions.yaml on disk holds the new Allow rule for playtests. + permPath := filepath.Join(f.dir, editor.PermissionsFileName) + data, err := os.ReadFile(permPath) + if err != nil { + t.Fatalf("read permissions.yaml: %v", err) + } + loaded, err := editor.ParsePermissions(data) + if err != nil { + t.Fatalf("ParsePermissions: %v", err) + } + eval := loaded.Evaluate(editor.PermissionRequest{ + Tool: editormcp.ToolGamePlaytest, + Action: editor.PermissionActionRun, + Target: editor.PermissionRunPlaytests, + }) + if eval.Decision != editor.PermissionAllow { + t.Fatalf("persisted permissions.yaml eval for playtests = %+v, want allow", eval) + } + + // Next identical call runs immediately WITHOUT showing any permission card! + mustOK(t, call(t, cs, editormcp.ToolGamePlaytest, map[string]any{})) + loop.Do(func() { + if f.ed.AgentSession().PendingAsk != nil { + t.Error("second identical call unexpectedly showed a permission card") + } + }) + if runs.Load() != 2 { + t.Fatalf("playtest runs = %d, want 2", runs.Load()) + } + + // Undo reverts the persisted rule so permissions.yaml asks again. + var undoErr error + loop.Do(func() { + toast, ok := f.ed.PermissionToast() + if !ok || toast.Message == "" { + t.Errorf("expected PermissionToast after Always, got %+v (%v)", toast, ok) + } + undoErr = f.ed.UndoPermissionToast() + }) + if undoErr != nil { + t.Fatalf("UndoPermissionToast: %v", undoErr) + } + var afterEval editor.PermissionEvaluation + loop.Do(func() { + afterEval = f.ed.EvaluatePermission(editor.PermissionRequest{ + Tool: editormcp.ToolGamePlaytest, + Action: editor.PermissionActionRun, + Target: editor.PermissionRunPlaytests, + }) + }) + if afterEval.Decision != editor.PermissionAsk { + t.Fatalf("after Undo, playtest eval = %+v, want ask", afterEval) + } +} + +func TestAddToRequestDeliversFollowUpsAndStopCancelsAsk(t *testing.T) { + f := openFixture(t) + writePlaytestFixture(t, f.dir) + if err := f.ed.SelectPermissionProfile(editor.PermissionProfileCautious); err != nil { + t.Fatalf("SelectPermissionProfile: %v", err) + } + loop, s := startTestMCPServer(t, f.ed, editormcp.Options{ + RunPlaytest: fakePlaytestRunner, + }) + cs := connect(t, s, nil) + + loop.Do(func() { + f.ed.StartAgentRequest("Inspect and edit.") + if err := f.ed.AddToAgentRequest("Also make the coins gold."); err != nil { + t.Errorf("AddToAgentRequest: %v", err) + } + }) + res := call(t, cs, editormcp.ToolAgentReportStep, map[string]any{"text": "Checked scene"}) + mustOK(t, res) + var out editormcp.AgentReportStepResult + structured(t, res, &out) + if !slices.Equal(out.FollowUps, []string{"Also make the coins gold."}) { + t.Fatalf("followUps = %v, want [Also make the coins gold.]", out.FollowUps) + } + + // Trigger a waiting Ask card and interrupt it with StopAgent(). + ptDone := make(chan *mcp.CallToolResult, 1) + go func() { + ptDone <- call(t, cs, editormcp.ToolGamePlaytest, map[string]any{}) + }() + waitForPendingAsk(t, loop, f.ed) + var stopped bool + loop.Do(func() { stopped = f.ed.StopAgent() }) + if !stopped { + t.Fatal("StopAgent returned false") + } + stoppedRes := <-ptDone + if !stoppedRes.IsError || !strings.Contains(text(stoppedRes), "stopped") { + t.Fatalf("expected stopped error after StopAgent, got isError=%v text=%q", stoppedRes.IsError, text(stoppedRes)) + } + var snap editor.AgentSessionSnapshot + loop.Do(func() { snap = f.ed.AgentSession() }) + if !snap.Stopped || snap.Review == nil || !snap.Review.Stopped || snap.Review.StepsDone != 1 { + t.Fatalf("session after Stop = %+v", snap) + } +} + +func TestLiveRequestStillEnforcesYouOnlyAndValidatesReportStep(t *testing.T) { + f := openFixture(t) + loop, s := startTestMCPServer(t, f.ed, editormcp.Options{}) + if err := s.AddTool(editormcp.Tool{ + Name: "file_edit_test", + Action: editormcp.ActionEdit, + Handler: func(ctx context.Context, c *editormcp.Call) (*editormcp.Result, error) { + return &editormcp.Result{Text: "should not run"}, nil + }, + }); err != nil { + t.Fatalf("AddTool: %v", err) + } + cs := connect(t, s, nil) + + loop.Do(func() { + f.ed.StartAgentRequest("Attempt restricted edits.") + }) + + // You-only boundary (permissions.yaml) must STILL be refused even during an active live request. + res := call(t, cs, "file_edit_test", map[string]any{"file": editor.PermissionsFileName}) + if !res.IsError || !strings.Contains(strings.ToLower(text(res)), "you only") { + t.Fatalf("expected You-only refusal on permissions.yaml, got err=%v text=%q", res.IsError, text(res)) + } + + // agent_report_step rejects NUL bytes and oversized text. + nulRes := call(t, cs, editormcp.ToolAgentReportStep, map[string]any{"text": "bad\x00step"}) + if !nulRes.IsError { + t.Fatal("agent_report_step unexpectedly accepted NUL byte") + } + bigRes := call(t, cs, editormcp.ToolAgentReportStep, map[string]any{"text": strings.Repeat("a", 5000)}) + if !bigRes.IsError { + t.Fatal("agent_report_step unexpectedly accepted oversized text") + } +} diff --git a/packages/game/editor/editormcp/example_test.go b/packages/game/editor/editormcp/example_test.go index 481a34784..d0277fd1f 100644 --- a/packages/game/editor/editormcp/example_test.go +++ b/packages/game/editor/editormcp/example_test.go @@ -82,6 +82,7 @@ func ExampleServer_AddTool() { } // Output: // + // agent_report_step read // agent_turn_get read // agent_turn_reply edit // brief_edit edit diff --git a/packages/game/editor/editormcp/proxy_test.go b/packages/game/editor/editormcp/proxy_test.go index 82ea4a2b1..12065cd68 100644 --- a/packages/game/editor/editormcp/proxy_test.go +++ b/packages/game/editor/editormcp/proxy_test.go @@ -62,7 +62,7 @@ func TestProxyFindsTheEditor(t *testing.T) { } }}, "") - if names := listNames(t, cs); !slices.Equal(names, []string{"agent_turn_get", "agent_turn_reply", "brief_edit", "checkpoint_list", "checkpoint_restore", "cutscene_scrub", "cutscene_write", "datatable_review_checks", "datatable_review_propose", "datatable_review_status", "file_edit", "game_check", "game_playtest", "history_list", "merge_abort", "merge_finish", "merge_resolve", "merge_status", "object_copy_yaml", "object_duplicate", "object_find_usages", "object_group", "object_locate_yaml", "object_move_under", "object_paste_yaml", "object_select_same_prefab", "object_set_field", "object_visibility", "permissions_draft", "play_frozen_context", "play_replay_step", "playtest_define", "playtest_report", "problem_propose_fix", "project_context", "refactor_rename", "refs_find", "release_notes_draft", "release_review_uploads", "review_notes_get", "review_redo", "review_status", "rules_edit", "scene_edit", "scene_read", "selection_get", "sketch_read", "sketch_reading", "states_test", "states_write", "tasks_control", "tasks_list", "tasks_submit", "tile_autotile", "tile_erase", "tile_paint", "tile_query", "tile_review_keep", "tile_review_restore_region", "tile_review_revert_all", "tile_review_revert_region", "tile_review_status", "tileset_edit", "tileset_read", "turn_end", "turn_start", "turn_status", "viewport_image"}) { + if names := listNames(t, cs); !slices.Equal(names, []string{"agent_report_step", "agent_turn_get", "agent_turn_reply", "brief_edit", "checkpoint_list", "checkpoint_restore", "cutscene_scrub", "cutscene_write", "datatable_review_checks", "datatable_review_propose", "datatable_review_status", "file_edit", "game_check", "game_playtest", "history_list", "merge_abort", "merge_finish", "merge_resolve", "merge_status", "object_copy_yaml", "object_duplicate", "object_find_usages", "object_group", "object_locate_yaml", "object_move_under", "object_paste_yaml", "object_select_same_prefab", "object_set_field", "object_visibility", "permissions_draft", "play_frozen_context", "play_replay_step", "playtest_define", "playtest_report", "problem_propose_fix", "project_context", "refactor_rename", "refs_find", "release_notes_draft", "release_review_uploads", "review_notes_get", "review_redo", "review_status", "rules_edit", "scene_edit", "scene_read", "selection_get", "sketch_read", "sketch_reading", "states_test", "states_write", "tasks_control", "tasks_list", "tasks_submit", "tile_autotile", "tile_erase", "tile_paint", "tile_query", "tile_review_keep", "tile_review_restore_region", "tile_review_revert_all", "tile_review_revert_region", "tile_review_status", "tileset_edit", "tileset_read", "turn_end", "turn_start", "turn_status", "viewport_image"}) { t.Fatalf("tools without an editor: %v", names) } res := call(t, cs, editormcp.ToolSceneRead, nil) diff --git a/packages/game/editor/editormcp/server.go b/packages/game/editor/editormcp/server.go index 55b1c9a92..bc66504c9 100644 --- a/packages/game/editor/editormcp/server.go +++ b/packages/game/editor/editormcp/server.go @@ -854,8 +854,8 @@ func (s *Server) handler(t Tool) mcp.ToolHandler { ed.PrepareExternalAgentBaseline() }) } - res, err := s.callWithSession(ctx, t, rawArgs, false, sess) - if !isTaskSession { + res, managed, err := s.callWithSessionManaged(ctx, t, rawArgs, false, sess) + if !isTaskSession && !managed { clientName := "" if sess != nil { s.mu.Lock() @@ -880,6 +880,25 @@ func (s *Server) handler(t Tool) mcp.ToolHandler { IsError: err != nil, }) }) + } else if !isTaskSession && managed && t.Name != ToolAgentReportStep { + stepTitle := t.Title + if stepTitle == "" { + stepTitle = t.Name + } + callSummary := formatMCPCallSummary(t.Name, rawArgs, stepTitle) + errText := formatMCPErrorSummary(err) + s.notifyEditor(func(ed *editor.Editor) { + if ed.AgentStopped() || !ed.HasActiveLiveAgentRequest() { + return + } + ed.RecordAgentToolCall(editor.AgentToolCallRecord{ + ToolName: t.Name, + StepTitle: stepTitle, + CallSummary: callSummary, + ErrorText: errText, + IsError: err != nil, + }) + }) } return sdkResult(res, err), nil } @@ -962,10 +981,11 @@ func formatMCPErrorSummary(err error) string { // call runs t with args after checking the editor's permission rules, recovering a panic as an error; onEditor says the caller is on the editor's goroutine. func (s *Server) call(ctx context.Context, t Tool, args json.RawMessage, onEditor bool) (res *Result, err error) { - return s.callWithSession(ctx, t, args, onEditor, nil) + res, _, err = s.callWithSessionManaged(ctx, t, args, onEditor, nil) + return res, err } -func (s *Server) callWithSession(ctx context.Context, t Tool, args json.RawMessage, onEditor bool, session *mcp.ServerSession) (res *Result, err error) { +func (s *Server) callWithSessionManaged(ctx context.Context, t Tool, args json.RawMessage, onEditor bool, session *mcp.ServerSession) (res *Result, managed bool, err error) { if len(args) == 0 || string(args) == "null" { args = json.RawMessage(`{}`) } @@ -975,67 +995,9 @@ func (s *Server) callWithSession(ctx context.Context, t Tool, args json.RawMessa } }() if !s.isToolEnabled(t.Name) { - return nil, toolDisabledError(t.Name) - } - if err := s.checkPermission(ctx, t, args, onEditor); err != nil { - return nil, err - } - if err = s.checkPrivacyPre(ctx, t, args, onEditor); err != nil { - return nil, err - } - c := &Call{ - Args: args, - s: s, - onEditor: onEditor, - session: session, - taskID: s.sessionTaskID(session), - } - startedTurn := false - if t.Action == ActionEdit && - t.Name != ToolCheckpointRestore && - t.Name != ToolAgentTurnReply && - t.Name != ToolTasksSubmit && - t.Name != ToolTasksControl && - t.Name != ToolPermissionsDraft && - t.Name != ToolGameDeleteFile { - kind := editor.CheckpointKindTurn - if onEditor { - kind = editor.CheckpointKindAutomation - } - _ = c.Editor(ctx, func(ed *editor.Editor) error { - if ed.Project != nil && ed.ProjectPath != "" && ed.ActiveTurnID() == "" { - if _, berr := ed.BeginCheckpointTurnWith(editor.CheckpointOptions{ - Who: editor.HistoryAuthorAgent, - Kind: kind, - Title: checkpointTitleForTool(t), - }); berr == nil { - startedTurn = true - } - } - return nil - }) - } - finished := false - if startedTurn { - defer func() { - cleanupCtx := context.WithoutCancel(ctx) - _ = c.Editor(cleanupCtx, func(ed *editor.Editor) error { - if !finished || err != nil { - _, _ = ed.FinishCheckpointTurnOnError("interrupted") - } else { - _, _ = ed.EndCheckpointTurn("") - } - return nil - }) - }() - } - res, err = t.Handler(ctx, c) - finished = true - if err == nil { - if perr := s.checkPrivacyPost(ctx, t, res, onEditor); perr != nil { - res, err = nil, perr - } + return nil, false, toolDisabledError(t.Name) } + res, managed, err = s.runManagedToolCall(ctx, t, args, onEditor, session) if warn := s.saveFailureWarning(ctx, onEditor); warn != nil { if err != nil { err = &saveWarningError{err: err, warning: warn} @@ -1054,7 +1016,7 @@ func (s *Server) callWithSession(ctx context.Context, t Tool, args json.RawMessa } } } - return res, err + return res, managed, err } func (s *Server) saveFailureWarning(ctx context.Context, onEditor bool) *SaveWarning { diff --git a/packages/game/editor/editormcp/server_test.go b/packages/game/editor/editormcp/server_test.go index c9e883fe0..88e8997f2 100644 --- a/packages/game/editor/editormcp/server_test.go +++ b/packages/game/editor/editormcp/server_test.go @@ -39,7 +39,7 @@ func TestServerListsToolsAndResources(t *testing.T) { } } slices.Sort(names) - want := []string{"agent_turn_get", "agent_turn_reply", "brief_edit", "checkpoint_list", "checkpoint_restore", "cutscene_scrub", "cutscene_write", "datatable_review_checks", "datatable_review_propose", "datatable_review_status", "file_edit", "game_check", "game_playtest", "history_list", "merge_abort", "merge_finish", "merge_resolve", "merge_status", "object_copy_yaml", "object_duplicate", "object_find_usages", "object_group", "object_locate_yaml", "object_move_under", "object_paste_yaml", "object_select_same_prefab", "object_set_field", "object_visibility", "permissions_draft", "play_frozen_context", "play_replay_step", "playtest_define", "playtest_report", "problem_propose_fix", "project_context", "refactor_rename", "refs_find", "release_notes_draft", "release_review_uploads", "review_notes_get", "review_redo", "review_status", "rules_edit", "scene_edit", "scene_read", "selection_get", "sketch_read", "sketch_reading", "states_test", "states_write", "tasks_control", "tasks_list", "tasks_submit", "tile_autotile", "tile_erase", "tile_paint", "tile_query", "tile_review_keep", "tile_review_restore_region", "tile_review_revert_all", "tile_review_revert_region", "tile_review_status", "tileset_edit", "tileset_read", "turn_end", "turn_start", "turn_status", "viewport_image"} + want := []string{"agent_report_step", "agent_turn_get", "agent_turn_reply", "brief_edit", "checkpoint_list", "checkpoint_restore", "cutscene_scrub", "cutscene_write", "datatable_review_checks", "datatable_review_propose", "datatable_review_status", "file_edit", "game_check", "game_playtest", "history_list", "merge_abort", "merge_finish", "merge_resolve", "merge_status", "object_copy_yaml", "object_duplicate", "object_find_usages", "object_group", "object_locate_yaml", "object_move_under", "object_paste_yaml", "object_select_same_prefab", "object_set_field", "object_visibility", "permissions_draft", "play_frozen_context", "play_replay_step", "playtest_define", "playtest_report", "problem_propose_fix", "project_context", "refactor_rename", "refs_find", "release_notes_draft", "release_review_uploads", "review_notes_get", "review_redo", "review_status", "rules_edit", "scene_edit", "scene_read", "selection_get", "sketch_read", "sketch_reading", "states_test", "states_write", "tasks_control", "tasks_list", "tasks_submit", "tile_autotile", "tile_erase", "tile_paint", "tile_query", "tile_review_keep", "tile_review_restore_region", "tile_review_revert_all", "tile_review_revert_region", "tile_review_status", "tileset_edit", "tileset_read", "turn_end", "turn_start", "turn_status", "viewport_image"} if !slices.Equal(names, want) { t.Fatalf("tools = %v, want %v", names, want) } diff --git a/packages/game/editor/locales/en.yaml b/packages/game/editor/locales/en.yaml index 07f8f2322..d0aad334c 100644 --- a/packages/game/editor/locales/en.yaml +++ b/packages/game/editor/locales/en.yaml @@ -2,6 +2,9 @@ version: 1 locale: en strings: + agent.addPlaceholder: Add to this request… + agent.allowNow: Allow now + agent.alwaysAddsRule: Always adds a rule agent.automationBadge: Automation agent.automationCheckpoint: Checkpoint taken before start · {id} agent.automationDismiss: Dismiss @@ -18,6 +21,7 @@ strings: agent.composerLabel: Ask the agent agent.composerPlaceholder: Describe a change… e.g. make the knight jump higher agent.connectShort: Connect + agent.footerHint: stops the agent from anywhere · Esc never stops the agent agent.headerPendingReview: Agent · {count} pending changes agent.headerWaiting: Waiting for you agent.headerWaitingDetail: Waiting for you · {detail} @@ -63,6 +67,7 @@ strings: agent.ref.sentOnce: Sent with this request only agent.ref.undo: Undo agent.revert: Revert + agent.review: Review agent.status.disconnected: Disconnected agent.status.limitShort: Limit agent.status.offline: Offline @@ -71,6 +76,8 @@ strings: agent.status.workingShort: Working agent.statusKept: Kept agent turn agent.statusReverted: Reverted agent turn + agent.stop: Stop + agent.stoppedToast: Agent stopped agent.tab: Agent agent.treeChanged: MOD agent.treeNew: NEW diff --git a/packages/game/editor/locales/zh.yaml b/packages/game/editor/locales/zh.yaml index 2afc724c2..2af03e44e 100644 --- a/packages/game/editor/locales/zh.yaml +++ b/packages/game/editor/locales/zh.yaml @@ -2,6 +2,9 @@ version: 1 locale: zh strings: + agent.addPlaceholder: 补充到此请求… + agent.allowNow: 立即允许 + agent.alwaysAddsRule: 「始终允许」会添加一条规则 agent.automationBadge: 自动化 agent.automationCheckpoint: 开始前已创建检查点 · {id} agent.automationDismiss: 忽略 @@ -18,6 +21,7 @@ strings: agent.composerLabel: 向智能体提问 agent.composerPlaceholder: 描述你想做的修改… 例如让骑士跳得更高 agent.connectShort: 连接 + agent.footerHint: 可随时停止代理 · Esc 不会停止代理 agent.headerPendingReview: 智能体 · {count} 项待审更改 agent.headerWaiting: 等待你确认 agent.headerWaitingDetail: 等待你确认 · {detail} @@ -63,6 +67,7 @@ strings: agent.ref.sentOnce: 仅随本次请求发送 agent.ref.undo: 撤销 agent.revert: 还原 + agent.review: 审查 agent.status.disconnected: 已断开 agent.status.limitShort: 已达上限 agent.status.offline: 离线 @@ -71,6 +76,8 @@ strings: agent.status.workingShort: 处理中 agent.statusKept: 已保留智能体更改 agent.statusReverted: 已还原智能体更改 + agent.stop: 停止 + agent.stoppedToast: 代理已停止 agent.tab: 智能体 agent.treeChanged: 改 agent.treeNew: NEW diff --git a/packages/game/editor/main_layout_ui.go b/packages/game/editor/main_layout_ui.go index a56ea8202..8167bbdef 100644 --- a/packages/game/editor/main_layout_ui.go +++ b/packages/game/editor/main_layout_ui.go @@ -2262,6 +2262,7 @@ func mainStatusBarView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) cor saveStatusBarView(cx, ed, rev), tasksStatusIndicatorView(cx, ed, rev), remoteStatusView(cx, ed, rev), + agentStatusBarActivityView(cx, ed, rev), core.Show{ When: func() bool { _ = rev.Get() diff --git a/packages/game/editor/permissions_ui.go b/packages/game/editor/permissions_ui.go index 53f37e304..d64e77630 100644 --- a/packages/game/editor/permissions_ui.go +++ b/packages/game/editor/permissions_ui.go @@ -1647,7 +1647,7 @@ func PermissionsWorkspaceOverlayView(cx *core.Scope, ed *Editor, rev *core.Signa } p := ed.SpecPalette(cx) items := make([]core.Node, 0, 2) - if pending := ed.PendingPermissionRequests(); len(pending) > 0 { + if pending := ed.PendingPermissionRequests(); len(pending) > 0 && ed.PendingAgentPermissionAsk() == nil { items = append(items, permissionsAskCardNode(p, ed, pending[0], "workspace-perm-ask")) } if blocked := ed.BlockedPermissions(); len(blocked) > 0 { diff --git a/packages/game/editor/state.go b/packages/game/editor/state.go index 3ff42f2bc..2144cd962 100644 --- a/packages/game/editor/state.go +++ b/packages/game/editor/state.go @@ -550,6 +550,10 @@ type Editor struct { OnAskAgent func(AgentPromptRequest) // OnStopAgent is invoked by Mod+. (even while a modal dialog is open, per Spec rule 04) to stop an active agent run without disturbing reviewable changes. OnStopAgent func() + // OnStartAgentRequest, when set, is called when the author starts a new agent request via StartAgentRequest. + OnStartAgentRequest func(prompt string) + // OnAddToAgentRequest, when set, is called when the author adds follow-up instructions via "Add to this request" while an agent request is running. + OnAddToAgentRequest func(text string) // AgentRunner runs a composer request against an external agent (such as Claude Code or Codex) and streams incremental steps; when nil on desktop, CLIAgentRunner is used. AgentRunner AgentRunner // AutomationDrafter optionally turns plain words from "+ New automation, in words" into a candidate AutomationRule; when nil, a built-in English/Chinese drafter is used. diff --git a/packages/game/editor/ui.go b/packages/game/editor/ui.go index fcac83533..56543f2cd 100644 --- a/packages/game/editor/ui.go +++ b/packages/game/editor/ui.go @@ -60,27 +60,10 @@ func EditorView(cx *core.Scope, ed *Editor) core.Node { ed.report(ed.StopAgentTurn()) } ed.StopRunningTasks() - if ed.OnStopAgent != nil { - ed.OnStopAgent() - } + ed.StopAgent() }) cx.OnKeyWith("mod+enter", core.KeyOptions{When: core.KeyNotEditing}, func() { - // Trust boundary (#1015): ⌘↵ NEVER applies a You-only permissions draft, and must not fire over full-screen modes or modals. - if ed.shortcutCaptureActive || ed.PermissionsDraftOpen() || ed.StartScreenOpen() || ed.FirstRunFullScreenOpen() || - ed.ReviewOpen() || ed.MergeConflictOpen() || ed.DataTableReviewOpen() || ed.UsagesScreenOpen() || ed.SettingsOpen() || - ed.AssetGeneratorOpen() || ed.ConnectDialogOpen() || ed.PendingTurnPromptOpen() || ed.BuildReleaseScreenOpen() { - return - } - if ed.AgentReviewOpen() && !ed.Playing() { - _, err := ed.KeepAllReviewChanges() - ed.report(err) - return - } - if ed.reviewKeepShortcutAllowed() { - if err := ed.KeepTurnReview(); err != nil && !errors.Is(err, ErrReviewBlocked) { - ed.report(err) - } - } + ed.handleGlobalModEnter() }) cx.OnKeyWith("shift+f5", core.KeyOptions{When: core.KeyNotEditing}, func() { if ed.GameRunning() { @@ -1888,6 +1871,7 @@ func statusBarView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.No }, }, remoteStatusView(cx, ed, rev), + agentStatusBarActivityView(cx, ed, rev), core.Show{ When: func() bool { _ = rev.Get() @@ -2139,3 +2123,23 @@ func playReplayBannerView(ed *Editor, rev *core.Signal[uint64]) core.Node { }, } } + +func (e *Editor) handleGlobalModEnter() { + // Trust boundary (#1015): ⌘↵ NEVER applies a You-only permissions draft, and must not fire over full-screen modes, modals, or a focused permission card. + if e.shortcutCaptureActive || e.CapturingKey() || e.PermissionsDraftOpen() || e.PendingAgentPermissionCardFocused() || + e.StartScreenOpen() || e.FirstRunFullScreenOpen() || e.ReviewOpen() || e.MergeConflictOpen() || + e.DataTableReviewOpen() || e.UsagesScreenOpen() || e.SettingsOpen() || e.AssetGeneratorOpen() || + e.ConnectDialogOpen() || e.PendingTurnPromptOpen() || e.BuildReleaseScreenOpen() { + return + } + if e.AgentReviewOpen() && !e.Playing() { + _, err := e.KeepAllReviewChanges() + e.report(err) + return + } + if e.reviewKeepShortcutAllowed() { + if err := e.KeepTurnReview(); err != nil && !errors.Is(err, ErrReviewBlocked) { + e.report(err) + } + } +}