diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 029ff48..4a41835 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -151,10 +151,16 @@ short of a full supervisor. Known limitations, accepted for now: full filesystem access. Only configure servers you trust. - **Dead servers are restarted on demand.** When a server process exits, its tools stay registered; the next call to one of them restarts and re-initializes the - server and retries exactly once. A failed restart surfaces as an + server before dispatch. A disconnect during a call reports an unknown outcome. + Calls are never automatically replayed. An unknown mutation outcome stops the + agent turn so the user can verify the result before requesting a retry. A failed restart surfaces as an `MCP server "" unavailable: ...` tool error, and after `CloseAll` no further restarts are attempted. Restarts are serialized with shutdown, so a restart cannot resurrect a process after GoCode begins closing servers. +- **Read-only MCP grants require local trust.** Under the individual MCP server + configuration, set `trusted_read_only_tools = ["tool_name"]` using the exact + advertised tool names. The default is empty. A tool must also advertise + `readOnlyHint` to qualify for the per-turn grant or parallel read execution. - **Advertised metadata is capped.** A server advertising more than 200 tools is rejected outright; individual tools with a name over 128 bytes, a description over 8 KiB, or an input schema over 32 KiB are skipped (and reported) rather than diff --git a/internal/agent/loop.go b/internal/agent/loop.go index 269376a..78ca568 100644 --- a/internal/agent/loop.go +++ b/internal/agent/loop.go @@ -215,6 +215,7 @@ func NewAgentLoop(registry *provider.Registry, session *Session, toolReg *tools. // to one loop; a gate shared by several loops binds to the last constructor. if approval != nil { approval.Bus = a + approval.Registry = toolReg if session != nil { approval.SetSessionID(session.ID()) } @@ -462,7 +463,7 @@ func (a *AgentLoop) streamResponse(ctx context.Context, m *turnMetrics) error { // A hook halt is a clean termination (StopTurn maps onto end_turn): // the tool result already carries the halt wording, and the exit funnel // fires TurnEnd, not StopFailure. - if errors.Is(err, errHookHalt) { + if errors.Is(err, errTurnHalted) { return nil } return err @@ -948,7 +949,7 @@ func (a *AgentLoop) handleToolCalls(ctx context.Context, toolCalls []provider.To } a.finishToolCalls(ctx, entries, m) a.writeSyntheticToolResults(toolCalls[i+1:], haltedToolResult) - return errHookHalt + return errTurnHalted } continue } @@ -984,7 +985,7 @@ func (a *AgentLoop) handleToolCalls(ctx context.Context, toolCalls []provider.To // Phase C publishes results in call order, regardless of completion order. // A post-hook halt ends the turn once every result is in the transcript. if halted := a.finishToolCalls(ctx, entries, m); halted { - return errHookHalt + return errTurnHalted } return nil } @@ -1027,7 +1028,7 @@ func (p *preparedToolCall) interrupt() { // toolIsReadOnly reports whether a call may run concurrently with other // read-only calls. Tools that opt into the read-only contract decide for -// themselves (MCP servers report the readOnlyHint); the built-in non-prompting +// themselves (MCP requires a locally trusted read-only hint); the built-in non-prompting // readers are classified by name. This is a concurrency classification only; // approval behavior is unchanged. func (a *AgentLoop) toolIsReadOnly(tool tools.Tool, name string) bool { @@ -1047,7 +1048,7 @@ func (a *AgentLoop) executeToolCalls(ctx context.Context, entries []*preparedToo waitPending := func() { wg.Wait() } - for _, e := range entries { + for i, e := range entries { if ctx.Err() != nil && !e.executed && !e.interrupted { // Unreached by the canceled turn; keep the message for Phase C. e.interrupt() @@ -1080,6 +1081,15 @@ func (a *AgentLoop) executeToolCalls(ctx context.Context, entries []*preparedToo continue } a.runPreparedCall(ctx, e) + if e.result.OutcomeUnknown { + for _, pending := range entries[i+1:] { + if pending.execute != nil { + pending.result = tools.Result{Error: "Skipped: verify the previous tool outcome before continuing."} + pending.execute = nil + } + } + return errTurnHalted + } } waitPending() diff --git a/internal/agent/loop_hooks.go b/internal/agent/loop_hooks.go index 44cdf2f..9200ba0 100644 --- a/internal/agent/loop_hooks.go +++ b/internal/agent/loop_hooks.go @@ -30,10 +30,10 @@ import ( // nothing. With no hooks configured every path below is a nil check: zero // overhead. -// errHookHalt ends the turn cleanly after a hook halt. A halt is a normal +// errTurnHalted ends the turn cleanly after a hook halt or an uncertain tool outcome. A halt is a normal // termination (StopTurn maps onto end_turn), so streamResponse folds // this sentinel into a nil return and the exit funnel fires TurnEnd. -var errHookHalt = errors.New("turn halted by hook") +var errTurnHalted = errors.New("turn halted") // haltedToolResult closes out calls a halted turn never reached. const haltedToolResult = "Error: tool call not executed: turn halted by hook." diff --git a/internal/agent/loop_parallel_test.go b/internal/agent/loop_parallel_test.go index 530440c..20e8bde 100644 --- a/internal/agent/loop_parallel_test.go +++ b/internal/agent/loop_parallel_test.go @@ -302,3 +302,19 @@ func TestMutatingToolCallsStaySerialized(t *testing.T) { t.Fatalf("tool messages = %v, want %d", ids, len(calls)) } } + +func TestUnknownMutationStopsRemainingCalls(t *testing.T) { + entries := []*preparedToolCall{ + {execute: func(context.Context) (tools.Result, error) { + return tools.Result{OutcomeUnknown: true, Error: "disconnected"}, nil + }}, + {execute: func(context.Context) (tools.Result, error) { + t.Fatal("executed a second mutation") + return tools.Result{}, nil + }}, + } + loop := &AgentLoop{} + if err := loop.executeToolCalls(context.Background(), entries); err != errTurnHalted || entries[1].result.Error == "" { + t.Fatalf("outcome: %v, pending: %+v", err, entries[1].result) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index b81ad46..d368a94 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -157,9 +157,10 @@ type MCPConfig struct { // MCPServerConfig defines an individual MCP server command and arguments. type MCPServerConfig struct { - Command string `toml:"command"` - Args []string `toml:"args"` - Env map[string]string `toml:"env,omitempty"` + Command string `toml:"command"` + Args []string `toml:"args"` + Env map[string]string `toml:"env,omitempty"` + TrustedReadOnlyTools []string `toml:"trusted_read_only_tools,omitempty"` // RequestTimeoutSeconds bounds a single JSON-RPC request to this server. // Zero or negative uses the built-in default of 60 seconds. RequestTimeoutSeconds int `toml:"request_timeout_seconds"` diff --git a/internal/hooks/runner.go b/internal/hooks/runner.go index 0312466..ee6b737 100644 --- a/internal/hooks/runner.go +++ b/internal/hooks/runner.go @@ -54,6 +54,9 @@ func ShellExecutor(ctx context.Context, command, cwd string, stdin []byte, env [ var exitErr *exec.ExitError if errors.As(err, &exitErr) { code = exitErr.ExitCode() + if code >= 0 { + err = nil // A completed hook communicates policy through its exit status. + } } else { code = -1 } diff --git a/internal/hooks/runner_test.go b/internal/hooks/runner_test.go index 6a3e6ac..bd57c7d 100644 --- a/internal/hooks/runner_test.go +++ b/internal/hooks/runner_test.go @@ -357,6 +357,19 @@ func TestRunnerHaltExitCodeIntegration(t *testing.T) { } } +func TestProductionRunnerDenials(t *testing.T) { + for _, tc := range []struct { + command string + halt bool + }{{"exit 2", false}, {"exit 49", true}} { + r := newTestRunner(t, Config{PreToolUse: []Hook{{Command: tc.command}}}, nil) + got := r.Run(context.Background(), PreToolUse, Input{}) + if got.Decision != DecisionDeny || got.Halt != tc.halt { + t.Fatalf("%s: %+v", tc.command, got) + } + } +} + // The real shell executor works on every platform (no skips): echo and a // deliberate exit code through the platform shell (bash -c / cmd /C). func TestShellExecutorRealSmoke(t *testing.T) { diff --git a/internal/mcp/client_test.go b/internal/mcp/client_test.go index 4635120..96023b3 100644 --- a/internal/mcp/client_test.go +++ b/internal/mcp/client_test.go @@ -118,8 +118,17 @@ func TestFakeMCPServerProcess(t *testing.T) { } fmt.Fprintf(os.Stdout, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"result\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{},\"serverInfo\":{\"name\":\"fake\",\"version\":\"0.0.1\"}}}\n", *req.ID) case "tools/list": - fmt.Fprintf(os.Stdout, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"result\":{\"tools\":[{\"name\":\"echo\",\"description\":\"echo back\",\"inputSchema\":{\"type\":\"object\"}}]}}\n", *req.ID) + fmt.Fprintf(os.Stdout, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"result\":{\"tools\":[{\"name\":\"echo\",\"description\":\"echo back\",\"annotations\":{\"readOnlyHint\":true},\"inputSchema\":{\"type\":\"object\"}}]}}\n", *req.ID) case "tools/call": + if marker := os.Getenv("GO_FAKE_MCP_CALL_MARKER"); marker != "" { + f, err := os.OpenFile(marker, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) + if err != nil { + os.Exit(1) + } + fmt.Fprintln(f, "called") + f.Close() + os.Exit(0) + } fmt.Fprintf(os.Stdout, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"result\":{\"content\":[{\"type\":\"text\",\"text\":\"hi\"}],\"isError\":false}}\n", *req.ID) } } diff --git a/internal/mcp/manager.go b/internal/mcp/manager.go index eb91e73..3591fe6 100644 --- a/internal/mcp/manager.go +++ b/internal/mcp/manager.go @@ -6,6 +6,7 @@ import ( "fmt" "log/slog" "os" + "slices" "sync" "time" @@ -143,6 +144,7 @@ func (m *Manager) StartAll(ctx context.Context, toolRegistry *tools.Registry) er } mcpTool := newManagedMCPTool(m, name, tInfo, client) + mcpTool.readOnly = tInfo.Annotations != nil && tInfo.Annotations.ReadOnlyHint && slices.Contains(cfg.TrustedReadOnlyTools, tInfo.Name) if err := toolRegistry.Register(mcpTool); err != nil { slog.Warn("failed to register MCP tool", "server", name, "tool", tInfo.Name, "error", err) fmt.Fprintf(os.Stderr, "gocode: could not register MCP tool from %q: %v\n", name, err) diff --git a/internal/mcp/robustness_test.go b/internal/mcp/robustness_test.go index d78434e..9bcb2ae 100644 --- a/internal/mcp/robustness_test.go +++ b/internal/mcp/robustness_test.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "os" + "path/filepath" "strconv" "strings" "sync" @@ -448,3 +449,30 @@ func TestMCPTool_PreviewInvalidJSONFallsBackToRaw(t *testing.T) { t.Fatalf("expected empty object for missing arguments, got %q", empty.Description) } } + +func TestDisconnectAfterDispatchNeverReplays(t *testing.T) { + marker := filepath.Join(t.TempDir(), "calls") + cfg := fakeServerConfig("TestFakeMCPServerProcess", map[string]string{ + "GO_FAKE_MCP_SERVER": "1", "GO_FAKE_MCP_CALL_MARKER": marker, + }, 10) + trusted := cfg + trusted.TrustedReadOnlyTools = []string{"echo"} + mgr := NewManager(map[string]config.MCPServerConfig{"default": cfg, "trusted": trusted}) + defer mgr.CloseAll() + reg := tools.NewRegistry() + if err := mgr.StartAll(context.Background(), reg); err != nil { + t.Fatal(err) + } + tool := reg.Get("mcp_default_echo").(*MCPTool) + if tool.ReadOnly() || !reg.Get("mcp_trusted_echo").(*MCPTool).ReadOnly() { + t.Fatal("read-only hint must also have local trust for that server and tool") + } + res, err := tool.Execute(context.Background(), json.RawMessage("{}")) + if err != nil || !res.OutcomeUnknown || !strings.Contains(res.Error, "Outcome unknown") { + t.Fatalf("lost response: %+v, %v", res, err) + } + calls, err := os.ReadFile(marker) + if err != nil || string(calls) != "called\n" { + t.Fatalf("dispatches = %q, err = %v", calls, err) + } +} diff --git a/internal/mcp/tool.go b/internal/mcp/tool.go index cd27606..3b6dc2e 100644 --- a/internal/mcp/tool.go +++ b/internal/mcp/tool.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "strings" "sync/atomic" @@ -34,7 +35,6 @@ func NewMCPTool(serverName string, info ToolInfo, client *Client) *MCPTool { toolName: info.Name, description: info.Description, parameters: info.InputSchema, - readOnly: info.Annotations != nil && info.Annotations.ReadOnlyHint, } t.client.Store(client) return t @@ -71,9 +71,7 @@ func (m *MCPTool) RequiresApproval() bool { return true } -// ReadOnly reports the server's MCP readOnlyHint. The approval gate uses it -// only to honor an explicit "read-only tools this turn" choice; a server that -// lies about the hint is still gated by the per-call prompt otherwise. +// ReadOnly requires both local trust for this server/tool pair and the server hint. func (m *MCPTool) ReadOnly() bool { return m.readOnly } @@ -105,15 +103,21 @@ func (m *MCPTool) Execute(ctx context.Context, args json.RawMessage) (tools.Resu return tools.Result{Error: fmt.Sprintf("MCP server %q unavailable: client is not initialized", m.serverName)}, nil } - callRes, err := client.CallTool(ctx, m.toolName, args) - if err != nil && m.manager != nil && client.IsClosed() && ctx.Err() == nil { - // The server process died: restart it and retry exactly once. + if m.manager != nil && client.IsClosed() && ctx.Err() == nil { + // Reconnect only before dispatch. A lost reply may follow a committed write. restarted, restartErr := m.manager.EnsureClient(ctx, m.serverName) if restartErr != nil { return tools.Result{Error: restartErr.Error()}, nil } m.client.Store(restarted) - callRes, err = restarted.CallTool(ctx, m.toolName, args) + client = restarted + } + callRes, err := client.CallTool(ctx, m.toolName, args) + if err != nil && (client.IsClosed() || errors.Is(err, context.DeadlineExceeded)) { + return tools.Result{ + OutcomeUnknown: !m.ReadOnly(), + Error: fmt.Sprintf("MCP server %q: %v. Outcome unknown. Verify the result before requesting another call.", m.serverName, err), + }, nil } if err != nil { return tools.Result{Error: err.Error()}, nil diff --git a/internal/tools/approval.go b/internal/tools/approval.go index 210de56..645aabd 100644 --- a/internal/tools/approval.go +++ b/internal/tools/approval.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "os" + "sort" "strings" "sync" @@ -62,6 +63,7 @@ type promptInfo struct { } type ApprovalGate struct { + Registry *Registry autoApprove map[string]bool deny map[string]bool // grants holds keyed session grants (PermissionKey). In-memory only, @@ -474,13 +476,23 @@ func (g *ApprovalGate) presentHook(snap pubsub.PermissionRequest) (ApprovalChoic displayPreview := safetext.Sanitize(snap.Description) displayDanger := safetext.Sanitize(snap.DangerReason) + var trusted []string + if g.Registry != nil { + for _, name := range g.Registry.List() { + if strings.HasPrefix(name, "mcp_") && toolReadOnly(g.Registry.Get(name)) { + trusted = append(trusted, safetext.Sanitize(name)) + } + } + sort.Strings(trusted) + } if g.OnPresentPrompt != nil { return g.OnPresentPrompt(ApprovalPrompt{ - ID: snap.ID, - ToolName: displayName, - Args: snap.Args, - Preview: displayPreview, - Danger: displayDanger, + TrustedReadOnly: trusted, + ID: snap.ID, + ToolName: displayName, + Args: snap.Args, + Preview: displayPreview, + Danger: displayDanger, }) } if g.OnPresentChoice != nil { @@ -496,6 +508,9 @@ func (g *ApprovalGate) presentHook(snap pubsub.PermissionRequest) (ApprovalChoic } return ApprovalDeny, nil } + if len(trusted) > 0 { + fmt.Println("Read-only turn includes trusted MCP tools:", strings.Join(trusted, ", ")) + } return g.promptTerminal(displayName, snap.Args, displayPreview, displayDanger) } diff --git a/internal/tools/permission.go b/internal/tools/permission.go index c7eb4d7..5f78c91 100644 --- a/internal/tools/permission.go +++ b/internal/tools/permission.go @@ -130,11 +130,12 @@ type PromptObserver interface { // ApprovalPrompt is the full presentation payload handed to OnPresentPrompt. // Danger is empty for non-dangerous calls, otherwise the classifier reason. type ApprovalPrompt struct { - ID string - ToolName string - Args json.RawMessage - Preview string - Danger string + TrustedReadOnly []string + ID string + ToolName string + Args json.RawMessage + Preview string + Danger string } // newPermissionID returns an unguessable UUID-shaped hex id (crypto/rand, diff --git a/internal/tools/tool.go b/internal/tools/tool.go index b158106..b6c86a6 100644 --- a/internal/tools/tool.go +++ b/internal/tools/tool.go @@ -46,9 +46,11 @@ func (p Preview) String() string { } type Result struct { - Output string `json:"output,omitempty"` - Error string `json:"error,omitempty"` - Diff string `json:"diff,omitempty"` + // OutcomeUnknown stops the turn when a dispatched mutation lost its reply. + OutcomeUnknown bool `json:"-"` + Output string `json:"output,omitempty"` + Error string `json:"error,omitempty"` + Diff string `json:"diff,omitempty"` } func (r Result) String() string { diff --git a/internal/tui/approval.go b/internal/tui/approval.go index eff7460..bb3b346 100644 --- a/internal/tui/approval.go +++ b/internal/tui/approval.go @@ -7,9 +7,10 @@ import ( ) type ApprovalRequest struct { - ToolName string - Args json.RawMessage - Preview string + TrustedReadOnly []string + ToolName string + Args json.RawMessage + Preview string // Danger, when non-empty, marks the call as potentially destructive: the // modal starts focused on Deny and restyles the approving button negative. Danger string @@ -66,11 +67,12 @@ func (b *ApprovalBridge) RequestApprovalChoice(toolName string, args json.RawMes func (b *ApprovalBridge) RequestApprovalPrompt(p tools.ApprovalPrompt) (tools.ApprovalChoice, error) { choiceCh := make(chan tools.ApprovalChoice, 1) b.RequestCh <- ApprovalRequest{ - ToolName: p.ToolName, - Args: p.Args, - Preview: p.Preview, - Danger: p.Danger, - ChoiceCh: choiceCh, + TrustedReadOnly: p.TrustedReadOnly, + ToolName: p.ToolName, + Args: p.Args, + Preview: p.Preview, + Danger: p.Danger, + ChoiceCh: choiceCh, } return <-choiceCh, nil } diff --git a/internal/tui/grants_test.go b/internal/tui/grants_test.go index 37c36db..8eef20e 100644 --- a/internal/tui/grants_test.go +++ b/internal/tui/grants_test.go @@ -28,7 +28,7 @@ func TestApprovalModalAllowExactKey(t *testing.T) { } view := stripANSI(m.View().Content) - if !strings.Contains(view, "grant session") { + if !strings.Contains(view, "allow exact request this session") { t.Fatalf("modal footer missing the allow-exact hint:\n%s", view) } if !strings.Contains(view, "read-only turn") { @@ -40,7 +40,7 @@ func TestApprovalModalAllowExactKey(t *testing.T) { if m.overlays.has(overlayApproval) { t.Fatal("modal stayed open after 'a'") } - if !m.sessionGrants["shell_exec"] { + if !m.sessionGrants["shell_exec · command: ls"] { t.Fatal("session grant not recorded by the model") } @@ -62,7 +62,7 @@ func TestApprovalModalAllowExactKey(t *testing.T) { ChoiceCh: make(chan tools.ApprovalChoice, 1), } view = stripANSI(m.View().Content) - if !strings.Contains(view, "granted: shell_exec") { + if !strings.Contains(view, "granted: shell_exec · command: ls") { t.Fatalf("footer does not list the used grant:\n%s", view) } } @@ -136,3 +136,31 @@ func TestApprovalChoiceBridgeRoundTrip(t *testing.T) { t.Fatal("choice requester never received a reply") } } + +func TestApprovalPagesKeepChoicesAndFullUnicodeText(t *testing.T) { + m := newTestModel(nil) + next, _ := m.Update(tea.WindowSizeMsg{Width: 80, Height: 24}) + m = next.(Model) + args, _ := json.Marshal(map[string]string{"z": "last", "path": strings.Repeat("界", 100) + "tail"}) + m.approvalReq = ApprovalRequest{ToolName: "file_write", Args: args, Danger: "writes a file", Preview: strings.Repeat("+changed\n", 100) + "+end"} + if got := approvalArguments(m.approvalReq); !strings.HasPrefix(got[0], "path: ") { + t.Fatalf("argument order = %v", got) + } + m, _ = m.updateApproval(tea.KeyPressMsg{Code: 'v', Text: "v"}) + view := stripANSI(m.renderApprovalModal()) + if !strings.Contains(view, "tail") || strings.Contains(view, "�") { + t.Fatalf("full Unicode argument missing:\n%s", view) + } + for range 25 { + m, _ = m.updateApproval(tea.KeyPressMsg{Code: tea.KeyPgDown}) + } + view = stripANSI(m.renderApprovalModal()) + for _, text := range []string{"+end", "Approve", "Deny", "writes a file", "PgUp/PgDn"} { + if !strings.Contains(view, text) { + t.Fatalf("missing %q on last page:\n%s", text, view) + } + } + if len(strings.Split(view, "\n")) > 24 { + t.Fatalf("approval exceeds screen height:\n%s", view) + } +} diff --git a/internal/tui/keymap.go b/internal/tui/keymap.go index 837a0bc..05a8edc 100644 --- a/internal/tui/keymap.go +++ b/internal/tui/keymap.go @@ -54,6 +54,7 @@ const ( actPaletteUp keyAction = "palette-up" actPaletteDown keyAction = "palette-down" + actApprovalFullArgs keyAction = "approval-full-args" actApprovalToggle keyAction = "approval-toggle" actApprovalConfirm keyAction = "approval-confirm" actApprovalAllow keyAction = "approval-allow" @@ -162,6 +163,9 @@ var keyBindings = []keyBinding{ {Keys: []string{"r"}, Context: keyCtxApproval, Action: actApprovalReadOnly, Help: ""}, {Keys: []string{"esc"}, Context: keyCtxApproval, Action: actApprovalReject, Help: ""}, {Keys: []string{"ctrl+c"}, Context: keyCtxApproval, Action: actApprovalDenyQuit, Help: ""}, + {Keys: []string{"v"}, Context: keyCtxApproval, Action: actApprovalFullArgs}, + {Keys: []string{"pgup"}, Context: keyCtxApproval, Action: actScrollPageUp}, + {Keys: []string{"pgdown"}, Context: keyCtxApproval, Action: actScrollPageDn}, {Keys: []string{"t"}, Context: keyCtxApproval, Action: actApprovalDiffToggle, Help: ""}, {Keys: []string{"f"}, Context: keyCtxApproval, Action: actApprovalDiffFullscreen, Help: ""}, diff --git a/internal/tui/model.go b/internal/tui/model.go index 65cb958..710a34e 100644 --- a/internal/tui/model.go +++ b/internal/tui/model.go @@ -173,8 +173,10 @@ type Model struct { // promptHistory is the in-memory Alt+P/Alt+N recall list. promptHistory promptHistory - approvalReq ApprovalRequest - approvalFocus int + approvalReq ApprovalRequest + approvalFocus int + approvalOffset int + approvalFullArgs bool // Tools the user granted exact-args approval for during this UI session, // displayed in the modal footer. The authoritative copy lives in the gate. sessionGrants map[string]bool @@ -559,6 +561,8 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.approvalReq.Args = json.RawMessage(safetext.Sanitize(string(msg.req.Args))) m.approvalReq.Danger = safetext.Sanitize(msg.req.Danger) m.approvalFocus = 0 + m.approvalOffset = 0 + m.approvalFullArgs = false if m.approvalReq.Danger != "" { // Danger-biased default: a reflexive Enter refuses. m.approvalFocus = 1 @@ -690,17 +694,29 @@ func (m Model) updateApproval(msg tea.KeyPressMsg) (Model, tea.Cmd) { case actApprovalReject: return m.resolveApproval(tools.ApprovalDeny, "✗ Denied", RoleError) case actApprovalGrant: + if m.approvalReq.ToolName == "/commit" { + return m, nil + } if m.sessionGrants == nil { m.sessionGrants = make(map[string]bool) } - // "/commit" is a synthetic slash-command prompt, not a gate tool; the - // gate keeps no grant for it, so the footer must not claim one. - if m.approvalReq.ToolName != "/commit" { - m.sessionGrants[m.approvalReq.ToolName] = true - } + m.sessionGrants[grantSummary(m.approvalReq)] = true return m.resolveApproval(tools.ApprovalGrantExact, "✓ Approved (exact args this session)", RoleSystem) case actApprovalReadOnly: + if m.approvalReq.ToolName == "/commit" { + return m, nil + } return m.resolveApproval(tools.ApprovalReadOnlyTurn, "✓ Read-only tools allowed this turn", RoleSystem) + case actScrollPageUp, actScrollPageDn: + _, page, last := m.approvalPage() + step := page + if binding.Action == actScrollPageUp { + step = -page + } + m.approvalOffset = max(0, min(last, min(last, m.approvalOffset)+step)) + case actApprovalFullArgs: + m.approvalFullArgs = !m.approvalFullArgs + m.approvalOffset = 0 case actApprovalDiffToggle: m.diffSplit = !m.diffSplit case actApprovalDiffFullscreen: @@ -853,7 +869,7 @@ func (m Model) resolveApproval(choice tools.ApprovalChoice, label string, role C var cmd tea.Cmd if choice == tools.ApprovalGrantExact { // A session grant is confirmed with a toast. - cmd = m.showToast(toastSuccess, "Session grant: "+req.ToolName) + cmd = m.showToast(toastSuccess, "Session grant: "+grantSummary(req)) } return m, cmd } @@ -1308,68 +1324,117 @@ func (m *Model) renderMessage(msg ChatMessage) string { return "" } +func approvalArguments(req ApprovalRequest) []string { + var args map[string]json.RawMessage + if err := json.Unmarshal(req.Args, &args); err != nil { + return []string{safetext.Sanitize(string(req.Args))} + } + keys := make([]string, 0, len(args)) + for _, key := range []string{"command", "path"} { + if _, ok := args[key]; ok { + keys = append(keys, key) + } + } + first := len(keys) + for key := range args { + if key != "command" && key != "path" { + keys = append(keys, key) + } + } + sort.Strings(keys[first:]) + lines := make([]string, 0, len(keys)) + for _, key := range keys { + value := string(args[key]) + var decoded string + if strings.HasPrefix(value, "\"") && json.Unmarshal(args[key], &decoded) == nil { + value = decoded + } + lines = append(lines, safetext.Sanitize(key+": "+value)) + } + return lines +} + +func grantSummary(req ApprovalRequest) string { + label := safetext.Sanitize(req.ToolName) + if args := approvalArguments(req); len(args) > 0 { + label += " · " + strings.Join(strings.Fields(args[0]), " ") + } + return truncateToWidth(label, 72) +} + func (m *Model) renderApprovalModal() string { - req := m.approvalReq + view, _, _ := m.approvalPage() + return view +} - // Sizing: min(70, area-border); fullscreen (f) takes the screen. - modalW := max(30, min(70, m.width-2)) +func (m *Model) approvalPage() (view string, page, last int) { + req := m.approvalReq + width := max(14, min(70, m.width-2)) if m.diffFullscreen { - modalW = max(30, m.width-2) + width = max(14, m.width-2) } - innerW := modalW - 4 - - var b strings.Builder - b.WriteString("Tool: " + modalToolNameStyle.Render(safetext.Sanitize(req.ToolName))) + inner := width - 4 + header := truncateToWidth(modalToolNameStyle.Render(safetext.Sanitize(req.ToolName)), inner) + var body []string if req.Danger != "" { - warn := lipgloss.NewStyle().Foreground(activeTheme.Tokens.Destructive) - b.WriteString("\n" + warn.Render("⚠ Potentially dangerous: "+safetext.Sanitize(req.Danger))) + warning := "⚠ Potentially dangerous: " + safetext.Sanitize(req.Danger) + header += "\n" + lipgloss.NewStyle().Foreground(activeTheme.Tokens.Destructive).Render(truncateToWidth(strings.Join(strings.Fields(warning), " "), inner)) + if cellWidth(warning) > inner || strings.Contains(warning, "\n") { + body = append(body, warning) + } } - - var prettyArgs map[string]interface{} - if err := json.Unmarshal(req.Args, &prettyArgs); err == nil { - for k, v := range prettyArgs { - // Values are decoded after ingestion, so sanitize again for display. - val := safetext.Sanitize(fmt.Sprintf("%v", v)) - if len(val) > 120 { - val = val[:117] + "..." - } - b.WriteString("\n" + modalArgKeyStyle.Render(safetext.Sanitize(k)+": ") + modalArgValStyle.Render(val)) + for _, arg := range approvalArguments(req) { + if !m.approvalFullArgs { + arg = truncateToWidth(strings.NewReplacer("\n", "↵", "\t", "⇥").Replace(arg), inner) } - } else { - b.WriteString("\n" + safetext.Sanitize(string(req.Args))) + key, value, _ := strings.Cut(arg, ": ") + body = append(body, modalArgKeyStyle.Render(key)+": "+modalArgValStyle.Render(value)) } - - if displayPreview := safetext.Sanitize(req.Preview); displayPreview != "" { - b.WriteString("\n\nPreview:") - if looksLikeDiff(displayPreview) { + preview := safetext.Sanitize(req.Preview) + if preview != "" { + body = append(body, "Preview:") + if looksLikeDiff(preview) && !m.approvalFullArgs { if m.diffSplit { - b.WriteString("\n" + renderDiffSplit(displayPreview, innerW)) + preview = renderDiffSplit(preview, inner) } else { - b.WriteString("\n" + renderDiffView(displayPreview, innerW)) + preview = renderDiffView(preview, inner) } - } else { - b.WriteString("\n" + toolBubbleStyle.Render(displayPreview)) } - } - - // On a flagged request approving is the destructive act: the approve - // button takes the negative (error) fill when focused. - negative := req.Danger != "" - approveBtn := dialogButton("✓ Approve", m.approvalFocus == 0, negative) - denyBtn := dialogButton("✗ Deny", m.approvalFocus == 1, false) - b.WriteString("\n\n" + approveBtn + " " + denyBtn) - b.WriteString("\n" + dialogHelp( - [2]string{"←→/tab", "switch"}, [2]string{"enter", "confirm"}, [2]string{"esc", "deny"}, - [2]string{"a", "grant session"}, [2]string{"r", "read-only turn"}, - )) - if looksLikeDiff(safetext.Sanitize(req.Preview)) { - b.WriteString("\n" + dialogHelp([2]string{"t", "split/unified"}, [2]string{"f", "fullscreen"})) + body = append(body, preview) } if names := m.grantedToolNames(); len(names) > 0 { - b.WriteString("\n" + systemStyle.Render("granted: "+strings.Join(names, ", "))) + body = append(body, "granted: "+strings.Join(names, "\ngranted: ")) } - - return dialogFrame("Tool Approval Required", dialogNormal, b.String(), modalW) + scope := "none" + if len(req.TrustedReadOnly) > 0 { + scope = strings.Join(req.TrustedReadOnly, ", ") + } + body = append([]string{"Read-only MCP tools: " + scope}, body...) + lines := strings.Split(ansi.Wrap(strings.Join(body, "\n"), inner, ""), "\n") + buttons := dialogButton("✓ Approve", m.approvalFocus == 0, req.Danger != "") + " " + dialogButton("✗ Deny", m.approvalFocus == 1, false) + help := "Tab switch · Enter confirm · Esc deny · v full text" + if looksLikeDiff(safetext.Sanitize(req.Preview)) { + help += " · t split · f fullscreen" + } + if req.ToolName != "/commit" { + help += "\na allow exact request this session · r read-only turn" + } + if inner < 35 || m.height < 14 { + buttons = "y Approve / n Deny" + help = "PgUp/PgDn · v full" + } + footer := ansi.Wrap(buttons+"\n"+help, inner, "") + // Frame borders, title and page indicator each occupy one row. + page = max(1, m.height-4-lipgloss.Height(header)-lipgloss.Height(footer)) + last = max(0, len(lines)-page) + start := min(m.approvalOffset, last) + end := min(len(lines), start+page) + status := fmt.Sprintf("Lines %d–%d of %d", start+1, end, len(lines)) + if last > 0 { + status += " · PgUp/PgDn" + } + content := header + "\n" + strings.Join(lines[start:end], "\n") + "\n" + truncateToWidth(status, inner) + "\n" + footer + return dialogFrame("Tool Approval Required", dialogNormal, content, width), page, last } func placeModal(base, modal string, totalW, totalH int) string { diff --git a/internal/tui/styles.go b/internal/tui/styles.go index b9fa9b9..d07da94 100644 --- a/internal/tui/styles.go +++ b/internal/tui/styles.go @@ -52,7 +52,6 @@ type palette struct { userBg color.Color userFg color.Color asstFg color.Color - toolBg color.Color toolFg color.Color // Mascot. @@ -100,7 +99,6 @@ func projectPalette(t Tokens) palette { userBg: t.BgLessVisible, userFg: t.Primary, asstFg: t.Accent, - toolBg: t.BgLessVisible, toolFg: t.Info, mascotBody: t.FgMoreSubtle, @@ -150,7 +148,6 @@ var ( // Each speaker owns a hue; fills only for quoted user/tool text. colorUserFg color.Color colorAsstFg color.Color - colorToolBg color.Color colorToolFg color.Color ) @@ -168,7 +165,6 @@ var ( asstLabelStyle lipgloss.Style toolLabelStyle lipgloss.Style toolDoneLabelStyle lipgloss.Style - toolBubbleStyle lipgloss.Style toolBodyStyle lipgloss.Style toolFaintStyle lipgloss.Style spinnerSuffixStyle lipgloss.Style @@ -235,7 +231,6 @@ func rebuildStyles() { colorDanger = col.danger colorUserFg = col.userFg colorAsstFg = col.asstFg - colorToolBg = col.toolBg colorToolFg = col.toolFg // Status bar. Side padding is load-bearing for renderStatusBar width math. @@ -294,12 +289,6 @@ func rebuildStyles() { Foreground(colorSuccess). Bold(true) - toolBubbleStyle = lipgloss.NewStyle(). - Foreground(colorToolFg). - Background(colorToolBg). - Padding(0, rowPadCompact). - MarginLeft(indentGutter) - // The tool-card body sits indented on the less-visible // surface; params render faint inside it. toolBodyStyle = lipgloss.NewStyle().