Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.
cmd: agent UI (#17017)
Parth Sareen82f905cd9c06
diff --git a/agent/approval.go b/agent/approval.gonew file mode 100644index 000000000..4889fecc0--- /dev/null+++ b/agent/approval.go@@ -0,0 +1,209 @@+package agent++import (+ "context"+ "strings"+ "sync"+)++type ApprovalRequest struct {+ WorkingDir string+ Calls []ApprovalToolCall+}++func (r *ApprovalRequest) AddToolCall(id, name string, args map[string]any) {+ r.Calls = append(r.Calls, ApprovalToolCall{+ ToolCallID: id,+ ToolName: name,+ Args: args,+ ApprovalScope: toolApprovalScope(name, args),+ })+}++type ApprovalToolCall struct {+ ToolCallID string+ ToolName string+ Args map[string]any+ ApprovalScope string+}++type Approval struct {+ Allow bool+ AllowAll bool+ AllowScopes []string+ Reason string+}++type ApprovalPrompter interface {+ PromptApproval(context.Context, ApprovalRequest) (Approval, error)+}++type ApprovalState struct {+ mu sync.RWMutex+ allowAll bool+ scopes map[string]bool+}++func (s *ApprovalState) Set(allowAll bool, scopes map[string]bool) {+ if s == nil {+ return+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ s.allowAll = allowAll+ s.scopes = cloneApprovalScopes(scopes)+}++func (s *ApprovalState) SetAllowAll(allowAll bool) {+ if s == nil {+ return+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ s.allowAll = allowAll+}++func (s *ApprovalState) AllowAll() bool {+ if s == nil {+ return false+ }+ s.mu.RLock()+ defer s.mu.RUnlock()+ return s.allowAll+}++func (s *ApprovalState) Allows(scope string) bool {+ if s == nil {+ return false+ }+ s.mu.RLock()+ defer s.mu.RUnlock()+ return s.allowAll || s.scopes[scope]+}++func (s *ApprovalState) Apply(result *Approval) {+ if s == nil || result == nil {+ return+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ if result.AllowAll {+ result.Allow = true+ s.allowAll = true+ }+ if len(result.AllowScopes) > 0 {+ result.Allow = true+ if s.scopes == nil {+ s.scopes = make(map[string]bool, len(result.AllowScopes))+ }+ for _, scope := range result.AllowScopes {+ scope = strings.TrimSpace(scope)+ if scope != "" {+ s.scopes[scope] = true+ }+ }+ }+}++func (s *ApprovalState) AllowScopes(scopes []string) {+ if s == nil {+ return+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.scopes == nil {+ s.scopes = make(map[string]bool, len(scopes))+ }+ for _, scope := range scopes {+ scope = strings.TrimSpace(scope)+ if scope != "" {+ s.scopes[scope] = true+ }+ }+}++func cloneApprovalScopes(src map[string]bool) map[string]bool {+ if len(src) == 0 {+ return nil+ }+ dst := make(map[string]bool, len(src))+ for scope, allowed := range src {+ if allowed {+ dst[scope] = true+ }+ }+ return dst+}++func (s *Session) needsApproval(tool Tool, name string, args map[string]any) bool {+ return ToolRequiresApproval(tool, args) && !s.allows(toolApprovalScope(name, args))+}++// allows reports whether scope is permitted by the session's accumulated approval state.+func (s *Session) allows(scope string) bool {+ if s == nil || s.ApprovalState == nil {+ return false+ }+ return s.ApprovalState.Allows(scope)+}++// applyApproval merges an approval result into the session's state and marks+// the result as allowed when scopes or allow-all were granted. It mutates+// result.Allow so the caller can branch on the effective decision.+func (s *Session) applyApproval(result *Approval) {+ if s == nil || result == nil {+ return+ }+ if s.ApprovalState == nil {+ s.ApprovalState = &ApprovalState{}+ }+ s.ApprovalState.Apply(result)+}++func (s *Session) authorizeToolCalls(ctx context.Context, req ApprovalRequest) (Approval, error) {+ if s == nil || len(req.Calls) == 0 || (s.ApprovalState != nil && s.ApprovalState.AllowAll()) {+ return Approval{Allow: true}, nil+ }+ if s.ApprovalPrompter == nil {+ return Approval{+ Reason: "Tool execution requires approval, but no approval prompter is available.",+ }, nil+ }++ result, err := s.ApprovalPrompter.PromptApproval(ctx, req)+ if err != nil {+ return Approval{}, err+ }+ s.applyApproval(&result)+ return result, nil+}++// toolApprovalScope returns the approval scope key for a tool invocation.+//+// For shell tools (bash/powershell) the scope is "<tool>\x00<command>": the+// exact, trimmed command byte string. "Always allow this command" therefore+// matches ONLY that precise string — any whitespace, quoting, or casing+// variant, or any command that is a superset of the approved one, will+// re-prompt. The NUL separator is safe because a shell command string cannot+// contain a literal NUL. For all other tools the scope is the tool name.+func toolApprovalScope(toolName string, args map[string]any) string {+ toolName = strings.TrimSpace(toolName)+ if isShellApprovalTool(toolName) {+ if command, ok := stringArg(args, "command"); ok {+ command = strings.TrimSpace(command)+ if command != "" {+ return toolName + "\x00" + command+ }+ }+ }+ return toolName+}++func isShellApprovalTool(name string) bool {+ return name == "bash" || name == "powershell"+}++func stringArg(args map[string]any, key string) (string, bool) {+ value, ok := args[key].(string)+ return value, ok+}diff --git a/agent/approval_test.go b/agent/approval_test.gonew file mode 100644index 000000000..88331a78e--- /dev/null+++ b/agent/approval_test.go@@ -0,0 +1,55 @@+package agent++import "testing"++func TestApprovalRequestScopesShellCommandsToExactCommand(t *testing.T) {+ req := ApprovalRequest{}+ req.AddToolCall("call-1", "bash", map[string]any{"command": " pwd "})+ req.AddToolCall("call-2", "powershell", map[string]any{"command": "Get-ChildItem"})+ req.AddToolCall("call-3", "edit", map[string]any{"path": "README.md"})++ tests := []struct {+ index int+ want string+ }{+ {index: 0, want: "bash\x00pwd"},+ {index: 1, want: "powershell\x00Get-ChildItem"},+ {index: 2, want: "edit"},+ }+ for _, tt := range tests {+ if got := req.Calls[tt.index].ApprovalScope; got != tt.want {+ t.Fatalf("call %d approval scope = %q, want %q", tt.index, got, tt.want)+ }+ }+}++func TestSessionApplyApprovalScopes(t *testing.T) {+ session := &Session{}+ result := Approval{AllowScopes: []string{"edit", "bash\x00pwd", " "}}++ session.applyApproval(&result)++ if !result.Allow {+ t.Fatal("scoped approval should allow the current request")+ }+ if !session.allows("edit") || !session.allows("bash\x00pwd") {+ t.Fatal("scoped approval was not saved")+ }+ if session.allows("bash") || session.allows("bash\x00ls") {+ t.Fatal("shell approval was too broad")+ }+ if session.ApprovalState.AllowAll() {+ t.Fatal("allow all = true, want false for scoped approval")+ }+}++func TestSessionApplyApprovalAllowAll(t *testing.T) {+ session := &Session{}+ result := Approval{AllowAll: true}++ session.applyApproval(&result)++ if !result.Allow || !session.allows("anything") {+ t.Fatalf("allow all = %v result = %#v, want allow all", session.ApprovalState.AllowAll(), result)+ }+}diff --git a/agent/registry.go b/agent/registry.goindex 1882e2fe3..7a9b4ce50 100644--- a/agent/registry.go+++ b/agent/registry.go@@ -63,6 +63,9 @@ func (r *Registry) Names() []string {}func (r *Registry) Tools() api.Tools {+ if r == nil {+ return nil+ }names := r.Names()apiTools := make(api.Tools, 0, len(names))for _, name := range names {diff --git a/agent/session.go b/agent/session.goindex 3d6b1ca2e..fbb279efc 100644--- a/agent/session.go+++ b/agent/session.go@@ -18,33 +18,13 @@ type ChatClient interface {Chat(context.Context, *api.ChatRequest, api.ChatResponseFunc) error}-type ApprovalRequest struct {- WorkingDir string- Calls []ApprovalToolCall-}--type ApprovalToolCall struct {- ToolCallID string- ToolName string- Args map[string]any-}--type Approval struct {- Allow bool- AllowAll bool- Reason string-}--type ApprovalPrompter interface {- PromptApproval(context.Context, ApprovalRequest) (Approval, error)-}-type Session struct {Client ChatClientEventSinks []EventSinkTools *Registry+ DisableTools boolApprovalPrompter ApprovalPrompter- AllowAllTools bool+ ApprovalState *ApprovalStateWorkingDir stringCompactor Compactor}@@ -101,6 +81,8 @@ const (toolExecutionCanceled toolExecutionStop = "canceled")+const toolExecutionDisabledMessage = "Tool execution disabled."+type runPhase intconst (@@ -169,6 +151,9 @@ func (s *Session) Run(ctx context.Context, opts RunOptions) (*RunResult, error)if opts.Model == "" {return nil, errors.New("agent session requires a model")}+ if s.ApprovalState == nil {+ s.ApprovalState = &ApprovalState{}+ }runID := uuid.NewString()messages := make([]api.Message, 0, len(opts.Messages)+len(opts.NewMessages))for _, msg := range opts.Messages {@@ -254,6 +239,18 @@ func (s *Session) runModelStep(ctx context.Context, st *runState) error {return nil}+ if s.DisableTools {+ batch, skipErr := s.disabledToolCalls(ctx, st.runID, opts, st.messages, pendingToolCalls)+ if skipErr != nil {+ s.emit(Event{Type: EventError, RunID: st.runID, ChatID: opts.ChatID, Model: opts.Model, Error: skipErr.Error()})+ return skipErr+ }+ st.messages = append(st.messages, batch.messages...)+ st.toolBatch = &batch+ st.phase = runPhaseCompact+ return nil+ }+if s.Tools == nil {st.finishDone()return nil@@ -344,31 +341,11 @@ func (s *Session) finishRun(ctx context.Context, st *runState) (*RunResult, erro}func (s *Session) chatRound(ctx context.Context, runID string, opts RunOptions, messages []api.Message, latest *api.ChatResponse) (api.Message, []api.ToolCall, bool, error) {- requestMessages := sanitizeMessagesForRequest(messages)- if strings.TrimSpace(opts.SystemPrompt) != "" {- withSystem := make([]api.Message, 0, len(requestMessages)+1)- withSystem = append(withSystem, api.Message{Role: "system", Content: opts.SystemPrompt})- requestMessages = append(withSystem, requestMessages...)- }-- format := opts.Format- if format == "json" {- format = `"` + format + `"`- }-- req := api.ChatRequest{- Model: opts.Model,- Messages: requestMessages,- Format: json.RawMessage(format),- Options: opts.Options,- Think: opts.Think,- }- if opts.KeepAlive != nil {- req.KeepAlive = opts.KeepAlive- }- if tools := s.availableTools(); len(tools) > 0 {- req.Tools = tools+ var tools api.Tools+ if !s.DisableTools {+ tools = s.availableTools()}+ req := buildChatRequest(opts, messages, tools)assistant := api.Message{Role: "assistant"}var pendingToolCalls []api.ToolCall@@ -418,6 +395,35 @@ func (s *Session) chatRound(ctx context.Context, runID string, opts RunOptions,return assistant, pendingToolCalls, false, nil}+func buildChatRequest(opts RunOptions, messages []api.Message, tools api.Tools) api.ChatRequest {+ requestMessages := sanitizeMessagesForRequest(messages)+ if strings.TrimSpace(opts.SystemPrompt) != "" {+ withSystem := make([]api.Message, 0, len(requestMessages)+1)+ withSystem = append(withSystem, api.Message{Role: "system", Content: opts.SystemPrompt})+ requestMessages = append(withSystem, requestMessages...)+ }++ format := opts.Format+ if format == "json" {+ format = `"` + format + `"`+ }++ req := api.ChatRequest{+ Model: opts.Model,+ Messages: requestMessages,+ Format: json.RawMessage(format),+ Options: opts.Options,+ Think: opts.Think,+ }+ if opts.KeepAlive != nil {+ req.KeepAlive = opts.KeepAlive+ }+ if len(tools) > 0 {+ req.Tools = tools+ }+ return req+}+func (s *Session) executeToolCalls(ctx context.Context, runID string, opts RunOptions, messages []api.Message, calls []api.ToolCall) (toolBatchResult, error) {batch := toolBatchResult{messages: make([]api.Message, 0, len(calls)),@@ -445,12 +451,8 @@ func (s *Session) executeToolCalls(ctx context.Context, runID string, opts RunOpargs: args,workingDir: batchWorkingDir,})- if ok && ToolRequiresApproval(tool, args) {- approvalReq.Calls = append(approvalReq.Calls, ApprovalToolCall{- ToolCallID: call.ID,- ToolName: toolName,- Args: args,- })+ if ok && s.needsApproval(tool, toolName, args) {+ approvalReq.AddToolCall(call.ID, toolName, args)}}@@ -574,25 +576,22 @@ func (s *Session) executeToolCalls(ctx context.Context, runID string, opts RunOpreturn batch, nil}-func (s *Session) authorizeToolCalls(ctx context.Context, req ApprovalRequest) (Approval, error) {- if s == nil || s.AllowAllTools || len(req.Calls) == 0 {- return Approval{Allow: true}, nil- }- if s.ApprovalPrompter == nil {- return Approval{- Reason: "Tool execution requires approval, but no approval prompter is available.",- }, nil- }-- result, err := s.ApprovalPrompter.PromptApproval(ctx, req)- if err != nil {- return Approval{}, err+func (s *Session) disabledToolCalls(ctx context.Context, runID string, opts RunOptions, messages []api.Message, calls []api.ToolCall) (toolBatchResult, error) {+ batch := toolBatchResult{+ messages: make([]api.Message, 0, len(calls)),}- if result.AllowAll {- result.Allow = true- s.AllowAllTools = true+ projectedMessages := append([]api.Message(nil), messages...)+ for _, call := range calls {+ toolName := call.Function.Name+ args := call.Function.Arguments.ToMap()+ msg := s.toolMessageForContext(toolName, call.ID, toolExecutionDisabledMessage, opts, projectedMessages)+ batch.messages = append(batch.messages, msg)+ projectedMessages = append(projectedMessages, msg)+ if emitErr := s.emitIgnoringCanceled(ctx, Event{Type: EventToolFinished, RunID: runID, ChatID: opts.ChatID, Model: opts.Model, Status: "disabled", ToolCallID: call.ID, ToolName: toolName, Args: args, Content: msg.Content, Error: msg.Content}); emitErr != nil {+ return toolBatchResult{}, emitErr+ }}- return result, nil+ return batch, nil}func (s *Session) skipToolCalls(ctx context.Context, runID string, opts RunOptions, calls []api.ToolCall, content string) ([]api.Message, error) {diff --git a/agent/session_test.go b/agent/session_test.goindex 4d70c7e6c..c8dc224d9 100644--- a/agent/session_test.go+++ b/agent/session_test.go@@ -2,6 +2,7 @@ package agentimport ("context"+ "encoding/json""errors""os""path/filepath"@@ -39,6 +40,10 @@ type approvalTestTool struct {called *bool}+type namedApprovalTestTool struct {+ name string+}+type cwdTestTool struct{}type largeTool struct{}@@ -147,6 +152,12 @@ type recordingApprovalPrompter struct {results []Approval}+func approvalStateForTest(allowAll bool, scopes map[string]bool) *ApprovalState {+ state := &ApprovalState{}+ state.Set(allowAll, scopes)+ return state+}+func (staticTool) Name() string {return "echo_tool"}@@ -272,6 +283,32 @@ func (t approvalTestTool) Execute(context.Context, ToolContext, map[string]any)return ToolResult{Content: "approved"}, nil}+func (t namedApprovalTestTool) Name() string {+ return t.name+}++func (t namedApprovalTestTool) Description() string {+ return "requires approval"+}++func (t namedApprovalTestTool) Schema() api.ToolFunction {+ return api.ToolFunction{+ Name: t.name,+ Description: "requires approval",+ Parameters: api.ToolFunctionParameters{+ Type: "object",+ },+ }+}++func (t namedApprovalTestTool) RequiresApproval(map[string]any) bool {+ return true+}++func (t namedApprovalTestTool) Execute(context.Context, ToolContext, map[string]any) (ToolResult, error) {+ return ToolResult{Content: "approved"}, nil+}+func (p *recordingApprovalPrompter) PromptApproval(_ context.Context, req ApprovalRequest) (Approval, error) {p.requests = append(p.requests, req)if len(p.results) == 0 {@@ -347,7 +384,7 @@ func TestSessionRunsToolLoop(t *testing.T) {session := &Session{Client: client,Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),}result, err := session.Run(context.Background(), RunOptions{@@ -402,6 +439,45 @@ func TestSessionAddsSystemPromptOnlyToRequest(t *testing.T) {}}+func TestSessionChatRequestMatchesRunRequest(t *testing.T) {+ client := &fakeClient{+ responses: [][]api.ChatResponse{+ {{Message: api.Message{Role: "assistant", Content: "done"}}},+ },+ }+ registry := &Registry{}+ registry.Register(staticTool{})+ session := &Session{Client: client, Tools: registry}+ opts := RunOptions{+ ChatID: "chat-1",+ Model: "model",+ SystemPrompt: "available context: go-code",+ NewMessages: []api.Message{{Role: "user", Content: "hello"}},+ Format: "json",+ Options: map[string]any{"temperature": 0.5},+ }++ want := buildChatRequest(opts, opts.NewMessages, registry.Tools())+ _, err := session.Run(context.Background(), opts)+ if err != nil {+ t.Fatal(err)+ }+ if len(client.requests) != 1 {+ t.Fatalf("requests = %d, want 1", len(client.requests))+ }+ gotJSON, err := json.Marshal(client.requests[0])+ if err != nil {+ t.Fatal(err)+ }+ wantJSON, err := json.Marshal(want)+ if err != nil {+ t.Fatal(err)+ }+ if string(gotJSON) != string(wantJSON) {+ t.Fatalf("ChatRequest mismatch\ngot: %s\nwant: %s", gotJSON, wantJSON)+ }+}+func TestSessionAccumulatesStreamingAssistantMessage(t *testing.T) {args := api.NewToolCallFunctionArguments()args.Set("value", "hello")@@ -467,7 +543,7 @@ func TestSessionRequestHistoryKeepsThinkingAndServerToolCallIDs(t *testing.T) {session := &Session{Client: client,Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),}result, err := session.Run(context.Background(), RunOptions{@@ -588,6 +664,71 @@ func TestSessionTreatsHTTPContextCanceledStringAsCancellation(t *testing.T) {}}+func TestSessionDisabledToolsOmitToolsAndReturnsDisabledResults(t *testing.T) {+ args := api.NewToolCallFunctionArguments()+ args.Set("value", "hello")+ client := &fakeClient{+ responses: [][]api.ChatResponse{+ {{+ Message: api.Message{Role: "assistant", ToolCalls: []api.ToolCall{{+ ID: "call-1",+ Function: api.ToolCallFunction{+ Name: "echo_tool",+ Arguments: args,+ },+ }}},+ }},+ {{Message: api.Message{Role: "assistant", Content: "tools are off"}}},+ },+ }+ registry := &Registry{}+ registry.Register(staticTool{})+ events := &recordingEventSink{}+ session := &Session{+ Client: client,+ EventSinks: []EventSink{events},+ Tools: registry,+ DisableTools: true,+ }++ result, err := session.Run(context.Background(), RunOptions{+ ChatID: "chat-1",+ Model: "model",+ NewMessages: []api.Message{{Role: "user", Content: "use a tool"}},+ })+ if err != nil {+ t.Fatal(err)+ }+ if len(client.requests) != 2 {+ t.Fatalf("requests = %d, want 2", len(client.requests))+ }+ if got := len(client.requests[0].Tools); got != 0 {+ t.Fatalf("advertised tools = %d, want 0", got)+ }+ secondMessages := client.requests[1].Messages+ if len(secondMessages) != 3 {+ t.Fatalf("second request messages = %#v", secondMessages)+ }+ if secondMessages[2].Role != "tool" || secondMessages[2].ToolCallID != "call-1" || secondMessages[2].Content != toolExecutionDisabledMessage {+ t.Fatalf("disabled tool message = %#v", secondMessages[2])+ }+ if len(result.Messages) != 4 || result.Messages[2].Content != toolExecutionDisabledMessage {+ t.Fatalf("result messages = %#v", result.Messages)+ }+ var sawDetected, sawDisabled bool+ for _, event := range events.events {+ if event.Type == EventToolCallDetected {+ sawDetected = true+ }+ if event.Type == EventToolFinished && event.Status == "disabled" && event.Content == toolExecutionDisabledMessage {+ sawDisabled = true+ }+ }+ if !sawDetected || !sawDisabled {+ t.Fatalf("events missing detected/disabled: %#v", events.events)+ }+}+func TestSessionCancellationAfterToolCallAppendsSkippedToolMessage(t *testing.T) {ctx, cancel := context.WithCancel(context.Background())registry := &Registry{}@@ -595,7 +736,7 @@ func TestSessionCancellationAfterToolCallAppendsSkippedToolMessage(t *testing.T)session := &Session{Client: cancelAfterToolCallClient{cancel: cancel},Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),}result, err := session.Run(ctx, RunOptions{@@ -636,7 +777,7 @@ func TestSessionCancellationDuringToolExecutionAppendsToolMessage(t *testing.T)session := &Session{Client: client,Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),EventSinks: []EventSink{events},}@@ -697,7 +838,7 @@ func TestSessionToolLoopAllowsRoundsUnderDefaultCap(t *testing.T) {session := &Session{Client: client,Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),}if _, err := session.Run(context.Background(), RunOptions{@@ -756,7 +897,7 @@ func TestSessionToolRoundLimitAppendsSkippedToolMessages(t *testing.T) {session := &Session{Client: client,Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),}result, err := session.Run(context.Background(), RunOptions{@@ -807,7 +948,7 @@ func TestSessionToolLoopStopsAtDefaultRoundCap(t *testing.T) {session := &Session{Client: client,Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),}_, err := session.Run(context.Background(), RunOptions{@@ -847,7 +988,7 @@ func TestSessionToolLoopNegativeLimitIsUnlimited(t *testing.T) {session := &Session{Client: client,Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),}if _, err := session.Run(context.Background(), RunOptions{@@ -883,7 +1024,7 @@ func TestSessionTruncatesLargeToolResultsBeforeHistory(t *testing.T) {session := &Session{Client: client,Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),}result, err := session.Run(context.Background(), RunOptions{@@ -936,7 +1077,7 @@ func TestSessionSmallContextUsesLowerToolResultPreviewCap(t *testing.T) {session := &Session{Client: client,Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),Compactor: &SimpleCompactor{Client: nil, Options: CompactionOptions{ContextWindowTokens: smallContextToolResultTokenWindow,}},@@ -984,7 +1125,7 @@ func TestSessionSmallContextRecapsPreTruncatedToolOutput(t *testing.T) {session := &Session{Client: client,Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),Compactor: &SimpleCompactor{Client: nil, Options: CompactionOptions{ContextWindowTokens: smallContextToolResultTokenWindow,}},@@ -1073,7 +1214,7 @@ func TestSessionCompactsAfterToolResultsBeforeContinuing(t *testing.T) {session := &Session{Client: client,Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),Compactor: compactor,}@@ -1134,7 +1275,7 @@ func TestSessionStopsWhenCompactedHistoryStillExceedsContext(t *testing.T) {Client: client,EventSinks: []EventSink{events},Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),Compactor: compactor,}@@ -1190,7 +1331,7 @@ func TestSessionContextCapsToolResultBeforeCompaction(t *testing.T) {session := &Session{Client: client,Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),Compactor: &SimpleCompactor{Client: nil, Options: CompactionOptions{ContextWindowTokens: 100,Threshold: 0.8,@@ -1239,7 +1380,7 @@ func TestSessionCompactsThenReattachesFullyOmittedToolResult(t *testing.T) {session := &Session{Client: client,Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),Compactor: &SimpleCompactor{Client: client, Options: CompactionOptions{ContextWindowTokens: smallContextToolResultTokenWindow,Threshold: 0.45,@@ -1316,7 +1457,7 @@ func TestSessionEmitsAutoCompactionActivityEvents(t *testing.T) {Client: client,EventSinks: []EventSink{events},Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),Compactor: &SimpleCompactor{Client: client, Options: CompactionOptions{ContextWindowTokens: 300,Threshold: 0.3,@@ -1567,7 +1708,7 @@ func TestSessionAllowsToolWorkingDirOutsideInitialDir(t *testing.T) {session := &Session{Client: client,Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),WorkingDir: root,}@@ -1726,6 +1867,83 @@ func TestSessionPromptsOnceForApprovalBatch(t *testing.T) {}}+func TestSessionRunsFullApprovedToolBatchBeforeNextModelStep(t *testing.T) {+ args := api.NewToolCallFunctionArguments()+ client := &fakeClient{+ responses: [][]api.ChatResponse{+ {+ {Message: api.Message{Role: "assistant", ToolCalls: []api.ToolCall{+ {+ ID: "call-1",+ Function: api.ToolCallFunction{+ Name: "approval_tool",+ Arguments: args,+ },+ },+ {+ ID: "call-2",+ Function: api.ToolCallFunction{+ Name: "approval_tool",+ Arguments: args,+ },+ },+ }}},+ },+ {+ {Message: api.Message{Role: "assistant", Content: "done"}},+ },+ },+ }+ registry := &Registry{}+ registry.Register(approvalTestTool{})+ prompter := &recordingApprovalPrompter{+ results: []Approval{{Allow: true}},+ }+ events := &recordingEventSink{}+ session := &Session{+ Client: client,+ Tools: registry,+ ApprovalPrompter: prompter,+ EventSinks: []EventSink{events},+ }++ result, err := session.Run(context.Background(), RunOptions{+ Model: "model",+ NewMessages: []api.Message{{Role: "user", Content: "use tools"}},+ })+ if err != nil {+ t.Fatal(err)+ }+ if client.calls != 2 {+ t.Fatalf("client calls = %d, want second model step only after tool batch", client.calls)+ }+ if len(result.Messages) != 5 {+ t.Fatalf("messages = %#v, want user, assistant tool calls, two tool results, final assistant", result.Messages)+ }+ if result.Messages[2].Role != "tool" || result.Messages[2].ToolCallID != "call-1" {+ t.Fatalf("first tool result = %#v", result.Messages[2])+ }+ if result.Messages[3].Role != "tool" || result.Messages[3].ToolCallID != "call-2" {+ t.Fatalf("second tool result = %#v", result.Messages[3])+ }+ if result.Messages[4].Role != "assistant" || result.Messages[4].Content != "done" {+ t.Fatalf("final assistant = %#v", result.Messages[4])+ }++ var finishedBeforeDelta []string+ for _, event := range events.events {+ if event.Type == EventMessageDelta && event.Content == "done" {+ break+ }+ if event.Type == EventToolFinished {+ finishedBeforeDelta = append(finishedBeforeDelta, event.ToolCallID)+ }+ }+ if strings.Join(finishedBeforeDelta, ",") != "call-1,call-2" {+ t.Fatalf("tool finishes before final model delta = %#v, want full batch before model", finishedBeforeDelta)+ }+}+func TestSessionAllowAllApprovalSkipsFuturePrompts(t *testing.T) {args := api.NewToolCallFunctionArguments()client := &fakeClient{@@ -1775,7 +1993,7 @@ func TestSessionAllowAllApprovalSkipsFuturePrompts(t *testing.T) {t.Fatal(err)}}- if !session.AllowAllTools {+ if !session.ApprovalState.AllowAll() {t.Fatal("session did not remember allow all")}if len(prompter.requests) != 1 {@@ -1783,6 +2001,150 @@ func TestSessionAllowAllApprovalSkipsFuturePrompts(t *testing.T) {}}+func TestSessionAllowToolApprovalSkipsFuturePromptForSameTool(t *testing.T) {+ args := api.NewToolCallFunctionArguments()+ client := &fakeClient{+ responses: [][]api.ChatResponse{+ {+ {Message: api.Message{Role: "assistant", ToolCalls: []api.ToolCall{{+ ID: "call-1",+ Function: api.ToolCallFunction{+ Name: "approval_tool",+ Arguments: args,+ },+ }}}},+ },+ {+ {Message: api.Message{Role: "assistant", Content: "done"}},+ },+ {+ {Message: api.Message{Role: "assistant", ToolCalls: []api.ToolCall{{+ ID: "call-2",+ Function: api.ToolCallFunction{+ Name: "approval_tool",+ Arguments: args,+ },+ }}}},+ },+ {+ {Message: api.Message{Role: "assistant", Content: "done again"}},+ },+ },+ }+ registry := &Registry{}+ registry.Register(approvalTestTool{})+ prompter := &recordingApprovalPrompter{+ results: []Approval{{AllowScopes: []string{"approval_tool"}}},+ }+ session := &Session{+ Client: client,+ Tools: registry,+ ApprovalPrompter: prompter,+ }++ for range 2 {+ if _, err := session.Run(context.Background(), RunOptions{+ Model: "model",+ NewMessages: []api.Message{{Role: "user", Content: "use a tool"}},+ }); err != nil {+ t.Fatal(err)+ }+ }+ if session.ApprovalState.AllowAll() {+ t.Fatal("allowing one tool enabled full access")+ }+ if !session.ApprovalState.Allows("approval_tool") {+ t.Fatal("approval_tool scope was not saved")+ }+ if len(prompter.requests) != 1 {+ t.Fatalf("approval prompts = %d, want 1", len(prompter.requests))+ }+}++func TestSessionAllowShellApprovalScopesToExactCommand(t *testing.T) {+ pwdArgs := api.NewToolCallFunctionArguments()+ pwdArgs.Set("command", "pwd")+ lsArgs := api.NewToolCallFunctionArguments()+ lsArgs.Set("command", "ls")+ client := &fakeClient{+ responses: [][]api.ChatResponse{+ {+ {Message: api.Message{Role: "assistant", ToolCalls: []api.ToolCall{{+ ID: "call-1",+ Function: api.ToolCallFunction{+ Name: "bash",+ Arguments: pwdArgs,+ },+ }}}},+ },+ {+ {Message: api.Message{Role: "assistant", Content: "done"}},+ },+ {+ {Message: api.Message{Role: "assistant", ToolCalls: []api.ToolCall{{+ ID: "call-2",+ Function: api.ToolCallFunction{+ Name: "bash",+ Arguments: pwdArgs,+ },+ }}}},+ },+ {+ {Message: api.Message{Role: "assistant", Content: "done again"}},+ },+ {+ {Message: api.Message{Role: "assistant", ToolCalls: []api.ToolCall{{+ ID: "call-3",+ Function: api.ToolCallFunction{+ Name: "bash",+ Arguments: lsArgs,+ },+ }}}},+ },+ {+ {Message: api.Message{Role: "assistant", Content: "done finally"}},+ },+ },+ }+ registry := &Registry{}+ registry.Register(namedApprovalTestTool{name: "bash"})+ prompter := &recordingApprovalPrompter{+ results: []Approval{+ {AllowScopes: []string{toolApprovalScope("bash", map[string]any{"command": "pwd"})}},+ {Allow: true},+ },+ }+ session := &Session{+ Client: client,+ Tools: registry,+ ApprovalPrompter: prompter,+ }++ for range 3 {+ if _, err := session.Run(context.Background(), RunOptions{+ Model: "model",+ NewMessages: []api.Message{{Role: "user", Content: "use a command"}},+ }); err != nil {+ t.Fatal(err)+ }+ }+ if !session.ApprovalState.Allows("bash\x00pwd") {+ t.Fatal("pwd command scope was not saved")+ }+ if session.ApprovalState.Allows("bash") || session.ApprovalState.Allows("bash\x00ls") {+ t.Fatal("shell approval was too broad")+ }+ if len(prompter.requests) != 2 {+ t.Fatalf("approval prompts = %d, want first pwd and later ls", len(prompter.requests))+ }+ if got := prompter.requests[0].Calls[0].ApprovalScope; got != "bash\x00pwd" {+ t.Fatalf("first approval scope = %q, want pwd command scope", got)+ }+ if got := prompter.requests[1].Calls[0].ApprovalScope; got != "bash\x00ls" {+ t.Fatalf("second approval scope = %q, want ls command scope", got)+ }+}+func TestSessionAllowAllToolsExecutesApprovalTool(t *testing.T) {args := api.NewToolCallFunctionArguments()client := &fakeClient{@@ -1807,7 +2169,7 @@ func TestSessionAllowAllToolsExecutesApprovalTool(t *testing.T) {session := &Session{Client: client,Tools: registry,- AllowAllTools: true,+ ApprovalState: approvalStateForTest(true, nil),}result, err := session.Run(context.Background(), RunOptions{diff --git a/agent/tools/bash.go b/agent/tools/bash.goindex e1fcb0b84..b5f267363 100644--- a/agent/tools/bash.go+++ b/agent/tools/bash.go@@ -133,6 +133,13 @@ func bashContentWithError(content, msg string) string {return content + "\n\n" + msg}+// rejectUnsafeShellCommand applies a best-effort blocklist for obviously+// destructive or credential-exfiltrating commands. It is defense-in-depth+// ONLY: the interactive approval prompt is the real security control, and+// this check must not be relied upon as a sandbox. Sophisticated or novel+// dangerous commands (e.g. find / -delete, dd, fork bombs, custom binaries)+// are NOT caught here and will simply be routed through approval like any+// other command. Keep the approval prompt as the gate.func rejectUnsafeShellCommand(command string) error {switch {case hasUnsafeRecursiveDelete(command):@@ -145,16 +152,51 @@ func rejectUnsafeShellCommand(command string) error {}func hasUnsafeRecursiveDelete(command string) bool {- fields := shellSafetyFields(command)- for i, field := range fields {- if isRMCommand(field) && rmCommandDeletesUnsafeTarget(fields[i+1:]) {- return true+ // Check each command segment independently. shellSafetyText flattens+ // separators (; & | newlines) to spaces, which would otherwise let the+ // rm target scan bleed across command boundaries — e.g.+ // "rm -rf build && echo ~/.ssh/config" flattened to one token stream+ // would treat the unrelated ~/.ssh/config (a ~/-prefixed "unsafe+ // target") as an rm argument. Splitting on separators first restores+ // command boundaries while still catching multi-target single commands+ // like "rm -rf build /etc".+ for _, segment := range shellSegments(command) {+ fields := shellSafetyFields(segment)+ for i, field := range fields {+ if isRMCommand(field) && rmCommandDeletesUnsafeTarget(fields[i+1:]) {+ return true+ }+ if isPowerShellDeleteCommand(field) && powerShellDeleteCommandDeletesUnsafeTarget(fields[i+1:]) {+ return true+ }}- if isPowerShellDeleteCommand(field) && powerShellDeleteCommandDeletesUnsafeTarget(fields[i+1:]) {+ }+ return false+}++// shellSegments splits a command on shell control operators (;, &, |, &&,+// ||) and newlines, returning the individual command segments. It operates on+// the lowercased raw command before quote/separator normalization so that+// command boundaries are preserved for per-segment checks. Subshell parens are+// intentionally NOT treated as separators: splitting on them would fragment+// command substitutions like "rm -rf $(echo /)" into "rm -rf $" and "echo /",+// hiding the destructive "/" target from the per-segment scan. Empty segments+// are dropped.+func shellSegments(command string) []string {+ command = strings.ToLower(command)+ var segments []string+ for _, segment := range strings.FieldsFunc(command, func(r rune) bool {+ switch r {+ case ';', '&', '|', '\n', '\r':return true}+ return false+ }) {+ if segment = strings.TrimSpace(segment); segment != "" {+ segments = append(segments, segment)+ }}- return false+ return segments}func rmCommandDeletesUnsafeTarget(fields []string) bool {@@ -211,9 +253,17 @@ func readsCredentialPath(command string) bool {"/.ssh/id_dsa","/.ssh/id_ecdsa","/.ssh/id_ed25519",+ "/.ssh/config",+ "/.ssh/known_hosts","/.aws/credentials",+ "/.aws/config","/.config/gcloud/application_default_credentials.json","/.kube/config",+ "/.netrc",+ "/.npmrc",+ "/.docker/config.json",+ "/.config/gh/hosts.yml",+ "/.gnupg/","/etc/shadow",} {if strings.Contains(normalized, fragment) {@@ -228,6 +278,8 @@ func hasCredentialReadVerb(fields []string) bool {switch field {case "cat", "less", "more", "head", "tail", "type", "get-content", "gc", "select-string", "grep", "rg", "sed", "awk":return true+ case "env", "printenv":+ return true}}return falsediff --git a/agent/tools/bash_test.go b/agent/tools/bash_test.goindex a4d89e5c5..9be40d784 100644--- a/agent/tools/bash_test.go+++ b/agent/tools/bash_test.go@@ -162,10 +162,22 @@ func TestRejectUnsafeShellCommand(t *testing.T) {{name: "ssh private key", command: "cat ~/.ssh/id_rsa", wantErr: true},{name: "aws credentials", command: "Get-Content $HOME/.aws/credentials", wantErr: true},{name: "shadow", command: "head /etc/shadow", wantErr: true},+ {name: "netrc", command: "cat ~/.netrc", wantErr: true},+ {name: "docker config", command: "cat ~/.docker/config.json", wantErr: true},+ {name: "gnupg dir", command: "cat ~/.gnupg/private-keys-v1.d/key", wantErr: true},+ {name: "gh hosts", command: "cat ~/.config/gh/hosts.yml", wantErr: true},+ {name: "ssh config", command: "cat ~/.ssh/config", wantErr: true},+ {name: "printenv dump", command: "printenv", wantErr: false},{name: "delete build dir", command: "rm -rf build", wantErr: false},{name: "read project file", command: "cat README.md", wantErr: false},{name: "mention key text", command: "rg id_rsa docs", wantErr: false},{name: "env example", command: "cat .env.example", wantErr: false},+ {name: "rm build then unrelated tilde path", command: "rm -rf build && echo ~/.ssh/config", wantErr: false},+ {name: "rm build then unrelated slash path", command: "rm -rf build; cat /etc/passwd", wantErr: false},+ {name: "rm build then unrelated star glob", command: "rm -rf build && ls *.go", wantErr: false},+ {name: "rm multiple targets one unsafe", command: "rm -rf build /etc", wantErr: true},+ {name: "rm unsafe then safe piped", command: "rm -rf / | tee log", wantErr: true},+ {name: "rm unsafe via command substitution", command: "rm -rf $(echo /)", wantErr: true},}for _, tt := range tests {diff --git a/agent/tools/file.go b/agent/tools/file.goindex 5e2f420fb..010bb652c 100644--- a/agent/tools/file.go+++ b/agent/tools/file.go@@ -63,7 +63,7 @@ func (r *Read) Execute(ctx context.Context, toolCtx agent.ToolContext, args map[return agent.ToolResult{}, fmt.Errorf("path parameter is required")}- file, info, err := openRegularFile(toolCtx.WorkingDir, path)+ file, info, err := openRegularFile(toolCtx.WorkingDir, path, true)if err != nil {return agent.ToolResult{}, err}@@ -162,7 +162,7 @@ func (e *Edit) Execute(ctx context.Context, toolCtx agent.ToolContext, args map[return agent.ToolResult{}, err}- file, info, err := openRegularFile(toolCtx.WorkingDir, path)+ file, info, err := openRegularFile(toolCtx.WorkingDir, path, false)if err != nil {return agent.ToolResult{}, err}@@ -226,7 +226,39 @@ func cleanRelativePath(path string) (string, error) {return cleaned, nil}-func openRegularFile(workingDir, path string) (*os.File, os.FileInfo, error) {+func openRegularFile(workingDir, path string, allowAbsolute bool) (*os.File, os.FileInfo, error) {+ path = strings.TrimSpace(path)+ if path == "" {+ return nil, nil, fmt.Errorf("path parameter is required")+ }+ if allowAbsolute && filepath.IsAbs(path) {+ cleaned := filepath.Clean(path)+ info, err := os.Lstat(cleaned)+ if err != nil {+ return nil, nil, err+ }+ if info.Mode()&os.ModeSymlink != 0 {+ return nil, nil, fmt.Errorf("%s is a symlink; read the target file directly", path)+ }+ if err := rejectNonRegularFile(path, info); err != nil {+ return nil, nil, err+ }+ file, err := os.Open(cleaned)+ if err != nil {+ return nil, nil, err+ }+ info, err = file.Stat()+ if err != nil {+ file.Close()+ return nil, nil, err+ }+ if err := rejectNonRegularFile(path, info); err != nil {+ file.Close()+ return nil, nil, err+ }+ return file, info, nil+ }+rel, err := cleanRelativePath(path)if err != nil {return nil, nil, err@@ -261,11 +293,14 @@ func regularRootFileInfo(root *os.Root, rel, path string) (os.FileInfo, error) {if err != nil {return nil, rootPathError(err)}+ // Reject symlinks outright. os.Root.Open follows symlinks via openat+ // without O_NOFOLLOW, so a symlink inside the working root that points+ // outside it (e.g. ./notes -> ~/.ssh/id_rsa) would otherwise be read+ // transparently, bypassing the working-directory confinement that the+ // bash denylist enforces for direct credential reads. The caller must+ // operate on the real target file instead.if info.Mode()&os.ModeSymlink != 0 {- info, err = root.Stat(rel)- if err != nil {- return nil, rootPathError(err)- }+ return nil, fmt.Errorf("%s is a symlink; read the target file directly", path)}if err := rejectNonRegularFile(path, info); err != nil {return nil, errdiff --git a/agent/tools/file_test.go b/agent/tools/file_test.goindex 396f84d22..34567c74a 100644--- a/agent/tools/file_test.go+++ b/agent/tools/file_test.go@@ -188,6 +188,47 @@ func TestReadDefaultsToEntireFile(t *testing.T) {}}+func TestReadAllowsAbsolutePath(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "note.txt")+ content := "one\ntwo\nthree\n"+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {+ t.Fatal(err)+ }++ result, err := (&Read{}).Execute(context.Background(), agent.ToolContext{WorkingDir: t.TempDir()}, map[string]any{+ "path": path,+ })+ if err != nil {+ t.Fatal(err)+ }+ if result.Content != content {+ t.Fatalf("content = %q", result.Content)+ }+}++func TestReadRejectsAbsoluteSymlink(t *testing.T) {+ dir := t.TempDir()+ target := filepath.Join(dir, "target.txt")+ if err := os.WriteFile(target, []byte("hello\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ link := filepath.Join(dir, "alias")+ if err := os.Symlink(target, link); err != nil {+ t.Skipf("symlinks unavailable: %v", err)+ }++ _, err := (&Read{}).Execute(context.Background(), agent.ToolContext{WorkingDir: t.TempDir()}, map[string]any{+ "path": link,+ })+ if err == nil {+ t.Fatal("expected absolute symlink to be rejected")+ }+ if !strings.Contains(err.Error(), "symlink") {+ t.Fatalf("err = %v, want symlink rejection", err)+ }+}+func TestReadStartEnd(t *testing.T) {dir := t.TempDir()if err := os.WriteFile(filepath.Join(dir, "note.txt"), []byte("one\ntwo\nthree\nfour\n"), 0o644); err != nil {diff --git a/agent/tools/file_unix_test.go b/agent/tools/file_unix_test.goindex 88203eef2..a0973abc2 100644--- a/agent/tools/file_unix_test.go+++ b/agent/tools/file_unix_test.go@@ -23,7 +23,7 @@ func TestOpenRegularFileRejectsFIFO(t *testing.T) {done := make(chan error, 1)go func() {- file, _, err := openRegularFile(dir, "pipe")+ file, _, err := openRegularFile(dir, "pipe", false)if file != nil {file.Close()}@@ -73,3 +73,49 @@ func TestEditPreservesModeDespiteUmask(t *testing.T) {t.Fatalf("mode = %#o, want 0666", got)}}++func TestReadRejectsSymlinkEscapingWorkingDir(t *testing.T) {+ root := t.TempDir()+ secret := filepath.Join(t.TempDir(), "secret.txt")+ if err := os.WriteFile(secret, []byte("top secret\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ link := filepath.Join(root, "notes")+ if err := os.Symlink(secret, link); err != nil {+ t.Fatal(err)+ }++ _, err := (&Read{}).Execute(context.Background(), agent.ToolContext{WorkingDir: root}, map[string]any{+ "path": "notes",+ })+ if err == nil {+ t.Fatal("expected symlink escaping working dir to be rejected")+ }+ if !strings.Contains(err.Error(), "symlink") {+ t.Fatalf("err = %v, want symlink rejection", err)+ }+}++func TestReadRejectsSymlinkInsideWorkingDirToOutside(t *testing.T) {+ root := t.TempDir()+ target := filepath.Join(root, "real.txt")+ if err := os.WriteFile(target, []byte("hello\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ // A symlink to a sibling file still resolves inside the root; Read must+ // reject it regardless, consistent with Edit's rejectFinalSymlink.+ link := filepath.Join(root, "alias")+ if err := os.Symlink(target, link); err != nil {+ t.Fatal(err)+ }++ _, err := (&Read{}).Execute(context.Background(), agent.ToolContext{WorkingDir: root}, map[string]any{+ "path": "alias",+ })+ if err == nil {+ t.Fatal("expected symlink to be rejected even when target is inside root")+ }+ if !strings.Contains(err.Error(), "symlink") {+ t.Fatalf("err = %v, want symlink rejection", err)+ }+}diff --git a/agent/tools/web.go b/agent/tools/web.goindex 92288a5d9..1e819489d 100644--- a/agent/tools/web.go+++ b/agent/tools/web.go@@ -76,7 +76,7 @@ func (w *WebSearch) Execute(ctx context.Context, _ agent.ToolContext, args map[sif err != nil {var authErr api.AuthorizationErrorif errors.As(err, &authErr) {- return agent.ToolResult{}, ErrWebSearchAuthRequired+ return agent.ToolResult{}, fmt.Errorf("%w: %s", ErrWebSearchAuthRequired, authErr)}return agent.ToolResult{}, err}@@ -140,9 +140,13 @@ func (w *WebFetch) Execute(ctx context.Context, _ agent.ToolContext, args map[stif !ok || strings.TrimSpace(urlStr) == "" {return agent.ToolResult{}, fmt.Errorf("url parameter is required")}- if _, err := url.Parse(urlStr); err != nil {+ parsed, err := url.Parse(urlStr)+ if err != nil {return agent.ToolResult{}, fmt.Errorf("invalid URL: %w", err)}+ if scheme := strings.ToLower(parsed.Scheme); scheme != "http" && scheme != "https" {+ return agent.ToolResult{}, fmt.Errorf("unsupported URL scheme %q: only http and https are allowed", parsed.Scheme)+ }client, err := api.ClientFromEnvironment()if err != nil {@@ -156,7 +160,7 @@ func (w *WebFetch) Execute(ctx context.Context, _ agent.ToolContext, args map[stif err != nil {var authErr api.AuthorizationErrorif errors.As(err, &authErr) {- return agent.ToolResult{}, ErrWebFetchAuthRequired+ return agent.ToolResult{}, fmt.Errorf("%w: %s", ErrWebFetchAuthRequired, authErr)}return agent.ToolResult{}, err}diff --git a/agent/tools/web_test.go b/agent/tools/web_test.goindex acd2bcf05..da155ce08 100644--- a/agent/tools/web_test.go+++ b/agent/tools/web_test.go@@ -20,6 +20,35 @@ func TestWebToolsRequireApproval(t *testing.T) {}}+func TestWebFetchRejectsUnsupportedScheme(t *testing.T) {+ tests := []struct {+ name string+ url string+ wantErr bool+ }{+ {name: "file scheme", url: "file:///etc/passwd", wantErr: true},+ {name: "data scheme", url: "data:text/plain,secret", wantErr: true},+ {name: "ftp scheme", url: "ftp://example.com/secret", wantErr: true},+ {name: "http allowed", url: "http://example.com", wantErr: false},+ {name: "https allowed", url: "https://example.com", wantErr: false},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ _, err := (&WebFetch{}).Execute(t.Context(), coreagent.ToolContext{}, map[string]any{"url": tt.url})+ if tt.wantErr && err == nil {+ t.Fatal("expected unsupported scheme to be rejected")+ }+ // For allowed schemes we expect an error only from the missing+ // server/auth path, not from scheme validation. The http/https+ // cases reach the client and may fail on connection/auth; we only+ // assert that the error is NOT a scheme error.+ if !tt.wantErr && err != nil && strings.Contains(err.Error(), "unsupported URL scheme") {+ t.Fatalf("http/https rejected as unsupported: %v", err)+ }+ })+ }+}+func TestWebFetchBoundsContentBeforeReturning(t *testing.T) {ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.URL.Path != "/api/experimental/web_fetch" {diff --git a/cmd/agent_tui.go b/cmd/agent_tui.gonew file mode 100644index 000000000..9f9f7c1bb--- /dev/null+++ b/cmd/agent_tui.go@@ -0,0 +1,829 @@+package cmd++import (+ "context"+ "errors"+ "fmt"+ "net/http"+ "os"+ "runtime"+ "slices"+ "strconv"+ "strings"+ "time"++ "github.com/spf13/cobra"++ coreagent "github.com/ollama/ollama/agent"+ agenttools "github.com/ollama/ollama/agent/tools"+ "github.com/ollama/ollama/api"+ "github.com/ollama/ollama/cmd/config"+ "github.com/ollama/ollama/cmd/launch"+ agentchat "github.com/ollama/ollama/cmd/tui/chat"+ "github.com/ollama/ollama/format"+ internalcloud "github.com/ollama/ollama/internal/cloud"+ "github.com/ollama/ollama/internal/modelref"+ "github.com/ollama/ollama/types/model"+)++type agentTUIOptions struct {+ Model string+ OpenModelPicker bool+ System string+ Format string+ Options map[string]any+ Think *api.ThinkValue+ KeepAlive *api.Duration+ ContextWindowTokens int+ AllowAllTools bool+ ToolsDisabled bool+ MultiModal bool+}++func registerAgentFlags(cmd *cobra.Command) {+ cmd.Flags().String("model", "", "Model to use")+ cmd.Flags().String("keepalive", "", "Duration to keep a model loaded (e.g. 5m)")+ cmd.Flags().String("format", "", "Response format (e.g. json)")+ cmd.Flags().String("think", "", "Enable thinking mode: true/false or high/medium/low for supported models")+ cmd.Flags().Lookup("think").NoOptDefVal = "true"+ cmd.Flags().Bool("auto-approve-tools", false, "Allow agent tools to run without prompting")+ cmd.Flags().Bool("yolo", false, "Alias for --auto-approve-tools")+ cmd.Flags().Bool("no-tools", false, "Disable agent tools")+}++func AgentHandler(cmd *cobra.Command, _ []string) error {+ opts := agentTUIOptions{+ Model: strings.TrimSpace(config.LastModel()),+ Options: map[string]any{},+ }+ thinkExplicit, err := applyAgentFlags(cmd, &opts)+ if err != nil {+ return err+ }++ if strings.TrimSpace(opts.Model) == "" {+ opts.OpenModelPicker = true+ } else if cmd.Flags().Lookup("model") == nil || !cmd.Flags().Lookup("model").Changed {+ opts.OpenModelPicker = true+ }++ client, err := api.ClientFromEnvironment()+ if err != nil {+ return err+ }++ if opts.OpenModelPicker {+ modelName, err := selectAgentModel(cmd.Context(), client, opts.Model)+ if errors.Is(err, launch.ErrCancelled) {+ return nil+ }+ if err != nil {+ return err+ }+ opts.Model = modelName+ opts.OpenModelPicker = false+ }++ if strings.TrimSpace(opts.Model) != "" {+ info, err := prepareAgentModel(cmd, client, &opts, thinkExplicit)+ if err != nil {+ if handleCloudAuthorizationError(err) {+ return nil+ }+ return err+ }+ opts.System = info.System+ if err := saveLastAgentModel(opts.Model); err != nil {+ return err+ }+ }++ if err := GenerateAgentTUI(cmd, client, opts); err != nil {+ if handleCloudAuthorizationError(err) {+ return nil+ }+ return fmt.Errorf("error running agent: %w", err)+ }+ return nil+}++func applyAgentFlags(cmd *cobra.Command, opts *agentTUIOptions) (bool, error) {+ if flag := cmd.Flags().Lookup("model"); flag != nil && flag.Changed {+ modelName, err := cmd.Flags().GetString("model")+ if err != nil {+ return false, err+ }+ modelName = strings.TrimSpace(modelName)+ if modelName == "" {+ return false, errors.New("--model cannot be empty")+ }+ opts.Model = modelName+ opts.OpenModelPicker = false+ }++ format, err := cmd.Flags().GetString("format")+ if err != nil {+ return false, err+ }+ opts.Format = format++ thinkExplicit := false+ thinkFlag := cmd.Flags().Lookup("think")+ if thinkFlag != nil && thinkFlag.Changed {+ thinkExplicit = true+ thinkStr, err := cmd.Flags().GetString("think")+ if err != nil {+ return false, err+ }+ switch thinkStr {+ case "", "true":+ opts.Think = &api.ThinkValue{Value: true}+ case "false":+ opts.Think = &api.ThinkValue{Value: false}+ case "high", "medium", "low", "max":+ opts.Think = &api.ThinkValue{Value: thinkStr}+ default:+ return false, fmt.Errorf("invalid value for --think: %q (must be true, false, high, medium, low, or max)", thinkStr)+ }+ }++ keepAlive, err := cmd.Flags().GetString("keepalive")+ if err != nil {+ return false, err+ }+ if keepAlive != "" {+ d, err := time.ParseDuration(keepAlive)+ if err != nil {+ return false, err+ }+ opts.KeepAlive = &api.Duration{Duration: d}+ }++ autoApprove, err := cmd.Flags().GetBool("auto-approve-tools")+ if err != nil {+ return false, err+ }+ yolo, err := cmd.Flags().GetBool("yolo")+ if err != nil {+ return false, err+ }+ opts.AllowAllTools = autoApprove || yolo+ toolsDisabled, err := cmd.Flags().GetBool("no-tools")+ if err != nil {+ return false, err+ }+ opts.ToolsDisabled = toolsDisabled+ return thinkExplicit, nil+}++func saveLastAgentModel(model string) error {+ model = strings.TrimSpace(model)+ if model == "" {+ return nil+ }+ return config.SetLastModel(model)+}++func prepareAgentModel(cmd *cobra.Command, client *api.Client, opts *agentTUIOptions, thinkExplicit bool) (*api.ShowResponse, error) {+ requestedCloud := modelref.HasExplicitCloudSource(opts.Model)+ info, err := func() (*api.ShowResponse, error) {+ info, err := client.Show(cmd.Context(), &api.ShowRequest{Model: opts.Model})+ var se api.StatusError+ if errors.As(err, &se) && se.StatusCode == http.StatusNotFound {+ if requestedCloud {+ return nil, err+ }+ if err := PullHandler(cmd, []string{opts.Model}); err != nil {+ return nil, err+ }+ return client.Show(cmd.Context(), &api.ShowRequest{Model: opts.Model})+ }+ return info, err+ }()+ if err != nil {+ return nil, err+ }++ ensureCloudStub(cmd.Context(), client, opts.Model)+ opts.Think, err = inferThinkingOption(&info.Capabilities, &runOptions{Model: opts.Model, Think: opts.Think}, thinkExplicit)+ if err != nil {+ return nil, err+ }+ opts.MultiModal = showResponseSupportsMultimodal(info)+ opts.ContextWindowTokens = showResponseContextWindow(info)+ return info, nil+}++func GenerateAgentTUI(cmd *cobra.Command, client *api.Client, opts agentTUIOptions) error {+ cwd, err := os.Getwd()+ if err != nil {+ cwd = ""+ }+ contextWindowForModel := func(ctx context.Context, model string, fallback int) int {+ return agentContextWindowForModel(ctx, client, model, fallback)+ }++ var registry *coreagent.Registry+ registryForModel := func(ctx context.Context, model string) *coreagent.Registry {+ return agentToolsRegistry(ctx, client, model)+ }+ if opts.Model != "" {+ registry = agentToolsRegistry(cmd.Context(), client, opts.Model)+ }+ systemPrompt := agentSystemPrompt(opts.Model, opts.System, "")++ _, err = agentchat.Run(cmd.Context(), agentchat.Options{+ Model: opts.Model,+ Client: client,+ Tools: registry,+ ToolRegistryForModel: registryForModel,+ ToolsDisabled: opts.ToolsDisabled,+ MultiModalForModel: func(ctx context.Context, model string) bool {+ return agentModelSupportsMultimodal(ctx, client, model)+ },+ ModelOptions: func(ctx context.Context) ([]agentchat.ModelOption, error) {+ return agentModelOptions(ctx, client)+ },+ OnModelSelected: func(_ context.Context, model string) error {+ return config.SetLastModel(model)+ },+ SystemPromptForModel: func(ctx context.Context, model string, registry *coreagent.Registry) string {+ return agentSystemPrompt(model, agentSystemFromShow(ctx, client, model), "")+ },+ SystemPrompt: systemPrompt,+ WorkingDir: cwd,+ Format: opts.Format,+ Options: opts.Options,+ Think: opts.Think,+ KeepAlive: opts.KeepAlive,+ MultiModal: opts.MultiModal,+ AllowAllTools: opts.AllowAllTools,+ ContextWindowTokens: opts.ContextWindowTokens,+ Compactor: &coreagent.SimpleCompactor{+ Client: client,+ Options: coreagent.CompactionOptions{ContextWindowTokens: opts.ContextWindowTokens},+ },+ ContextWindowTokensForModel: func(ctx context.Context, model string, fallback int) int {+ return contextWindowForModel(ctx, model, fallback)+ },+ PreloadModel: func(ctx context.Context, model string, think *api.ThinkValue) (int, error) {+ return preloadAgentModelIfLocal(ctx, client, opts, model, think)+ },+ CheckCloudModel: func(ctx context.Context, model, requiredPlan string) error {+ return ensureCloudModelAccess(ctx, client, model, requiredPlan)+ },+ OpenBrowser: launch.OpenBrowser,+ PollCloudAuth: func(ctx context.Context) (string, bool, error) {+ user, err := client.Whoami(ctx)+ if err != nil {+ return "", false, err+ }+ if user == nil || user.Name == "" {+ return "", false, nil+ }+ return user.Name, true, nil+ },+ })+ return err+}++func selectAgentModel(ctx context.Context, client *api.Client, current string) (string, error) {+ models, err := agentModelOptions(ctx, client)+ if err != nil {+ return "", err+ }+ if len(models) == 0 {+ return "", errors.New("no models available, run 'ollama pull <model>' first")+ }++ items := agentSelectionItems(models)+ switch {+ case launch.DefaultSingleSelectorWithUpdates != nil:+ return launch.DefaultSingleSelectorWithUpdates("Select model to run:", items, current, nil)+ case launch.DefaultSingleSelector != nil:+ return launch.DefaultSingleSelector("Select model to run:", items, current)+ default:+ return "", errors.New("no selector configured")+ }+}++func agentSelectionItems(models []agentchat.ModelOption) []launch.SelectionItem {+ items := make([]launch.SelectionItem, 0, len(models))+ for _, model := range models {+ items = append(items, launch.SelectionItem{+ Name: model.Name,+ Description: agentSelectionDescription(model),+ Recommended: model.Recommended,+ AvailabilityBadge: model.AvailabilityBadge,+ })+ }+ return items+}++func agentSelectionDescription(model agentchat.ModelOption) string {+ return strings.TrimSpace(model.Description)+}++func agentSystemPrompt(modelName string, modelSystem string, extra string) string {+ return agentSystemPromptAt(time.Now(), modelName, modelSystem, extra)+}++func agentSystemPromptAt(now time.Time, modelName string, modelSystem string, extra string) string {+ var parts []string+ parts = append(parts, agentDefaultSystemPrompt(now, modelName))+ if strings.TrimSpace(modelSystem) != "" {+ parts = append(parts, strings.TrimSpace(modelSystem))+ }+ if strings.TrimSpace(extra) != "" {+ parts = append(parts, strings.TrimSpace(extra))+ }+ return strings.Join(parts, "\n\n")+}++func agentDefaultSystemPrompt(now time.Time, modelName string) string {+ date := now.Format("Monday, January 2, 2006")+ shellName := "bash"+ if runtime.GOOS == "windows" {+ shellName = "PowerShell"+ }+ return strings.Join([]string{+ "You are running in Ollama, in a harness to help the user accomplish tasks, and the model is " + modelName + ".",+ "",+ "Current date: " + date + ".",+ "",+ "Be concise, practical, and action-oriented. Use tools when they materially help. Verify current or fast-changing facts with web tools when available; otherwise state uncertainty.",+ "",+ "Use " + shellName + " carefully. Prefer read-only inspection first. Stay within the current working directory unless explicitly asked. Surface intent before risky actions such as writes, deletes, moves, installs, git state changes, service changes, sudo, secrets access, network scripts, or commands outside the working directory. Request approval when required and do not work around denied approvals.",+ "",+ "Tell the user about meaningful changes, verification, failures, blockers, assumptions, and risks. Summarize routine tool output instead of dumping it.",+ }, "\n")+}++func agentSystemFromShow(ctx context.Context, client *api.Client, modelName string) string {+ if client == nil || strings.TrimSpace(modelName) == "" {+ return ""+ }+ resp, err := client.Show(ctx, &api.ShowRequest{Model: modelName})+ if err != nil {+ fmt.Fprintf(os.Stderr, "\033[1mwarning:\033[0m could not load model system prompt: %v\n", err)+ return ""+ }+ return resp.System+}++func agentToolsRegistry(ctx context.Context, client *api.Client, modelName string) *coreagent.Registry {+ supportsTools, err := agentModelSupportsTools(ctx, client, modelName)+ if err != nil {+ fmt.Fprintf(os.Stderr, "\033[1mwarning:\033[0m could not check model capabilities: %v\n", err)+ }+ if !supportsTools {+ return nil+ }++ registry := &coreagent.Registry{}+ if os.Getenv("OLLAMA_AGENT_DISABLE_SHELL") == "" {+ registry.Register(&agenttools.Bash{})+ }+ registry.Register(&agenttools.Read{})+ registry.Register(&agenttools.Edit{})++ if os.Getenv("OLLAMA_AGENT_DISABLE_WEBSEARCH") == "" {+ if disabled, known := agentCloudStatusDisabled(ctx, client); !known || !disabled {+ registry.Register(&agenttools.WebSearch{})+ registry.Register(&agenttools.WebFetch{})+ } else {+ fmt.Fprintf(os.Stderr, "%s\n", internalcloud.DisabledError("web search is unavailable"))+ }+ }+ return registry+}++func agentModelSupportsTools(ctx context.Context, client *api.Client, modelName string) (bool, error) {+ if client == nil || strings.TrimSpace(modelName) == "" {+ return false, nil+ }+ resp, err := client.Show(ctx, &api.ShowRequest{Model: modelName})+ if err != nil {+ return false, err+ }+ return slices.Contains(resp.Capabilities, model.CapabilityTools), nil+}++func agentModelSupportsMultimodal(ctx context.Context, client *api.Client, modelName string) bool {+ if client == nil || strings.TrimSpace(modelName) == "" {+ return false+ }+ resp, err := client.Show(ctx, &api.ShowRequest{Model: modelName})+ if err != nil {+ fmt.Fprintf(os.Stderr, "\033[1mwarning:\033[0m could not check model capabilities: %v\n", err)+ return false+ }+ return showResponseSupportsMultimodal(resp)+}++func showResponseSupportsMultimodal(resp *api.ShowResponse) bool {+ if resp == nil {+ return false+ }+ if slices.Contains(resp.Capabilities, model.CapabilityVision) || slices.Contains(resp.Capabilities, model.CapabilityAudio) {+ return true+ }+ if len(resp.ProjectorInfo) != 0 {+ return true+ }+ for key := range resp.ModelInfo {+ if strings.Contains(key, ".vision.") {+ return true+ }+ }+ return false+}++func agentContextWindowForModel(ctx context.Context, client *api.Client, modelName string, fallback int) int {+ if client == nil || strings.TrimSpace(modelName) == "" {+ return fallback+ }+ if tokens := loadedContextWindowForModel(ctx, client, modelName); tokens > 0 {+ return tokens+ }+ if modelref.HasExplicitCloudSource(modelName) {+ if tokens := agentRecommendationContextWindowForModel(ctx, client, modelName); tokens > 0 {+ return tokens+ }+ }+ resp, err := client.Show(ctx, &api.ShowRequest{Model: modelName})+ if err != nil {+ return fallback+ }+ if tokens := showResponseContextWindow(resp); tokens > 0 {+ return tokens+ }+ return fallback+}++func agentRecommendationContextWindowForModel(ctx context.Context, client *api.Client, modelName string) int {+ if client == nil {+ return 0+ }+ recs, err := client.ModelRecommendationsExperimental(ctx)+ if err != nil || recs == nil {+ return 0+ }+ return contextWindowFromRecommendations(modelName, recs.Recommendations)+}++func contextWindowFromRecommendations(modelName string, recommendations []api.ModelRecommendation) int {+ for _, rec := range recommendations {+ if rec.ContextLength <= 0 {+ continue+ }+ if sameModelRef(modelName, rec.Model) {+ return rec.ContextLength+ }+ }+ return 0+}++func sameModelRef(a, b string) bool {+ a = comparableModelRef(a)+ b = comparableModelRef(b)+ if strings.EqualFold(a, b) {+ return true+ }+ pa, errA := modelref.ParseRef(a)+ pb, errB := modelref.ParseRef(b)+ if errA != nil || errB != nil {+ return false+ }+ if !strings.EqualFold(pa.Base, pb.Base) {+ return false+ }+ return pa.Source == pb.Source ||+ pa.Source == modelref.ModelSourceUnspecified ||+ pb.Source == modelref.ModelSourceUnspecified+}++func comparableModelRef(value string) string {+ value = strings.TrimSpace(value)+ if strings.HasSuffix(strings.ToLower(value), ":latest") {+ return strings.TrimSpace(value[:len(value)-len(":latest")])+ }+ return value+}++func showResponseContextWindow(resp *api.ShowResponse) int {+ if resp == nil {+ return 0+ }+ if resp.Details.ContextLength > 0 {+ return resp.Details.ContextLength+ }+ if n, ok := numericModelInfo(resp.ModelInfo["general.context_length"]); ok {+ return n+ }+ best := 0+ for key, value := range resp.ModelInfo {+ if key != "context_length" && !strings.HasSuffix(key, ".context_length") {+ continue+ }+ if n, ok := numericModelInfo(value); ok && n > best {+ best = n+ }+ }+ return best+}++func numericModelInfo(value any) (int, bool) {+ switch v := value.(type) {+ case int:+ return v, v > 0+ case int32:+ return int(v), v > 0+ case int64:+ return int(v), v > 0+ case uint:+ return int(v), v > 0+ case uint32:+ return int(v), v > 0+ case uint64:+ return int(v), v > 0+ case float64:+ return int(v), v > 0+ case string:+ n, err := strconv.Atoi(strings.TrimSpace(v))+ return n, err == nil && n > 0+ default:+ return 0, false+ }+}++func preloadAgentModelIfLocal(ctx context.Context, client *api.Client, opts agentTUIOptions, modelName string, think *api.ThinkValue) (int, error) {+ modelName = strings.TrimSpace(modelName)+ if client == nil || modelName == "" {+ return 0, nil+ }+ if modelref.HasExplicitCloudSource(modelName) {+ return 0, nil+ }+ info, err := client.Show(ctx, &api.ShowRequest{Model: modelName})+ if err != nil {+ return 0, err+ }+ if info.RemoteHost != "" {+ return 0, nil+ }+ if err := client.Generate(ctx, &api.GenerateRequest{+ Model: modelName,+ KeepAlive: opts.KeepAlive,+ Options: opts.Options,+ Think: think,+ }, func(api.GenerateResponse) error {+ return nil+ }); err != nil {+ return 0, err+ }+ return loadedContextWindowForModel(ctx, client, modelName), nil+}++func loadedContextWindowForModel(ctx context.Context, client *api.Client, modelName string) int {+ if client == nil || strings.TrimSpace(modelName) == "" {+ return 0+ }+ resp, err := client.ListRunning(ctx)+ if err != nil {+ return 0+ }+ return processContextWindowForModel(modelName, resp)+}++func processContextWindowForModel(modelName string, resp *api.ProcessResponse) int {+ if resp == nil {+ return 0+ }+ for _, running := range resp.Models {+ if running.ContextLength <= 0 {+ continue+ }+ if sameModelRef(modelName, running.Name) || sameModelRef(modelName, running.Model) {+ return running.ContextLength+ }+ }+ return 0+}++func agentModelOptions(ctx context.Context, client *api.Client) ([]agentchat.ModelOption, error) {+ if client == nil {+ return nil, errors.New("model picker requires an API client")+ }++ list, err := client.List(ctx)+ if err != nil {+ return nil, err+ }++ seen := make(map[string]struct{})+ var options []agentchat.ModelOption+ add := func(name, description string, recommended bool, requiredPlan string, cloud bool) {+ name = strings.TrimSpace(name)+ if name == "" {+ return+ }+ key := strings.ToLower(name)+ if _, ok := seen[key]; ok {+ return+ }+ seen[key] = struct{}{}+ options = append(options, agentchat.ModelOption{+ Name: name,+ Description: strings.TrimSpace(description),+ Recommended: recommended,+ RequiredPlan: requiredPlan,+ Cloud: cloud,+ })+ }++ if disabled, known := agentCloudStatusDisabled(ctx, client); !known || !disabled {+ if recs, err := client.ModelRecommendationsExperimental(ctx); err == nil {+ for _, rec := range recs.Recommendations {+ name := strings.TrimSpace(rec.Model)+ if !modelref.HasExplicitCloudSource(name) {+ continue+ }+ add(name, agentRecommendationDescription(rec), true, strings.TrimSpace(rec.RequiredPlan), true)+ }+ }+ }++ local := slices.Clone(list.Models)+ slices.SortStableFunc(local, func(a, b api.ListModelResponse) int {+ return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name))+ })+ for _, model := range local {+ name := strings.TrimSpace(model.Name)+ if name == "" {+ name = strings.TrimSpace(model.Model)+ }+ name = strings.TrimSuffix(name, ":latest")+ if modelref.HasExplicitCloudSource(name) {+ add(name, agentCloudModelDescription(model), false, "", true)+ continue+ }+ add(name, agentLocalModelDescription(model), false, "", false)+ }++ badges, signInURLs := cloudAvailabilityBadges(ctx, client, options)+ for i := range options {+ options[i].AvailabilityBadge = badges[options[i].Name]+ options[i].SignInURL = signInURLs[options[i].Name]+ }+ return options, nil+}++func cloudAvailabilityBadges(ctx context.Context, client *api.Client, options []agentchat.ModelOption) (map[string]string, map[string]string) {+ badges := make(map[string]string)+ signInURLs := make(map[string]string)+ hasCloud := false+ for _, opt := range options {+ if opt.Cloud {+ hasCloud = true+ break+ }+ }+ if !hasCloud {+ return badges, signInURLs+ }++ if disabled, known := agentCloudStatusDisabled(ctx, client); known && disabled {+ return badges, signInURLs+ }++ whoamiCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ defer cancel()+ user, err := client.Whoami(whoamiCtx)+ if err != nil {+ var authErr api.AuthorizationError+ signInURL := ""+ if errors.As(err, &authErr) && (authErr.StatusCode == http.StatusUnauthorized || authErr.SigninURL != "") {+ if authErr.SigninURL != "" {+ signInURL = authErr.SigninURL+ }+ } else {+ return badges, signInURLs+ }+ for _, opt := range options {+ if opt.Cloud {+ badges[opt.Name] = "Sign in required"+ if signInURL != "" {+ signInURLs[opt.Name] = signInURL+ }+ }+ }+ return badges, signInURLs+ }++ signedIn := user != nil && user.Name != ""+ for _, opt := range options {+ if !opt.Cloud {+ continue+ }+ if !signedIn {+ badges[opt.Name] = "Sign in required"+ } else if opt.RequiredPlan != "" && !launch.PlanSatisfies(user.Plan, opt.RequiredPlan) {+ badges[opt.Name] = "Upgrade required"+ }+ }+ return badges, signInURLs+}++func agentRecommendationDescription(rec api.ModelRecommendation) string {+ var parts []string+ if description := strings.TrimSpace(rec.Description); description != "" {+ parts = append(parts, description)+ } else {+ parts = append(parts, "cloud")+ }+ if rec.ContextLength > 0 {+ parts = append(parts, format.HumanNumber(uint64(rec.ContextLength))+" ctx")+ }+ return strings.Join(parts, " - ")+}++func agentLocalModelDescription(model api.ListModelResponse) string {+ desc := agentModelArchDescription(model)+ if desc == "" {+ return "local"+ }+ return "local - " + desc+}++func agentCloudModelDescription(model api.ListModelResponse) string {+ return agentModelArchDescription(model)+}++func agentModelArchDescription(model api.ListModelResponse) string {+ var details []string+ if model.Details.Family != "" {+ details = append(details, model.Details.Family)+ }+ if ps := humanizedParameterSize(model.Details.ParameterSize); ps != "" {+ details = append(details, ps)+ }+ if model.Details.QuantizationLevel != "" {+ details = append(details, model.Details.QuantizationLevel)+ }+ var parts []string+ if len(details) > 0 {+ parts = append(parts, strings.Join(details, " "))+ }+ if model.Details.ContextLength > 0 {+ parts = append(parts, format.HumanNumber(uint64(model.Details.ContextLength))+" ctx")+ }+ return strings.Join(parts, " - ")+}++func humanizedParameterSize(s string) string {+ s = strings.TrimSpace(s)+ if s == "" {+ return ""+ }+ if f, err := strconv.ParseFloat(s, 64); err == nil {+ return format.HumanNumber(uint64(f))+ }+ return s+}++func agentCloudStatusDisabled(ctx context.Context, client *api.Client) (disabled bool, known bool) {+ if internalcloud.Disabled() {+ return true, true+ }++ status, err := client.CloudStatusExperimental(ctx)+ if err != nil {+ var statusErr api.StatusError+ if errors.As(err, &statusErr) && statusErr.StatusCode == http.StatusNotFound {+ return false, false+ }+ return false, false+ }+ return status.Cloud.Disabled, true+}++func ensureCloudModelAccess(ctx context.Context, client *api.Client, modelName, requiredPlan string) error {+ if client == nil {+ return errors.New("no API client available")+ }+ if disabled, known := agentCloudStatusDisabled(ctx, client); known && disabled {+ return errors.New("remote inference is unavailable")+ }+ user, err := client.Whoami(ctx)+ if err != nil {+ return err+ }+ if user != nil && user.Name != "" {+ if requiredPlan != "" && !launch.PlanSatisfies(user.Plan, requiredPlan) {+ return fmt.Errorf("plan upgrade required: %s needs plan %s, you have %s", modelName, requiredPlan, user.Plan)+ }+ return nil+ }+ return fmt.Errorf("%s requires sign in", modelName)+}diff --git a/cmd/agent_tui_test.go b/cmd/agent_tui_test.gonew file mode 100644index 000000000..fd783e870--- /dev/null+++ b/cmd/agent_tui_test.go@@ -0,0 +1,99 @@+package cmd++import (+ "testing"++ "github.com/spf13/cobra"++ "github.com/ollama/ollama/api"+ "github.com/ollama/ollama/cmd/config"+ agentchat "github.com/ollama/ollama/cmd/tui/chat"+)++func TestAgentSelectionItemsUseLaunchSections(t *testing.T) {+ items := agentSelectionItems([]agentchat.ModelOption{+ {Name: "glm-5.2:cloud", Description: "cloud", Recommended: true, Cloud: true},+ {Name: "llama3.2", Description: "local"},+ })++ if len(items) != 2 {+ t.Fatalf("items = %d, want 2", len(items))+ }+ if !items[0].Recommended {+ t.Fatalf("cloud recommendation should be pinned: %#v", items[0])+ }+ if items[1].Recommended {+ t.Fatalf("local selected model should stay in launch More section: %#v", items[1])+ }+ if items[1].Description != "local" {+ t.Fatalf("selected model description = %q, want plain description", items[1].Description)+ }+}++func TestContextWindowFromRecommendationsMatchesCloudModel(t *testing.T) {+ got := contextWindowFromRecommendations("glm-5.2:cloud", []api.ModelRecommendation{+ {Model: "gemma4:cloud", ContextLength: 32768},+ {Model: "glm-5.2:cloud", ContextLength: 1048576},+ })+ if got != 1048576 {+ t.Fatalf("context window = %d, want 1048576", got)+ }+}++func TestShowResponseContextWindowReadsArchitectureContextLength(t *testing.T) {+ got := showResponseContextWindow(&api.ShowResponse{+ ModelInfo: map[string]any{+ "qwen3.context_length": uint32(262144),+ "qwen3.rope.scaling.original_context_length": uint32(32768),+ },+ })+ if got != 262144 {+ t.Fatalf("context window = %d, want 262144", got)+ }+}++func TestProcessContextWindowForModelMatchesLatestAlias(t *testing.T) {+ got := processContextWindowForModel("ornith", &api.ProcessResponse{+ Models: []api.ProcessModelResponse{+ {Name: "other:latest", Model: "other:latest", ContextLength: 32768},+ {Name: "ornith:latest", Model: "ornith:latest", ContextLength: 262144},+ },+ })+ if got != 262144 {+ t.Fatalf("context window = %d, want 262144", got)+ }+}++func TestSaveLastAgentModel(t *testing.T) {+ setCmdTestHome(t, t.TempDir())++ if err := saveLastAgentModel(" qwen3:8b "); err != nil {+ t.Fatalf("saveLastAgentModel returned error: %v", err)+ }+ if got := config.LastModel(); got != "qwen3:8b" {+ t.Fatalf("last model = %q, want qwen3:8b", got)+ }++ if err := saveLastAgentModel(" "); err != nil {+ t.Fatalf("saveLastAgentModel blank returned error: %v", err)+ }+ if got := config.LastModel(); got != "qwen3:8b" {+ t.Fatalf("blank save changed last model to %q", got)+ }+}++func TestApplyAgentFlagsNoTools(t *testing.T) {+ cmd := &cobra.Command{}+ registerAgentFlags(cmd)+ if err := cmd.Flags().Set("no-tools", "true"); err != nil {+ t.Fatal(err)+ }++ var opts agentTUIOptions+ if _, err := applyAgentFlags(cmd, &opts); err != nil {+ t.Fatalf("applyAgentFlags returned error: %v", err)+ }+ if !opts.ToolsDisabled {+ t.Fatal("--no-tools should disable tools")+ }+}diff --git a/cmd/cmd.go b/cmd/cmd.goindex 4396dc061..cc1689bb2 100644--- a/cmd/cmd.go+++ b/cmd/cmd.go@@ -2132,72 +2132,32 @@ func ensureServerRunning(ctx context.Context) error {}func launchInteractiveModel(cmd *cobra.Command, modelName string) error {- opts := runOptions{- Model: modelName,- WordWrap: os.Getenv("TERM") == "xterm-256color",- Options: map[string]any{},- ShowConnect: true,- }-client, err := api.ClientFromEnvironment()if err != nil {return err}- requestedCloud := modelref.HasExplicitCloudSource(modelName)-- info, err := func() (*api.ShowResponse, error) {- showReq := &api.ShowRequest{Name: modelName}- info, err := client.Show(cmd.Context(), showReq)- var se api.StatusError- if errors.As(err, &se) && se.StatusCode == http.StatusNotFound {- if requestedCloud {- return nil, err- }- if err := PullHandler(cmd, []string{modelName}); err != nil {- return nil, err- }- return client.Show(cmd.Context(), &api.ShowRequest{Name: modelName})- }- return info, err- }()+ opts := agentTUIOptions{+ Model: modelName,+ Options: map[string]any{},+ }+ info, err := prepareAgentModel(cmd, client, &opts, false)if err != nil {if handleCloudAuthorizationError(err) {return nil}return err}+ opts.System = info.System- ensureCloudStub(cmd.Context(), client, modelName)-- opts.Think, err = inferThinkingOption(&info.Capabilities, &opts, false)- if err != nil {+ if err := saveLastAgentModel(opts.Model); err != nil {return err}-- audioCapable := slices.Contains(info.Capabilities, model.CapabilityAudio)- opts.MultiModal = slices.Contains(info.Capabilities, model.CapabilityVision) || audioCapable-- // TODO: remove the projector info and vision info checks below,- // these are left in for backwards compatibility with older servers- // that don't have the capabilities field in the model info- if len(info.ProjectorInfo) != 0 {- opts.MultiModal = true- }- for k := range info.ModelInfo {- if strings.Contains(k, ".vision.") {- opts.MultiModal = true- break+ if err := GenerateAgentTUI(cmd, client, opts); err != nil {+ if handleCloudAuthorizationError(err) {+ return nil}- }-- applyShowResponseToRunOptions(&opts, info)-- if err := loadOrUnloadModel(cmd, &opts); err != nil {- return fmt.Errorf("error loading model: %w", err)- }- if err := generateInteractive(cmd, opts); err != nil {- return fmt.Errorf("error running model: %w", err)+ return fmt.Errorf("error running agent: %w", err)}return nil}@@ -2409,6 +2369,15 @@ func NewCLI() *cobra.Command {runCmd.Flags().Bool("imagegen", false, "Use the imagegen runner for LLM inference")runCmd.Flags().MarkHidden("imagegen")+ agentCmd := &cobra.Command{+ Use: "agent",+ Short: "Run an agent",+ Args: cobra.ExactArgs(0),+ PreRunE: checkServerHeartbeat,+ RunE: AgentHandler,+ }+ registerAgentFlags(agentCmd)+stopCmd := &cobra.Command{Use: "stop MODEL",Short: "Stop a running model",@@ -2539,6 +2508,7 @@ func NewCLI() *cobra.Command {createCmd,showCmd,runCmd,+ agentCmd,stopCmd,pullCmd,pushCmd,@@ -2586,6 +2556,7 @@ func NewCLI() *cobra.Command {createCmd,showCmd,runCmd,+ agentCmd,stopCmd,pullCmd,pushCmd,diff --git a/cmd/internal/filedata/filedata.go b/cmd/internal/filedata/filedata.gonew file mode 100644index 000000000..257fb609a--- /dev/null+++ b/cmd/internal/filedata/filedata.go@@ -0,0 +1,189 @@+package filedata++import (+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "os"+ "path/filepath"+ "regexp"+ "slices"+ "strings"++ "github.com/ollama/ollama/api"+)++type File struct {+ Path string+ Data api.ImageData+}++func NormalizePath(fp string) string {+ fp = strings.Trim(fp, "\"")+ fp = strings.NewReplacer(+ "\\ ", " ",+ "\\(", "(",+ "\\)", ")",+ "\\[", "[",+ "\\]", "]",+ "\\{", "{",+ "\\}", "}",+ "\\$", "$",+ "\\&", "&",+ "\\;", ";",+ "\\'", "'",+ "\\\\", "\\",+ "\\*", "*",+ "\\?", "?",+ "\\~", "~",+ ).Replace(fp)++ if u, err := url.Parse(fp); err == nil && strings.EqualFold(u.Scheme, "file") {+ return normalizeFileURL(u)+ } else if normalized, ok := normalizeMalformedFileURL(fp); ok {+ return normalized+ }++ return fp+}++// fileExtractRe matches file:// URLs and filesystem paths ending in image/audio+// extensions. Hoisted to package scope so the per-keystroke slash-completion+// path (chat.slashInputIsMultimodalFile -> ExtractNames) doesn't recompile it+// on every call.+var fileExtractRe = regexp.MustCompile(`(?:file://\S+?\.(?i:jpg|jpeg|png|webp|wav)\b)|(?:(?:[a-zA-Z]:)?(?:\./|\.\\|/|\\)[\S\\ ]+?\.(?i:jpg|jpeg|png|webp|wav)\b)`)++func ExtractNames(input string) []string {+ return fileExtractRe.FindAllString(input, -1)+}++func Extract(input string) (string, []api.ImageData, error) {+ cleaned, files, err := ExtractWithFiles(input)+ if err != nil {+ return "", nil, err+ }+ data := make([]api.ImageData, 0, len(files))+ for _, file := range files {+ data = append(data, file.Data)+ }+ return cleaned, data, nil+}++func ExtractWithFiles(input string) (string, []File, error) {+ filePaths := ExtractNames(input)+ var files []File++ for _, fp := range filePaths {+ nfp := NormalizePath(fp)+ data, err := GetData(nfp)+ if errors.Is(err, os.ErrNotExist) {+ continue+ } else if err != nil {+ return "", nil, fmt.Errorf("couldn't process file %q: %w", nfp, err)+ }+ input = strings.ReplaceAll(input, "'"+nfp+"'", "")+ input = strings.ReplaceAll(input, "'"+fp+"'", "")+ input = strings.ReplaceAll(input, `"`+nfp+`"`, "")+ input = strings.ReplaceAll(input, `"`+fp+`"`, "")+ input = strings.ReplaceAll(input, fp, "")+ files = append(files, File{Path: nfp, Data: data})+ }+ return strings.TrimSpace(input), files, nil+}++func GetData(filePath string) ([]byte, error) {+ file, err := os.Open(filePath)+ if err != nil {+ return nil, err+ }+ defer file.Close()++ buf := make([]byte, 512)+ _, err = file.Read(buf)+ if err != nil {+ return nil, err+ }++ contentType := http.DetectContentType(buf)+ allowedTypes := []string{"image/jpeg", "image/jpg", "image/png", "image/webp", "audio/wave"}+ if !slices.Contains(allowedTypes, contentType) {+ return nil, fmt.Errorf("invalid file type: %s", contentType)+ }++ info, err := file.Stat()+ if err != nil {+ return nil, err+ }++ var maxSize int64 = 100 * 1024 * 1024+ if info.Size() > maxSize {+ return nil, errors.New("file size exceeds maximum limit (100MB)")+ }++ buf = make([]byte, info.Size())+ _, err = file.Seek(0, 0)+ if err != nil {+ return nil, err+ }++ _, err = io.ReadFull(file, buf)+ if err != nil {+ return nil, err+ }++ return buf, nil+}++func Kind(path string) string {+ if strings.EqualFold(filepath.Ext(path), ".wav") {+ return "audio"+ }+ return "image"+}++func normalizeFileURL(u *url.URL) string {+ path := u.Path+ if unescaped, err := url.PathUnescape(path); err == nil {+ path = unescaped+ }+ host := u.Host+ if unescaped, err := url.PathUnescape(host); err == nil {+ host = unescaped+ }+ if len(host) >= 2 && host[1] == ':' && isASCIIAlpha(host[0]) {+ return filepath.Clean(filepath.FromSlash(host + path))+ }+ if len(path) >= 4 && path[0] == '/' && path[2] == ':' && isASCIIAlpha(path[1]) {+ path = path[1:]+ }+ if u.Host != "" && !strings.EqualFold(u.Host, "localhost") {+ return `\\` + u.Host + filepath.FromSlash(path)+ }+ return filepath.FromSlash(path)+}++func normalizeMalformedFileURL(raw string) (string, bool) {+ const prefix = "file://"+ if !strings.HasPrefix(strings.ToLower(raw), prefix) {+ return "", false+ }++ path := raw[len(prefix):]+ if unescaped, err := url.PathUnescape(path); err == nil {+ path = unescaped+ }+ path = strings.TrimPrefix(path, "localhost")+ if len(path) >= 3 && path[0] == '/' && path[2] == ':' && isASCIIAlpha(path[1]) {+ path = path[1:]+ }+ if len(path) >= 2 && path[1] == ':' && isASCIIAlpha(path[0]) {+ return filepath.Clean(filepath.FromSlash(path)), true+ }+ return "", false+}++func isASCIIAlpha(b byte) bool {+ return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')+}diff --git a/cmd/internal/filedata/filedata_test.go b/cmd/internal/filedata/filedata_test.gonew file mode 100644index 000000000..0ce801a1b--- /dev/null+++ b/cmd/internal/filedata/filedata_test.go@@ -0,0 +1,223 @@+package filedata++import (+ "net/url"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestNormalizePathMalformedWindowsFileURL(t *testing.T) {+ got := NormalizePath(`file://C:%5CUsers%5Cjdoe%5CPictures%5Cimg.png`)+ want := filepath.Clean(`C:\Users\jdoe\Pictures\img.png`)+ if got != want {+ t.Fatalf("path = %q, want %q", got, want)+ }+}++func TestNormalizePathTwoSlashWindowsFileURL(t *testing.T) {+ got := NormalizePath(`file://C:/Users/jdoe/Pictures/img.png`)+ want := filepath.Clean(`C:/Users/jdoe/Pictures/img.png`)+ if got != want {+ t.Fatalf("path = %q, want %q", got, want)+ }+}++func TestNormalizePathLocalhostWindowsFileURL(t *testing.T) {+ got := NormalizePath(`file://localhost/C:/Users/jdoe/Pictures/img.png`)+ want := filepath.Clean(`C:/Users/jdoe/Pictures/img.png`)+ if got != want {+ t.Fatalf("path = %q, want %q", got, want)+ }+}++func TestExtractNames(t *testing.T) {+ // Unix style paths+ input := ` some preamble+ ./relative\ path/one.png inbetween1 ./not a valid two.jpg inbetween2 ./1.svg+/unescaped space /three.jpeg inbetween3 /valid\ path/dir/four.png "./quoted with spaces/five.JPG+/unescaped space /six.webp inbetween6 /valid\ path/dir/seven.WEBP`+ res := ExtractNames(input)+ if len(res) != 7 {+ t.Fatalf("len = %d, want 7", len(res))+ }+ assertContains(t, res[0], "one.png")+ assertContains(t, res[1], "two.jpg")+ assertContains(t, res[2], "three.jpeg")+ assertContains(t, res[3], "four.png")+ assertContains(t, res[4], "five.JPG")+ assertContains(t, res[5], "six.webp")+ assertContains(t, res[6], "seven.WEBP")+ assertNotContains(t, res[4], "\"")+ for _, r := range res {+ assertNotContains(t, r, "inbetween1")+ }+ assertNotContainsSlice(t, res, "./1.svg")+}++func TestExtractNamesWindowsPaths(t *testing.T) {+ input := ` some preamble+ c:/users/jdoe/one.png inbetween1 c:/program files/someplace/two.jpg inbetween2+ /absolute/nospace/three.jpeg inbetween3 /absolute/with space/four.png inbetween4+./relative\ path/five.JPG inbetween5 "./relative with/spaces/six.png inbetween6+d:\path with\spaces\seven.JPEG inbetween7 c:\users\jdoe\eight.png inbetween8+ d:\program files\someplace\nine.png inbetween9 "E:\program files\someplace\ten.PNG+c:/users/jdoe/eleven.webp inbetween11 c:/program files/someplace/twelve.WebP inbetween12+d:\path with\spaces\thirteen.WEBP some ending+`+ res := ExtractNames(input)+ if len(res) != 13 {+ t.Fatalf("len = %d, want 13", len(res))+ }+ assertNotContainsSlice(t, res, "inbetween2")+ assertContains(t, res[0], "one.png")+ assertContains(t, res[0], "c:")+ assertContains(t, res[1], "two.jpg")+ assertContains(t, res[1], "c:")+ assertContains(t, res[2], "three.jpeg")+ assertContains(t, res[3], "four.png")+ assertContains(t, res[4], "five.JPG")+ assertContains(t, res[5], "six.png")+ assertContains(t, res[6], "seven.JPEG")+ assertContains(t, res[6], "d:")+ assertContains(t, res[7], "eight.png")+ assertContains(t, res[7], "c:")+ assertContains(t, res[8], "nine.png")+ assertContains(t, res[8], "d:")+ assertContains(t, res[9], "ten.PNG")+ assertContains(t, res[9], "E:")+ assertContains(t, res[10], "eleven.webp")+ assertContains(t, res[10], "c:")+ assertContains(t, res[11], "twelve.WebP")+ assertContains(t, res[11], "c:")+ assertContains(t, res[12], "thirteen.WEBP")+ assertContains(t, res[12], "d:")+}++func TestExtractNamesDragDropPaths(t *testing.T) {+ input := `file:///Users/jdoe/Pictures/one.png file://localhost/C:/Users/jdoe/Pictures/two.webp file:///C:/Users/jdoe/Pictures/three.jpg .\relative\four.png`+ res := ExtractNames(input)+ if len(res) != 4 {+ t.Fatalf("len = %d, want 4", len(res))+ }+ assertContains(t, res[0], "file:///Users/jdoe/Pictures/one.png")+ assertContains(t, res[1], "file://localhost/C:/Users/jdoe/Pictures/two.webp")+ assertContains(t, res[2], "file:///C:/Users/jdoe/Pictures/three.jpg")+ assertContains(t, res[3], `.\relative\four.png`)+}++func TestNormalizePathFileURL(t *testing.T) {+ got := NormalizePath("file:///C:/Users/jdoe/Pictures/img.png")+ want := filepath.FromSlash("C:/Users/jdoe/Pictures/img.png")+ if got != want {+ t.Fatalf("path = %q, want %q", got, want)+ }+}++func TestExtractRemovesQuotedFilepath(t *testing.T) {+ dir := t.TempDir()+ fp := filepath.Join(dir, "img.jpg")+ data := make([]byte, 600)+ copy(data, []byte{+ 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 'J', 'F', 'I', 'F',+ 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0xff, 0xd9,+ })+ if err := os.WriteFile(fp, data, 0o600); err != nil {+ t.Fatalf("failed to write test image: %v", err)+ }++ input := "before '" + fp + "' after"+ cleaned, imgs, err := Extract(input)+ if err != nil {+ t.Fatalf("err: %v", err)+ }+ if len(imgs) != 1 {+ t.Fatalf("imgs = %d, want 1", len(imgs))+ }+ if cleaned != "before after" {+ t.Fatalf("cleaned = %q, want %q", cleaned, "before after")+ }+}++func TestExtractFileURL(t *testing.T) {+ dir := t.TempDir()+ fp := filepath.Join(dir, "img.png")+ data := make([]byte, 600)+ copy(data, []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'})+ if err := os.WriteFile(fp, data, 0o600); err != nil {+ t.Fatalf("failed to write test image: %v", err)+ }++ fileURL := (&url.URL{Scheme: "file", Path: fp}).String()+ cleaned, imgs, err := Extract("before " + fileURL + " after")+ if err != nil {+ t.Fatalf("err: %v", err)+ }+ if len(imgs) != 1 {+ t.Fatalf("imgs = %d, want 1", len(imgs))+ }+ if cleaned != "before after" {+ t.Fatalf("cleaned = %q, want %q", cleaned, "before after")+ }+}++func TestExtractWAV(t *testing.T) {+ dir := t.TempDir()+ fp := filepath.Join(dir, "sample.wav")+ data := make([]byte, 600)+ copy(data[:44], []byte{+ 'R', 'I', 'F', 'F',+ 0x58, 0x02, 0x00, 0x00,+ 'W', 'A', 'V', 'E',+ 'f', 'm', 't', ' ',+ 0x10, 0x00, 0x00, 0x00,+ 0x01, 0x00,+ 0x01, 0x00,+ 0x80, 0x3e, 0x00, 0x00,+ 0x00, 0x7d, 0x00, 0x00,+ 0x02, 0x00,+ 0x10, 0x00,+ 'd', 'a', 't', 'a',+ 0x34, 0x02, 0x00, 0x00,+ })+ if err := os.WriteFile(fp, data, 0o600); err != nil {+ t.Fatalf("failed to write test audio: %v", err)+ }++ input := "before " + fp + " after"+ cleaned, imgs, err := Extract(input)+ if err != nil {+ t.Fatalf("err: %v", err)+ }+ if len(imgs) != 1 {+ t.Fatalf("imgs = %d, want 1", len(imgs))+ }+ if cleaned != "before after" {+ t.Fatalf("cleaned = %q, want %q", cleaned, "before after")+ }+}++func assertContains(t *testing.T, s, want string) {+ t.Helper()+ if !strings.Contains(s, want) {+ t.Fatalf("%q does not contain %q", s, want)+ }+}++func assertNotContains(t *testing.T, s, want string) {+ t.Helper()+ if strings.Contains(s, want) {+ t.Fatalf("%q unexpectedly contains %q", s, want)+ }+}++func assertNotContainsSlice(t *testing.T, ss []string, want string) {+ t.Helper()+ for _, s := range ss {+ if strings.Contains(s, want) {+ t.Fatalf("slice unexpectedly contains %q in %q", want, s)+ }+ }+}diff --git a/cmd/launch/account.go b/cmd/launch/account.goindex 1471e1f08..9de432d0c 100644--- a/cmd/launch/account.go+++ b/cmd/launch/account.go@@ -20,7 +20,7 @@ const ()var (- ErrPlanVerificationUnavailable = errors.New("Could not verify your plan. Try again in a moment.")+ ErrPlanVerificationUnavailable = errors.New("Could not verify Ollama plan. Try again in a moment or use a local model.")errUpgradeCancelled = errors.New("upgrade cancelled"))@@ -247,7 +247,7 @@ func (c *launcherClient) ensureCloudModelAccess(ctx context.Context, model strinc.accountState = &state}if state.Status == accountStateUnknown {- return ErrPlanVerificationUnavailable+ return nil}if state.Status == accountStateSignedOut {@@ -259,7 +259,7 @@ func (c *launcherClient) ensureCloudModelAccess(ctx context.Context, model strinc.accountState = &state}if state.Status == accountStateUnknown {- return ErrPlanVerificationUnavailable+ return nil}}diff --git a/cmd/launch/integrations_test.go b/cmd/launch/integrations_test.goindex a6e1a238f..274836243 100644--- a/cmd/launch/integrations_test.go+++ b/cmd/launch/integrations_test.go@@ -1081,6 +1081,51 @@ func TestShowOrPullWithPolicy_CloudModelNotFound_FailsEarlyForAllPolicies(t *tes}}+func TestShowOrPullWithPolicy_CloudModelShowUnavailableAllowsSelection(t *testing.T) {+ oldHook := DefaultConfirmPrompt+ DefaultConfirmPrompt = func(prompt string, options ConfirmOptions) (bool, error) {+ t.Fatal("confirm prompt should not be called for explicit cloud models")+ return false, nil+ }+ defer func() { DefaultConfirmPrompt = oldHook }()++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api/show":+ w.WriteHeader(http.StatusInternalServerError)+ fmt.Fprintf(w, `{"error":"temporary failure"}`)+ case "/api/status":+ w.WriteHeader(http.StatusInternalServerError)+ fmt.Fprintf(w, `{"error":"temporary failure"}`)+ case "/api/pull":+ t.Fatal("pull should not be called for explicit cloud models")+ default:+ w.WriteHeader(http.StatusNotFound)+ }+ }))+ defer srv.Close()++ u, _ := url.Parse(srv.URL)+ client := api.NewClient(u, srv.Client())++ if err := showOrPullWithPolicy(context.Background(), client, "glm-5.1:cloud", missingModelFail, true); err != nil {+ t.Fatalf("showOrPullWithPolicy returned error: %v", err)+ }+}++func TestShowOrPullWithPolicy_CloudModelShowUnreachableAllowsSelection(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ t.Fatalf("unexpected request after server close: %s %s", r.Method, r.URL.Path)+ }))+ u, _ := url.Parse(srv.URL)+ client := api.NewClient(u, srv.Client())+ srv.Close()++ if err := showOrPullWithPolicy(context.Background(), client, "glm-5.1:cloud", missingModelFail, true); err != nil {+ t.Fatalf("showOrPullWithPolicy returned error: %v", err)+ }+}+func TestShowOrPullWithPolicy_CloudModelDisabled_FailsWithCloudDisabledError(t *testing.T) {oldHook := DefaultConfirmPromptDefaultConfirmPrompt = func(prompt string, options ConfirmOptions) (bool, error) {diff --git a/cmd/launch/launch_test.go b/cmd/launch/launch_test.goindex a23328a93..2a986c667 100644--- a/cmd/launch/launch_test.go+++ b/cmd/launch/launch_test.go@@ -2215,7 +2215,7 @@ func TestResolveRunModel_UpgradeCancelledReturnsToModelSelector(t *testing.T) {}}-func TestResolveRunModel_SubscriptionModelUnavailableWhoamiFailsGracefully(t *testing.T) {+func TestResolveRunModel_SubscriptionModelUnavailableWhoamiAllowsSelection(t *testing.T) {tmpDir := t.TempDir()setLaunchTestHome(t, tmpDir)withLauncherHooks(t)@@ -2237,6 +2237,8 @@ func TestResolveRunModel_SubscriptionModelUnavailableWhoamiFailsGracefully(t *tecase "/api/status":w.WriteHeader(http.StatusNotFound)fmt.Fprint(w, `{"error":"not found"}`)+ case "/api/show":+ fmt.Fprint(w, `{"remote_model":"kimi-k2.6"}`)case "/api/me":w.WriteHeader(http.StatusInternalServerError)fmt.Fprint(w, `{"error":"temporary failure"}`)@@ -2247,12 +2249,12 @@ func TestResolveRunModel_SubscriptionModelUnavailableWhoamiFailsGracefully(t *tedefer srv.Close()t.Setenv("OLLAMA_HOST", srv.URL)- _, err := ResolveRunModel(context.Background(), RunModelRequest{ForcePicker: true})- if err == nil {- t.Fatal("expected plan verification error")+ model, err := ResolveRunModel(context.Background(), RunModelRequest{ForcePicker: true})+ if err != nil {+ t.Fatalf("ResolveRunModel returned error: %v", err)}- if !strings.Contains(err.Error(), "Could not verify your plan. Try again in a moment.") {- t.Fatalf("unexpected error: %v", err)+ if model != "kimi-k2.6:cloud" {+ t.Fatalf("expected selected cloud model, got %q", model)}}diff --git a/cmd/launch/models.go b/cmd/launch/models.goindex c9e554ec8..37afb6c62 100644--- a/cmd/launch/models.go+++ b/cmd/launch/models.go@@ -194,10 +194,10 @@ func ensureCloudAuth(ctx context.Context, client *api.Client, modelList string)}var aErr api.AuthorizationError- if !errors.As(err, &aErr) || aErr.SigninURL == "" {- if err != nil {- return err- }+ if err != nil && !errors.As(err, &aErr) {+ return nil+ }+ if err == nil || aErr.SigninURL == "" {return fmt.Errorf("%s requires sign in", modelList)}@@ -258,19 +258,23 @@ func showOrPullWithPolicy(ctx context.Context, client *api.Client, model string,if _, err := client.Show(ctx, &api.ShowRequest{Model: model}); err == nil {return nil} else {+ if isCloudModel {+ if disabled, known := cloudStatusDisabled(ctx, client); known && disabled {+ return errors.New(internalcloud.DisabledError("remote inference is unavailable"))+ }+ var statusErr api.StatusError+ if errors.As(err, &statusErr) && statusErr.StatusCode == http.StatusNotFound {+ return fmt.Errorf("model %q not found", model)+ }+ return nil+ }+var statusErr api.StatusErrorif !errors.As(err, &statusErr) || statusErr.StatusCode != http.StatusNotFound {return err}}- if isCloudModel {- if disabled, known := cloudStatusDisabled(ctx, client); known && disabled {- return errors.New(internalcloud.DisabledError("remote inference is unavailable"))- }- return fmt.Errorf("model %q not found", model)- }-switch policy {case missingModelAutoPull:return pullMissingModel(ctx, client, model)diff --git a/cmd/tui/chat/approval.go b/cmd/tui/chat/approval.gonew file mode 100644index 000000000..9281f5557--- /dev/null+++ b/cmd/tui/chat/approval.go@@ -0,0 +1,402 @@+package chat++import (+ "context"+ "fmt"+ "slices"+ "strings"+ "time"++ tea "github.com/charmbracelet/bubbletea"++ coreagent "github.com/ollama/ollama/agent"+)++type chatApprovalChoice struct {+ label string+ key string+ allow bool+ allowTools bool+ allowAll bool+ reason string+}++var chatApprovalChoices = []chatApprovalChoice{+ {label: "Approve once", key: "1", allow: true},+ {label: "Always allow tool", key: "2", allow: true, allowTools: true},+ {label: "Deny", key: "3", reason: "Tool execution denied."},+}++type chatApprovalPrompt struct {+ request coreagent.ApprovalRequest+ reply chan<- coreagent.Approval+ cursor int+}++func (m chatModel) approvalPrompterForRun(controller *chatApprovalController) coreagent.ApprovalPrompter {+ if m.opts.ApprovalPrompter != nil {+ return m.opts.ApprovalPrompter+ }+ return controller+}++func (m *chatModel) ensureApprovalState() *coreagent.ApprovalState {+ if m.approvalState == nil {+ m.approvalState = &coreagent.ApprovalState{}+ m.approvalState.Set(m.defaultAllowAll, nil)+ }+ return m.approvalState+}++func (m *chatModel) resetApprovalState() {+ m.approvalState = &coreagent.ApprovalState{}+ m.approvalState.Set(m.defaultAllowAll, nil)+}++func (m chatModel) allowAllToolsEnabled() bool {+ if m.approvalState == nil {+ return m.defaultAllowAll+ }+ return m.approvalState.AllowAll()+}++func (m *chatModel) setAllowAllTools(allowAll bool) {+ m.ensureApprovalState().SetAllowAll(allowAll)+ m.opts.AllowAllTools = allowAll+}++func (m *chatModel) openApprovalPrompt(msg chatApprovalPromptMsg) {+ m.approvalPrompt = &chatApprovalPrompt{request: msg.request, reply: msg.reply}+ m.status = "approval required"+ m.thinking = false+ m.thinkingTokens = 0+ m.upsertApprovalToolEntries(msg.request)+}++func (m *chatModel) togglePermissionMode() (tea.Model, tea.Cmd) {+ m.setAllowAllTools(!m.allowAllToolsEnabled())+ if m.allowAllToolsEnabled() {+ m.permissionNotice = "full access enabled"+ m.status = "full access enabled"+ if m.approvalPrompt != nil {+ updated, cmd := m.resolveApprovalPrompt(chatApprovalChoice{allow: true, allowAll: true})+ if model, ok := updated.(chatModel); ok {+ model.permissionNotice = "full access enabled"+ model.status = "full access enabled"+ return model, cmd+ }+ return updated, cmd+ }+ return *m, nil+ }+ m.permissionNotice = "review mode enabled"+ m.status = "review mode enabled"+ return *m, nil+}++func (m *chatModel) upsertApprovalToolEntries(request coreagent.ApprovalRequest) {+ for _, call := range request.Calls {+ idx := m.findToolEntry(call.ToolCallID)+ if idx < 0 {+ m.groupCompletedToolHistory()+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "tool"}))+ idx = len(m.entries) - 1+ }+ m.entries[idx].detail = call.ToolName+ m.entries[idx].label = toolInvocationLabel(call.ToolName, call.Args)+ m.entries[idx].status = "approval"+ m.entries[idx].toolID = call.ToolCallID+ m.entries[idx].args = call.Args+ m.entries[idx].startedAt = time.Now()+ m.applyToolOutputModeTo(idx)+ m.markEntryDirty(idx)+ }+}++func (m chatModel) updateApprovalPrompt(msg tea.KeyMsg) (tea.Model, tea.Cmd) {+ switch msg.Type {+ case tea.KeyLeft, tea.KeyUp:+ m.moveApprovalChoice(-1)+ case tea.KeyRight, tea.KeyDown, tea.KeyTab:+ m.moveApprovalChoice(1)+ case tea.KeyRunes:+ switch string(msg.Runes) {+ case "1", "2", "3":+ choice := chatApprovalChoices[int(msg.Runes[0]-'1')]+ return m.resolveApprovalPrompt(choice)+ }+ case tea.KeyEnter:+ choice := chatApprovalChoices[clamp(m.approvalPrompt.cursor, 0, len(chatApprovalChoices)-1)]+ return m.resolveApprovalPrompt(choice)+ case tea.KeyEsc, tea.KeyCtrlC:+ return m.resolveApprovalPrompt(chatApprovalChoice{reason: "Tool execution denied."})+ }+ return m, nil+}++func (m *chatModel) moveApprovalChoice(delta int) {+ if m.approvalPrompt == nil {+ return+ }+ m.approvalPrompt.cursor = (m.approvalPrompt.cursor + delta) % len(chatApprovalChoices)+ if m.approvalPrompt.cursor < 0 {+ m.approvalPrompt.cursor += len(chatApprovalChoices)+ }+ m.markApprovalPromptEntryDirty()+}++func (m *chatModel) markApprovalPromptEntryDirty() {+ if m.approvalPrompt == nil {+ return+ }+ for _, call := range m.approvalPrompt.request.Calls {+ if idx := m.findToolEntry(call.ToolCallID); idx >= 0 {+ m.markEntryDirty(idx)+ }+ }+}++func (m chatModel) resolveApprovalPrompt(choice chatApprovalChoice) (tea.Model, tea.Cmd) {+ if m.approvalPrompt == nil {+ return m, nil+ }+ printedLines := m.flowPrintedLines+ var printedTranscript []string+ if printedLines > 0 {+ printedTranscript = slices.Clone(m.transcriptLines(m.viewWidth()))+ }+ prompt := m.approvalPrompt+ m.approvalPrompt = nil+ m.status = "running"+ if !choice.allow {+ m.status = "denied"+ }+ if choice.allowAll {+ m.setAllowAllTools(true)+ }+ allowScopes := approvalScopes(prompt.request)+ if choice.allowTools {+ m.ensureApprovalState().AllowScopes(allowScopes)+ }+ for _, call := range prompt.request.Calls {+ if idx := m.findToolEntry(call.ToolCallID); idx >= 0 && m.entries[idx].status == "approval" {+ if !choice.allow {+ m.entries[idx].status = "error"+ m.entries[idx].err = choice.reason+ if m.entries[idx].err == "" {+ m.entries[idx].err = "Tool execution denied."+ }+ } else {+ m.entries[idx].status = "queued"+ }+ m.markEntryDirty(idx)+ }+ }+ result := coreagent.Approval{Allow: choice.allow, AllowAll: choice.allowAll, Reason: choice.reason}+ if choice.allowTools {+ result.AllowScopes = allowScopes+ }+ prompt.reply <- result+ return m.withFlowTranscriptRefreshAfter(printedTranscript, printedLines, waitForChatMsg(m.events))+}++func (m chatModel) renderApprovalPromptLines(width int) []string {+ prompt := m.approvalPrompt+ if prompt == nil {+ return nil+ }+ if width <= 0 {+ width = 80+ }+ bodyWidth := max(20, width-2)++ var lines []string+ if len(prompt.request.Calls) <= 1 {+ detail := approvalRequestDetail(prompt.request, bodyWidth)+ if detail == "" {+ label := "Tool request"+ if len(prompt.request.Calls) == 1 {+ label = toolDisplayName(prompt.request.Calls[0].ToolName)+ }+ lines = append(lines, wrapChatText(fmt.Sprintf("%s wants to run", label), width)...)+ } else {+ lines = append(lines, indentLines(splitRenderedBody(detail), " ")...)+ }+ lines = append(lines, "")+ }++ lines = append(lines, indentLines(renderApprovalChoices(prompt.request, prompt.cursor, bodyWidth), " ")...)+ return lines+}++func approvalRequestDetail(request coreagent.ApprovalRequest, width int) string {+ if len(request.Calls) == 0 {+ return ""+ }+ if len(request.Calls) == 1 {+ return approvalToolCallDetail(request.Calls[0], width)+ }+ lines := make([]string, 0, len(request.Calls))+ for _, call := range request.Calls {+ lines = append(lines, toolInvocationLabel(call.ToolName, call.Args))+ }+ return chatMetaStyle.Render(strings.Join(lines, "\n"))+}++func approvalToolCallDetail(call coreagent.ApprovalToolCall, width int) string {+ if isShellToolName(call.ToolName) {+ command, ok := rawStringArg(call.Args, "command")+ if !ok {+ return ""+ }+ return strings.Join(wrapChatText(shellPromptPrefix(call.ToolName)+command, width), "\n")+ }+ switch call.ToolName {+ case "edit":+ path, ok := rawStringArg(call.Args, "path")+ if !ok {+ return ""+ }+ var lines []string+ lines = append(lines, "path: "+path)+ if oldText, ok := rawStringArg(call.Args, "old_text"); ok {+ lines = append(lines, fmt.Sprintf("old_text: %d chars", len([]rune(oldText))))+ }+ if newText, ok := rawStringArg(call.Args, "new_text"); ok {+ lines = append(lines, fmt.Sprintf("new_text: %d chars", len([]rune(newText))))+ }+ return chatMetaStyle.Render(strings.Join(lines, "\n"))+ default:+ if len(call.Args) == 0 {+ return ""+ }+ return strings.Join(renderToolCallArgs(call.Args, width), "\n")+ }+}++func renderApprovalChoices(request coreagent.ApprovalRequest, cursor int, width int) []string {+ var lines []string+ for i, choice := range chatApprovalChoices {+ label := choice.key + ". " + approvalChoiceLabel(choice, request)+ wrapped := wrapChatText(label, max(20, width-2))+ if i == clamp(cursor, 0, len(chatApprovalChoices)-1) {+ for j, line := range wrapped {+ if j == 0 {+ lines = append(lines, chatPickerSelectedStyle.Render("> "+line))+ } else {+ lines = append(lines, chatPickerSelectedStyle.Render(" "+line))+ }+ }+ } else {+ for _, line := range wrapped {+ lines = append(lines, chatPickerTextStyle.Render(" "+line))+ }+ }+ }+ return lines+}++func approvalChoiceLabel(choice chatApprovalChoice, request coreagent.ApprovalRequest) string {+ if !choice.allowTools {+ return choice.label+ }+ scopes := approvalScopes(request)+ if len(scopes) == 1 {+ call := approvalCallForScope(request, scopes[0])+ if isShellToolName(call.ToolName) {+ if command, ok := rawStringArg(call.Args, "command"); ok && strings.TrimSpace(command) != "" {+ return "Always allow this command"+ }+ }+ return "Always allow " + toolDisplayName(call.ToolName)+ }+ return "Always allow these requests"+}++func approvalScopes(request coreagent.ApprovalRequest) []string {+ seen := make(map[string]bool, len(request.Calls))+ var scopes []string+ for _, call := range request.Calls {+ scope := approvalScope(call)+ if scope == "" || seen[scope] {+ continue+ }+ seen[scope] = true+ scopes = append(scopes, scope)+ }+ return scopes+}++func approvalCallForScope(request coreagent.ApprovalRequest, scope string) coreagent.ApprovalToolCall {+ for _, call := range request.Calls {+ if approvalScope(call) == scope {+ return call+ }+ }+ return coreagent.ApprovalToolCall{}+}++func approvalScope(call coreagent.ApprovalToolCall) string {+ if scope := strings.TrimSpace(call.ApprovalScope); scope != "" {+ return scope+ }+ return strings.TrimSpace(call.ToolName)+}++type chatApprovalPrompter struct {+ ch chan<- tea.Msg+}++func (p chatApprovalPrompter) PromptApproval(ctx context.Context, request coreagent.ApprovalRequest) (coreagent.Approval, error) {+ reply := make(chan coreagent.Approval, 1)+ select {+ case p.ch <- chatApprovalPromptMsg{request: request, reply: reply}:+ case <-ctx.Done():+ return coreagent.Approval{Reason: "Tool approval canceled."}, nil+ }++ select {+ case result := <-reply:+ return result, nil+ case <-ctx.Done():+ return coreagent.Approval{Reason: "Tool approval canceled."}, nil+ }+}++type chatApprovalController struct {+ ch chan<- tea.Msg+ state *coreagent.ApprovalState+}++func newChatApprovalController(ch chan<- tea.Msg, state *coreagent.ApprovalState) *chatApprovalController {+ return &chatApprovalController{+ ch: ch,+ state: state,+ }+}++func (c *chatApprovalController) PromptApproval(ctx context.Context, request coreagent.ApprovalRequest) (coreagent.Approval, error) {+ if result, ok := c.preapproved(request); ok {+ return result, nil+ }+ return chatApprovalPrompter{ch: c.ch}.PromptApproval(ctx, request)+}++func (c *chatApprovalController) preapproved(request coreagent.ApprovalRequest) (coreagent.Approval, bool) {+ if c == nil {+ return coreagent.Approval{}, false+ }+ if c.state.AllowAll() {+ return coreagent.Approval{Allow: true, AllowAll: true}, true+ }+ scopes := approvalScopes(request)+ if len(scopes) == 0 {+ return coreagent.Approval{}, false+ }+ for _, scope := range scopes {+ if !c.state.Allows(scope) {+ return coreagent.Approval{}, false+ }+ }+ return coreagent.Approval{Allow: true, AllowScopes: scopes}, true+}diff --git a/cmd/tui/chat/approval_test.go b/cmd/tui/chat/approval_test.gonew file mode 100644index 000000000..1dc0e323f--- /dev/null+++ b/cmd/tui/chat/approval_test.go@@ -0,0 +1,495 @@+package chat++import (+ "context"+ "strings"+ "testing"+ "time"++ tea "github.com/charmbracelet/bubbletea"++ coreagent "github.com/ollama/ollama/agent"+)++func testApprovalRequest() coreagent.ApprovalRequest {+ return coreagent.ApprovalRequest{+ WorkingDir: "/repo",+ Calls: []coreagent.ApprovalToolCall{{+ ToolCallID: "call-1",+ ToolName: "edit",+ Args: map[string]any{"path": "note.txt"},+ ApprovalScope: "edit",+ }},+ }+}++func testApprovalState(allowAll bool, scopes map[string]bool) *coreagent.ApprovalState {+ state := &coreagent.ApprovalState{}+ state.Set(allowAll, scopes)+ return state+}++func TestChatApprovalApprovesOnce(t *testing.T) {+ reply := make(chan coreagent.Approval, 1)+ m := chatModel{+ approvalPrompt: &chatApprovalPrompt{+ request: testApprovalRequest(),+ reply: reply,+ },+ events: make(chan tea.Msg),+ }++ updated, cmd := m.updateApprovalPrompt(tea.KeyMsg{Type: tea.KeyEnter})+ if cmd == nil {+ t.Fatal("approval should resume waiting for agent events")+ }+ fm := updated.(chatModel)+ if fm.approvalPrompt != nil {+ t.Fatal("approval prompt should close")+ }+ result := <-reply+ if !result.Allow || result.AllowAll {+ t.Fatalf("approval = %#v, want allow once", result)+ }+}++func TestChatApprovalAllowsTool(t *testing.T) {+ reply := make(chan coreagent.Approval, 1)+ m := chatModel{+ approvalPrompt: &chatApprovalPrompt{+ request: testApprovalRequest(),+ reply: reply,+ cursor: 1,+ },+ events: make(chan tea.Msg),+ }++ updated, _ := m.updateApprovalPrompt(tea.KeyMsg{Type: tea.KeyEnter})+ fm := updated.(chatModel)+ if fm.allowAllToolsEnabled() {+ t.Fatal("allowing a tool should not enable full access")+ }+ if !fm.approvalState.Allows("edit") {+ t.Fatal("edit scope was not saved")+ }+ result := <-reply+ if !result.Allow || result.AllowAll || len(result.AllowScopes) != 1 || result.AllowScopes[0] != "edit" {+ t.Fatalf("approval = %#v, want per-tool approval", result)+ }+}++func TestChatApprovalLabelsSecondChoiceAsPerTool(t *testing.T) {+ lines := stripANSI(strings.Join(renderApprovalChoices(testApprovalRequest(), 1, 80), "\n"))+ if !strings.Contains(lines, "2. Always allow Edit") {+ t.Fatalf("approval choices = %q, want per-tool option", lines)+ }+ if strings.Contains(lines, "Approve all") {+ t.Fatalf("approval choices = %q, should not offer approve all as option 2", lines)+ }+}++func TestChatApprovalLabelsShellChoiceAsCommandScoped(t *testing.T) {+ request := coreagent.ApprovalRequest{+ WorkingDir: "/repo",+ Calls: []coreagent.ApprovalToolCall{{+ ToolCallID: "call-1",+ ToolName: "bash",+ Args: map[string]any{"command": "pwd"},+ ApprovalScope: "bash\x00pwd",+ }},+ }+ lines := stripANSI(strings.Join(renderApprovalChoices(request, 1, 80), "\n"))+ if !strings.Contains(lines, "2. Always allow this command") {+ t.Fatalf("approval choices = %q, want command-scoped option", lines)+ }+ if strings.Contains(lines, "Always allow Bash") {+ t.Fatalf("approval choices = %q, should not offer top-level Bash approval", lines)+ }+}++func TestChatApprovalUsesShellNameForPermissionPrompt(t *testing.T) {+ request := coreagent.ApprovalRequest{+ WorkingDir: "/repo",+ Calls: []coreagent.ApprovalToolCall{{+ ToolCallID: "call-1",+ ToolName: "bash",+ Args: map[string]any{"command": "pwd"},+ ApprovalScope: "bash\x00pwd",+ }},+ }++ detail := stripANSI(approvalRequestDetail(request, 80))+ if !strings.Contains(detail, "$ pwd") {+ t.Fatalf("approval detail should show command prompt, got %q", detail)+ }++ m := chatModel{}+ m.upsertApprovalToolEntries(request)+ if len(m.entries) != 1 {+ t.Fatalf("entries = %#v", m.entries)+ }+ line := stripANSI(toolStatusLine(m.entries[0]))+ if !strings.Contains(line, `Bash("pwd")`) || !strings.Contains(line, "needs approval") {+ t.Fatalf("approval status line = %q", line)+ }+}++func TestChatApprovalPromptOmitsDuplicateBatchDetails(t *testing.T) {+ request := coreagent.ApprovalRequest{+ WorkingDir: "/repo",+ Calls: []coreagent.ApprovalToolCall{+ {+ ToolCallID: "call-1",+ ToolName: "bash",+ Args: map[string]any{"command": "git rev-parse --abbrev-ref HEAD"},+ ApprovalScope: "bash\x00git rev-parse --abbrev-ref HEAD",+ },+ {+ ToolCallID: "call-2",+ ToolName: "bash",+ Args: map[string]any{"command": "git branch -a"},+ ApprovalScope: "bash\x00git branch -a",+ },+ },+ }+ m := chatModel{+ approvalPrompt: &chatApprovalPrompt{request: request},+ }++ lines := stripANSI(strings.Join(m.renderApprovalPromptLines(120), "\n"))+ if strings.Contains(lines, `Bash("git rev-parse --abbrev-ref HEAD")`) || strings.Contains(lines, `Bash("git branch -a")`) {+ t.Fatalf("batched approval prompt should not duplicate visible tool rows:\n%s", lines)+ }+ for _, want := range []string{"1. Approve once", "2. Always allow these requests", "3. Deny"} {+ if !strings.Contains(lines, want) {+ t.Fatalf("batched approval prompt missing %q:\n%s", want, lines)+ }+ }+}++func TestChatApprovalKeepsQueuedBatchCallsVisible(t *testing.T) {+ reply := make(chan coreagent.Approval, 1)+ request := coreagent.ApprovalRequest{+ WorkingDir: "/repo",+ Calls: []coreagent.ApprovalToolCall{+ {+ ToolCallID: "call-1",+ ToolName: "bash",+ Args: map[string]any{"command": "git rev-parse --abbrev-ref HEAD"},+ ApprovalScope: "bash\x00git rev-parse --abbrev-ref HEAD",+ },+ {+ ToolCallID: "call-2",+ ToolName: "bash",+ Args: map[string]any{"command": "git branch -a"},+ ApprovalScope: "bash\x00git branch -a",+ },+ },+ }+ m := chatModel{+ running: true,+ events: make(chan tea.Msg),+ }+ m.openApprovalPrompt(chatApprovalPromptMsg{request: request, reply: reply})++ updated, _ := m.resolveApprovalPrompt(chatApprovalChoice{allow: true})+ m = updated.(chatModel)+ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolStarted,+ ToolCallID: "call-1",+ ToolName: "bash",+ Args: request.Calls[0].Args,+ })+ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolFinished,+ ToolCallID: "call-1",+ ToolName: "bash",+ Args: request.Calls[0].Args,+ Content: "parth-agent-tui\n",+ })+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventMessageDelta, Content: "I'm on branch parth-agent-tui."})++ transcript := stripANSI(m.renderTranscript(180))+ for _, want := range []string{+ `Bash("git rev-parse --abbrev-ref HEAD")`,+ `Bash("git branch -a")`,+ "I'm on branch parth-agent-tui.",+ } {+ if !strings.Contains(transcript, want) {+ t.Fatalf("transcript missing %q:\n%s", want, transcript)+ }+ }+}++func TestChatApprovalPromptRepaintsFlowTranscript(t *testing.T) {+ reply := make(chan coreagent.Approval, 1)+ request := coreagent.ApprovalRequest{+ WorkingDir: "/repo",+ Calls: []coreagent.ApprovalToolCall{+ {+ ToolCallID: "call-1",+ ToolName: "web_fetch",+ Args: map[string]any{"url": "https://parthsareen.com/"},+ ApprovalScope: "web_fetch",+ },+ {+ ToolCallID: "call-2",+ ToolName: "web_fetch",+ Args: map[string]any{"url": "https://github.com/ParthSareen"},+ ApprovalScope: "web_fetch",+ },+ },+ }+ m := chatModel{+ running: true,+ width: 160,+ flowPrintedLines: 1,+ entries: []chatEntry{+ {role: "user", content: "research parth"},+ },+ }++ updated, cmd := m.Update(chatApprovalPromptMsg{request: request, reply: reply})+ if cmd == nil {+ t.Fatal("opening approval should repaint flow transcript")+ }+ fm := updated.(chatModel)+ transcript := stripANSI(fm.renderTranscript(160))+ for _, want := range []string{+ `Web Fetch("https://parthsareen.com/") needs approval`,+ `Web Fetch("https://github.com/ParthSareen") needs approval`,+ } {+ if !strings.Contains(transcript, want) {+ t.Fatalf("transcript missing %q:\n%s", want, transcript)+ }+ }+}++func TestChatApprovalResolutionRepaintsFlowTranscript(t *testing.T) {+ reply := make(chan coreagent.Approval, 1)+ request := coreagent.ApprovalRequest{+ WorkingDir: "/repo",+ Calls: []coreagent.ApprovalToolCall{+ {+ ToolCallID: "call-1",+ ToolName: "web_fetch",+ Args: map[string]any{"url": "https://parthsareen.com/"},+ ApprovalScope: "web_fetch",+ },+ {+ ToolCallID: "call-2",+ ToolName: "web_fetch",+ Args: map[string]any{"url": "https://github.com/ParthSareen"},+ ApprovalScope: "web_fetch",+ },+ },+ }+ m := chatModel{+ running: true,+ width: 160,+ events: make(chan tea.Msg),+ entries: []chatEntry{+ {role: "user", content: "research parth"},+ },+ }+ m.openApprovalPrompt(chatApprovalPromptMsg{request: request, reply: reply})+ printed := len(m.transcriptLines(160))+ m.flowPrintedLines = printed++ updated, cmd := m.resolveApprovalPrompt(chatApprovalChoice{allow: true})+ if cmd == nil {+ t.Fatal("approval resolution should keep waiting for agent events")+ }+ fm := updated.(chatModel)+ if fm.flowPrintedLines >= printed {+ t.Fatalf("approval resolution should repaint and hold queued rows, flowPrintedLines = %d, was %d", fm.flowPrintedLines, printed)+ }+ if result := <-reply; !result.Allow {+ t.Fatalf("approval = %#v, want allow", result)+ }+}++func TestChatApprovalBatchCollapsesAtNextToolBoundary(t *testing.T) {+ reply := make(chan coreagent.Approval, 1)+ request := coreagent.ApprovalRequest{+ WorkingDir: "/repo",+ Calls: []coreagent.ApprovalToolCall{+ {+ ToolCallID: "call-1",+ ToolName: "bash",+ Args: map[string]any{"command": "git rev-parse --abbrev-ref HEAD"},+ ApprovalScope: "bash\x00git rev-parse --abbrev-ref HEAD",+ },+ {+ ToolCallID: "call-2",+ ToolName: "bash",+ Args: map[string]any{"command": "git branch -a"},+ ApprovalScope: "bash\x00git branch -a",+ },+ },+ }+ m := chatModel{+ running: true,+ events: make(chan tea.Msg),+ }+ m.openApprovalPrompt(chatApprovalPromptMsg{request: request, reply: reply})++ updated, _ := m.resolveApprovalPrompt(chatApprovalChoice{allow: true})+ m = updated.(chatModel)+ for _, call := range request.Calls {+ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolStarted,+ ToolCallID: call.ToolCallID,+ ToolName: call.ToolName,+ Args: call.Args,+ })+ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolFinished,+ ToolCallID: call.ToolCallID,+ ToolName: call.ToolName,+ Args: call.Args,+ Content: "ok\n",+ })+ }+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventMessageDelta, Content: "I'm on branch parth-agent-tui."})++ transcript := stripANSI(m.renderTranscript(180))+ if strings.Contains(transcript, "Ran 2 commands") {+ t.Fatalf("completed batch should stay expanded until the next tool boundary:\n%s", transcript)+ }+ if !strings.Contains(transcript, `Bash("git branch -a")`) {+ t.Fatalf("completed batch should keep concrete command rows before the next boundary:\n%s", transcript)+ }++ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolStarted,+ ToolCallID: "call-3",+ ToolName: "bash",+ Args: map[string]any{"command": "git status --short"},+ })+ transcript = stripANSI(m.renderTranscript(180))+ if !strings.Contains(transcript, "Ran 2 commands") {+ t.Fatalf("completed batch should collapse when a new tool starts:\n%s", transcript)+ }+ if !strings.Contains(transcript, `Bash("git status --short")`) {+ t.Fatalf("new running command should remain concrete after previous batch collapses:\n%s", transcript)+ }+}++func TestChatApprovalPrompterCancels(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ result, err := (chatApprovalPrompter{ch: make(chan tea.Msg)}).PromptApproval(ctx, testApprovalRequest())+ if err != nil {+ t.Fatal(err)+ }+ if result.Allow || result.Reason == "" {+ t.Fatalf("approval = %#v, want canceled denial", result)+ }+}++func TestChatApprovalControllerAutoApprovesAfterFullAccessToggle(t *testing.T) {+ events := make(chan tea.Msg, 1)+ state := testApprovalState(false, nil)+ controller := newChatApprovalController(events, state)+ state.SetAllowAll(true)++ result, err := controller.PromptApproval(context.Background(), testApprovalRequest())+ if err != nil {+ t.Fatal(err)+ }+ if !result.Allow || !result.AllowAll {+ t.Fatalf("approval = %#v, want full-access approval", result)+ }+ select {+ case msg := <-events:+ t.Fatalf("approval UI event should not be sent after full access toggle: %#v", msg)+ default:+ }+}++func TestChatPermissionToggleSyncsRunningApprovalController(t *testing.T) {+ events := make(chan tea.Msg, 1)+ state := testApprovalState(false, nil)+ m := chatModel{+ approvalState: state,+ approvalController: newChatApprovalController(events, state),+ }++ updated, _ := m.togglePermissionMode()+ fm := updated.(chatModel)+ result, err := fm.approvalController.PromptApproval(context.Background(), testApprovalRequest())+ if err != nil {+ t.Fatal(err)+ }+ if !result.Allow || !result.AllowAll {+ t.Fatalf("approval = %#v, want full-access approval", result)+ }+}++func TestChatPermissionToggleFromFullAccessRequiresReviewInRunningController(t *testing.T) {+ events := make(chan tea.Msg, 1)+ state := testApprovalState(true, nil)+ m := chatModel{+ approvalState: state,+ approvalController: newChatApprovalController(events, state),+ }++ updated, _ := m.togglePermissionMode()+ fm := updated.(chatModel)+ if fm.allowAllToolsEnabled() {+ t.Fatal("full access should be disabled")+ }++ resultCh := make(chan coreagent.Approval, 1)+ go func() {+ result, err := fm.approvalController.PromptApproval(context.Background(), testApprovalRequest())+ if err != nil {+ resultCh <- coreagent.Approval{Reason: err.Error()}+ return+ }+ resultCh <- result+ }()++ select {+ case msg := <-events:+ prompt, ok := msg.(chatApprovalPromptMsg)+ if !ok {+ t.Fatalf("event = %#v, want approval prompt", msg)+ }+ prompt.reply <- coreagent.Approval{Reason: "denied"}+ case <-time.After(time.Second):+ t.Fatal("expected approval prompt after toggling from full access to review")+ }++ result := <-resultCh+ if result.Allow {+ t.Fatalf("approval = %#v, want review prompt result", result)+ }+}++func TestChatApprovalPromptSkippedWhenFullAccessEnabledInFlight(t *testing.T) {+ reply := make(chan coreagent.Approval, 1)+ // Full access is on by the time the buffered approval request reaches the+ // UI (toggled after the agent sent the request but before Update ran).+ // The stale prompt must not surface; the request is auto-approved.+ m := chatModel{approvalState: testApprovalState(true, nil), running: true}++ updated, _ := m.Update(chatApprovalPromptMsg{request: testApprovalRequest(), reply: reply})+ fm := updated.(chatModel)++ if fm.approvalPrompt != nil {+ t.Fatalf("approval prompt = %#v, want nil (full access on)", fm.approvalPrompt)+ }+ if got := fm.status; got == "approval required" {+ t.Fatalf("status = %q, should not show approval required", got)+ }+ select {+ case result := <-reply:+ if !result.Allow || !result.AllowAll {+ t.Fatalf("approval = %#v, want full-access approval", result)+ }+ default:+ t.Fatal("expected auto-approval sent on the reply channel")+ }+}diff --git a/cmd/tui/chat/chat.go b/cmd/tui/chat/chat.gonew file mode 100644index 000000000..c938e2cbf--- /dev/null+++ b/cmd/tui/chat/chat.go@@ -0,0 +1,1205 @@+package chat++import (+ "context"+ "errors"+ "fmt"+ "hash/fnv"+ "runtime"+ "slices"+ "strings"++ tea "github.com/charmbracelet/bubbletea"++ coreagent "github.com/ollama/ollama/agent"+ "github.com/ollama/ollama/api"+ "github.com/ollama/ollama/cmd/internal/filedata"+)++var chatSpinnerFrames = []string{".", "..", "..."}++var chatRuntimeGOOS = runtime.GOOS++const (+ maxPickerItems = 8+ maxInlineModelPickerItems = 5+ maxSlashCompletions = 5+ maxPromptHistory = 50+ idleWorkingDelayTicks = 4+)++var chatEmptyPrompts = []string{+ `read this repo and tell me where to start`,+ `what changed on this branch?`,+ `run the tests and summarize failures`,+ `find the riskiest code path in this folder`,+ `search the web and compare the latest docs with this implementation`,+ `summarize this file and suggest edits`,+}++type ModelOption struct {+ Name string+ Description string+ Recommended bool+ RequiredPlan string+ Cloud bool+ AvailabilityBadge string+ SignInURL string+}++type Options struct {+ Model string+ OpenModelPicker bool+ ChatID string+ Messages []api.Message+ Client coreagent.ChatClient+ Tools *coreagent.Registry+ ToolRegistryForModel func(context.Context, string) *coreagent.Registry+ ToolsDisabled bool+ MultiModalForModel func(context.Context, string) bool+ ModelOptions func(context.Context) ([]ModelOption, error)+ OnModelSelected func(context.Context, string) error+ SystemPromptForModel func(context.Context, string, *coreagent.Registry) string+ ApprovalPrompter coreagent.ApprovalPrompter+ EventSinks []coreagent.EventSink+ AllowAllTools bool+ WorkingDir string+ RootDir string+ Format string+ Options map[string]any+ Think *api.ThinkValue+ KeepAlive *api.Duration+ Images []api.ImageData+ MultiModal bool+ Compactor coreagent.Compactor+ ContextWindowTokens int+ ContextWindowTokensForModel func(context.Context, string, int) int+ PreloadModel func(context.Context, string, *api.ThinkValue) (int, error)+ CheckCloudModel func(context.Context, string, string) error+ OpenBrowser func(string)+ PollCloudAuth func(context.Context) (string, bool, error)+ CompactionThreshold float64+ SystemPrompt string+}++type Result struct {+ ChatID string+ Messages []api.Message+}++//nolint:containedctx // chatModel is a Bubble Tea session model; the context is the run-scoped cancellation root.+type chatModel struct {+ ctx context.Context+ opts Options+ chatID string+ messages []api.Message+ liveMessages []api.Message+ entries []chatEntry+ workingDir string++ input []rune+ inputCursor int+ inputCursorSet bool+ inputAttachments []chatInputAttachment+ inputPastedTexts []chatInputPastedText+ nextImageID int+ nextAudioID int+ nextPastedTextID int+ promptHistory []string+ promptCursor int+ promptDraft []rune+ promptActive bool+ running bool+ awaitingModel bool+ compacting bool+ cancel context.CancelFunc+ events <-chan tea.Msg+ compactEvents <-chan tea.Msg+ detectedToolCalls []chatEntry+ scroll int+ toolOutputMode bool+ toolOutputOpen bool+ flowPrintedLines int+ thinking bool+ thinkingTokens int+ compactingTokens int+ contextTokens int+ contextEstimate bool+ modelPicker *chatModelPicker+ modelPickerModels []ModelOption+ thinkPicker *chatThinkPicker+ promptDebug *chatPromptDebug+ approvalPrompt *chatApprovalPrompt+ approvalController *chatApprovalController+ approvalState *coreagent.ApprovalState+ cloudAuthPrompt *cloudAuthPrompt+ pendingModel string+ defaultAllowAll bool+ permissionNotice string+ selection chatSelection++ width int+ height int+ status string+ spinner int+ tickActive bool+ preloadingModel string+ complete int+ quitting bool+ openModelOnInit bool+ quitArmed bool+ quitArmedKey string+ escArmed bool+ eventErrorRendered bool+ err error+}++type chatSelectionPoint struct {+ line int+ col int+}++type chatSelection struct {+ active bool+ dragging bool+ anchor chatSelectionPoint+ cursor chatSelectionPoint+}++func startChatSelection(selection *chatSelection, msg tea.MouseMsg, contains func(tea.MouseMsg) bool, point func(tea.MouseMsg) chatSelectionPoint) {+ if !contains(msg) {+ *selection = chatSelection{}+ return+ }+ p := point(msg)+ *selection = chatSelection{active: true, dragging: true, anchor: p, cursor: p}+}++func dragChatSelection(selection *chatSelection, msg tea.MouseMsg, point func(tea.MouseMsg) chatSelectionPoint, scrollEdge func(tea.MouseMsg)) {+ if !selection.active || !selection.dragging {+ return+ }+ selection.cursor = point(msg)+ scrollEdge(msg)+}++func finishChatSelection(selection *chatSelection, msg tea.MouseMsg, point func(tea.MouseMsg) chatSelectionPoint) {+ if !selection.active || !selection.dragging {+ return+ }+ selection.cursor = point(msg)+ selection.dragging = false+ if selection.anchor == selection.cursor {+ *selection = chatSelection{}+ }+}++type chatInputAttachment struct {+ placeholder string+ kind string+ data api.ImageData+}++func Run(ctx context.Context, opts Options) (*Result, error) {+ if opts.RootDir == "" {+ opts.RootDir = opts.WorkingDir+ }++ approvalState := &coreagent.ApprovalState{}+ approvalState.Set(opts.AllowAllTools, nil)++ m := chatModel{+ ctx: ctx,+ opts: opts,+ chatID: opts.ChatID,+ messages: slices.Clone(opts.Messages),+ workingDir: opts.WorkingDir,+ approvalState: approvalState,+ defaultAllowAll: opts.AllowAllTools,+ promptHistory: initialPromptHistory(ctx, opts),+ status: "ready",+ openModelOnInit: opts.OpenModelPicker || (strings.TrimSpace(opts.Model) == "" && opts.ModelOptions != nil),+ }+ m.nextImageID, m.nextAudioID = nextInputAttachmentIDsFromMessages(m.messages)+ m.nextPastedTextID = nextInputPastedTextIDFromMessages(m.messages)+ m.entries = entriesFromMessages(m.messages)+ if !m.openModelOnInit {+ m.refreshContextWindowTokens(m.opts.Model)+ }+ m.contextTokens = m.estimatePromptTokens(m.messages, "")+ m.contextEstimate = true+ if m.openModelOnInit {+ updated, cmd := m.openModelPicker("")+ if cmd != nil {+ return nil, errors.New("initial model picker returned an unexpected command")+ }+ m = updated.(chatModel)+ }+ if opts.PreloadModel != nil && strings.TrimSpace(opts.Model) != "" && !m.openModelOnInit {+ m.preloadingModel = strings.TrimSpace(opts.Model)+ }++ p := tea.NewProgram(m, tea.WithReportFocus())+ finalModel, err := p.Run()+ if err != nil {+ return nil, err+ }++ fm := finalModel.(chatModel)+ if fm.err != nil {+ return nil, fm.err+ }+ return &Result{ChatID: fm.chatID, Messages: fm.messages}, nil+}++func (m chatModel) Init() tea.Cmd {+ var cmds []tea.Cmd+ if m.preloadingModel != "" && m.opts.PreloadModel != nil {+ cmds = append(cmds, preloadModelCmd(m.ctx, m.opts.PreloadModel, m.preloadingModel, m.opts.Think), chatTickCmd())+ }+ if cmd := cloudModelPreflightCmd(m.ctx, m.opts, m.opts.Model, ""); cmd != nil && !m.openModelOnInit {+ cmds = append(cmds, cmd)+ }+ return tea.Batch(cmds...)+}++func (m chatModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {+ if m.canEditInput() && isShiftEnterCSI(msg) {+ m.insertInputNewline()+ return m, nil+ }++ switch msg := msg.(type) {+ case tea.WindowSizeMsg:+ wasSet := m.width > 0 || m.height > 0+ resized := wasSet && (m.width != msg.Width || m.height != msg.Height)+ m.width = msg.Width+ m.height = msg.Height+ if resized {+ return m.withFlowTranscriptRepaint(nil)+ }+ return m.withFlowTranscriptFlush(nil)++ case tea.FocusMsg:+ return m, nil++ case chatTickMsg:+ m.tickActive = false+ if !m.running && !m.compacting && m.preloadingModel == "" {+ return m, nil+ }+ m.spinner+++ cmd := m.scheduleTick()+ return m, cmd++ case chatModelPreloadDoneMsg:+ if msg.model != "" && msg.model != m.preloadingModel {+ return m, nil+ }+ m.preloadingModel = ""+ if msg.err != nil {+ if isUnsupportedThinkingError(msg.err) && thinkRequestsThinking(m.opts.Think) {+ m.opts.Think = &api.ThinkValue{Value: false}+ m.status = fmt.Sprintf("Thinking disabled for %s", msg.model)+ if msg.model != "" && m.opts.PreloadModel != nil {+ m.preloadingModel = msg.model+ return m, tea.Batch(preloadModelCmd(m.ctx, m.opts.PreloadModel, msg.model, m.opts.Think), m.scheduleTick())+ }+ return m, nil+ }+ if !errors.Is(msg.err, context.Canceled) {+ m.status = "error"+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "error", content: fmt.Sprintf("Could not load model: %v", msg.err), err: msg.err.Error()}))+ }+ return m, nil+ }+ if msg.contextWindowTokens > 0 {+ m.updateContextWindowTokens(msg.contextWindowTokens)+ } else {+ m.refreshContextWindowTokens(msg.model)+ }+ return m, nil++ case chatAgentMsg:+ printedLines := m.flowPrintedLines+ var printedTranscript []string+ if printedLines > 0 {+ printedTranscript = slices.Clone(m.transcriptLines(m.viewWidth()))+ }+ m.applyAgentEvent(msg.event)+ return m.withFlowTranscriptRefreshAfter(printedTranscript, printedLines, waitForChatMsg(m.events))++ case chatClipboardErrorMsg:+ if msg.err != nil {+ m.status = "copy failed: " + msg.err.Error()+ }+ return m, nil++ case chatApprovalPromptMsg:+ // Full access may have been enabled while this request was in flight+ // (the user toggled it on after the agent sent the approval request+ // but before this buffered message was handled). In that window+ // togglePermissionMode's auto-resolve sees no open prompt yet, so+ // short-circuit here rather than surfacing a stale approval prompt.+ if m.allowAllToolsEnabled() {+ m.approvalPrompt = &chatApprovalPrompt{request: msg.request, reply: msg.reply}+ return m.resolveApprovalPrompt(chatApprovalChoice{allow: true, allowAll: true})+ }+ printedLines := m.flowPrintedLines+ var printedTranscript []string+ if printedLines > 0 {+ printedTranscript = slices.Clone(m.transcriptLines(m.viewWidth()))+ }+ m.modelPicker = nil+ m.modelPickerModels = nil+ m.openApprovalPrompt(msg)+ return m.withFlowTranscriptRefreshAfter(printedTranscript, printedLines, nil)++ case chatRunDoneMsg:+ wasCanceling := m.status == "canceling"+ m.finishThinkingEntry()+ m.running = false+ m.awaitingModel = false+ m.compacting = false+ m.compactingTokens = 0+ m.cancel = nil+ m.events = nil+ m.approvalController = nil+ m.thinking = false+ m.thinkingTokens = 0+ m.approvalPrompt = nil+ if msg.result != nil {+ m.messages = msg.result.Messages+ m.liveMessages = nil+ if msg.result.WorkingDir != "" {+ m.workingDir = msg.result.WorkingDir+ }+ m.refreshContextWindowTokens(m.responseModelName(&msg.result.Latest))+ m.contextTokens = m.estimatePromptTokens(m.messages, "")+ m.contextEstimate = true+ if !messagesEndWithCompactionResult(m.messages) {+ m.applyResponseMetrics(&msg.result.Latest)+ }+ }+ if msg.result == nil {+ m.finishLiveMessagesForStoppedRun(msg.newMessagesPersisted, msg.persistedMessages)+ }+ if wasCanceling || isChatContextCanceledError(msg.err) {+ m.status = "Tell the model what to do instead."+ return m.withFlowTranscriptFlush(nil)+ }+ if msg.err != nil {+ if !m.eventErrorRendered {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "error", content: msg.err.Error(), err: msg.err.Error()}))+ }+ m.status = "error"+ return m.withFlowTranscriptFlush(nil)+ }+ m.status = "ready"+ return m.withFlowTranscriptFlush(nil)++ case chatCompactDoneMsg:+ return m.finishManualCompaction(msg)++ case chatCompactProgressMsg:+ if msg.tokens > m.compactingTokens {+ m.compactingTokens = msg.tokens+ }+ return m, waitForChatMsg(m.compactEvents)++ case chatEventsClosedMsg:+ if m.compacting {+ return m.Update(chatCompactDoneMsg{err: context.Canceled})+ }+ if m.running {+ return m.Update(chatRunDoneMsg{err: context.Canceled, newMessagesPersisted: true})+ }+ return m, nil++ case cloudAuthTickMsg:+ if m.cloudAuthPrompt != nil {+ return m.updateCloudAuthPrompt(msg)+ }+ return m, nil++ case cloudAuthCheckMsg:+ if m.cloudAuthPrompt != nil {+ return m.updateCloudAuthPrompt(msg)+ }+ return m, nil++ case cloudModelPreflightMsg:+ return m.updateCloudModelPreflight(msg)++ case cloudAuthPollMsg:+ if m.cloudAuthPrompt != nil {+ return m.updateCloudAuthPrompt(msg)+ }+ return m, nil++ case tea.MouseMsg:+ return m.updateMouse(msg)++ case tea.KeyMsg:+ return m.updateKey(msg)+ }+ return m, nil+}++func (m chatModel) updateMouse(msg tea.MouseMsg) (tea.Model, tea.Cmd) {+ if m.promptDebug != nil {+ switch msg.Type {+ case tea.MouseWheelUp:+ m.promptDebug.scroll = clamp(m.promptDebug.scroll-3, 0, m.promptDebugMaxScroll())+ case tea.MouseWheelDown:+ m.promptDebug.scroll = clamp(m.promptDebug.scroll+3, 0, m.promptDebugMaxScroll())+ }+ return m, nil+ }+ if m.modelPicker != nil {+ switch msg.Type {+ case tea.MouseWheelUp:+ m.modelPicker.Move(-3)+ case tea.MouseWheelDown:+ m.modelPicker.Move(3)+ }+ return m, nil+ }+ if !m.mouseInTranscript(msg) && !m.selection.active {+ switch msg.Type {+ case tea.MouseWheelUp:+ m.scrollBy(3)+ case tea.MouseWheelDown:+ m.scrollBy(-3)+ }+ return m, nil+ }+ switch msg.Type {+ case tea.MouseWheelUp:+ m.scrollBy(3)+ case tea.MouseWheelDown:+ m.scrollBy(-3)+ case tea.MouseLeft:+ switch msg.Action {+ case tea.MouseActionPress:+ m.startTranscriptSelection(msg)+ case tea.MouseActionMotion:+ m.dragTranscriptSelection(msg)+ default:+ if msg.Action == 0 {+ m.startTranscriptSelection(msg)+ }+ }+ case tea.MouseMotion:+ m.dragTranscriptSelection(msg)+ case tea.MouseRelease:+ return m, m.finishTranscriptSelection(msg)+ }+ return m, nil+}++func (m chatModel) mouseInTranscript(msg tea.MouseMsg) bool {+ top, height := m.transcriptLayout()+ if msg.X < 0 || msg.X >= m.viewWidth() {+ return false+ }+ return msg.Y >= top && msg.Y < top+height+}++func (m chatModel) mouseTranscriptPoint(msg tea.MouseMsg) chatSelectionPoint {+ top, height := m.transcriptLayout()+ visibleY := clamp(msg.Y-top, 0, max(0, height-1))+ line := m.visibleTranscriptStartLine(m.viewWidth(), height) + visibleY+ col := max(0, msg.X)+ return chatSelectionPoint{line: line, col: col}+}++func (m *chatModel) startTranscriptSelection(msg tea.MouseMsg) {+ startChatSelection(&m.selection, msg, m.mouseInTranscript, m.mouseTranscriptPoint)+}++func (m *chatModel) dragTranscriptSelection(msg tea.MouseMsg) {+ dragChatSelection(&m.selection, msg, m.mouseTranscriptPoint, func(msg tea.MouseMsg) {+ top, height := m.transcriptLayout()+ if msg.Y <= top {+ m.scrollBy(1)+ } else if msg.Y >= top+height-1 {+ m.scrollBy(-1)+ }+ })+}++func (m *chatModel) finishTranscriptSelection(msg tea.MouseMsg) tea.Cmd {+ finishChatSelection(&m.selection, msg, m.mouseTranscriptPoint)+ if chatRuntimeGOOS != "windows" || !m.selection.active {+ return nil+ }+ selected := m.selectedTranscriptText(m.viewWidth())+ if strings.TrimSpace(selected) == "" {+ m.selection = chatSelection{}+ return nil+ }+ m.selection = chatSelection{}+ m.status = "copied"+ return copyTextCmd(m.ctx, selected)+}++func (m chatModel) updateKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {+ if m.promptDebug != nil {+ return m.updatePromptDebug(msg)+ }+ if msg.Type == tea.KeyCtrlO {+ m.toggleInlineToolOutput()+ m.disarmQuit()+ m.disarmEsc()+ return m.withFlowTranscriptRepaint(nil)+ }+ if msg.Type == tea.KeyShiftTab {+ return m.togglePermissionMode()+ }+ if m.approvalPrompt != nil {+ return m.updateApprovalPrompt(msg)+ }+ if m.cloudAuthPrompt != nil {+ return m.updateCloudAuthPrompt(msg)+ }+ if m.modelPicker != nil {+ return m.updateModelPicker(msg)+ }+ if m.thinkPicker != nil {+ return m.updateThinkPicker(msg)+ }+ if msg.Type != tea.KeyCtrlC && msg.Type != tea.KeyCtrlD {+ m.disarmQuit()+ }+ if msg.Type != tea.KeyEsc {+ m.disarmEsc()+ }++ switch msg.Type {+ case tea.KeyCtrlC:+ return m.updateCtrlC()+ case tea.KeyCtrlD:+ return m.updateCtrlD()+ case tea.KeyEsc:+ return m.updateEsc()+ case tea.KeyEnter:+ if msg.Alt {+ m.insertInputNewline()+ return m, nil+ }+ return m.handleSubmit()+ case tea.KeyCtrlJ:+ m.insertInputNewline()+ return m, nil+ case tea.KeyCtrlG:+ return m, nil+ case tea.KeyCtrlP:+ return m.updateUpKey()+ case tea.KeyCtrlN:+ return m.updateDownKey()+ case tea.KeyUp:+ return m.updateUpKey()+ case tea.KeyDown:+ return m.updateDownKey()+ case tea.KeyLeft:+ if msg.Alt {+ m.moveInputCursorWord(-1)+ } else {+ m.moveInputCursorHorizontal(-1)+ }+ case tea.KeyRight:+ if msg.Alt {+ m.moveInputCursorWord(1)+ } else {+ m.moveInputCursorHorizontal(1)+ }+ case tea.KeyCtrlA:+ m.moveInputCursorToLineStart()+ case tea.KeyCtrlE:+ m.moveInputCursorToLineEnd()+ case tea.KeyCtrlB:+ m.moveInputCursorHorizontal(-1)+ case tea.KeyCtrlF:+ m.moveInputCursorHorizontal(1)+ case tea.KeyCtrlLeft:+ m.moveInputCursorWord(-1)+ case tea.KeyCtrlRight:+ m.moveInputCursorWord(1)+ case tea.KeyPgUp:+ m.scrollBy(max(1, m.transcriptHeight()-1))+ case tea.KeyPgDown:+ m.scrollBy(-max(1, m.transcriptHeight()-1))+ case tea.KeyHome:+ m.moveInputCursorToLineStart()+ case tea.KeyEnd:+ m.moveInputCursorToLineEnd()+ case tea.KeyCtrlHome:+ m.scroll = m.maxScroll()+ case tea.KeyCtrlEnd:+ m.scroll = 0+ case tea.KeyBackspace, tea.KeyCtrlH:+ m.resetPromptHistoryCursor()+ if msg.Alt {+ m.deleteInputWordBackward()+ } else {+ m.deleteInputBackward()+ }+ case tea.KeyCtrlW:+ m.resetPromptHistoryCursor()+ m.deleteInputWordBackward()+ case tea.KeyCtrlU:+ m.resetPromptHistoryCursor()+ m.clearInput()+ case tea.KeyCtrlK:+ m.resetPromptHistoryCursor()+ m.deleteInputForward()+ case tea.KeyDelete:+ m.resetPromptHistoryCursor()+ m.deleteInputForward()+ case tea.KeyTab:+ m.applyCompletion()+ case tea.KeySpace:+ m.insertInputRunes([]rune{' '})+ case tea.KeyRunes:+ if !msg.Alt || !m.handleInputAltRunes(msg.Runes) {+ m.insertInputRunesFromKey(msg.Runes, msg.Paste)+ }+ }+ return m, nil+}++func (m *chatModel) toggleInlineToolOutput() {+ m.toolOutputMode = true+ m.toolOutputOpen = !m.toolOutputOpen+ m.applyToolOutputMode()+ m.selection = chatSelection{}+ m.scroll = 0+}++func (m chatModel) updateCtrlC() (tea.Model, tea.Cmd) {+ if len(m.input) > 0 {+ m.clearInput()+ m.resetPromptHistoryCursor()+ m.disarmQuit()+ m.status = "ready"+ return m, nil+ }+ if (m.running || m.compacting) && m.cancel != nil {+ m.cancel()+ m.disarmQuit()+ m.status = "canceling"+ return m, nil+ }+ if !m.quitArmed || m.quitArmedKey != "ctrl+c" {+ m.armQuit("ctrl+c", "press ctrl+c again to quit")+ return m, nil+ }+ m.quitting = true+ return m, m.quitCmd()+}++func (m chatModel) updateCtrlD() (tea.Model, tea.Cmd) {+ if len(m.input) > 0 {+ return m, nil+ }+ if !m.quitArmed || m.quitArmedKey != "ctrl+d" {+ m.armQuit("ctrl+d", "press ctrl+d again to quit")+ return m, nil+ }+ m.quitting = true+ if (m.running || m.compacting) && m.cancel != nil {+ m.cancel()+ }+ return m, m.quitCmd()+}++func (m chatModel) quitCmd() tea.Cmd {+ return tea.Quit+}++func (m *chatModel) armQuit(key, status string) {+ m.quitArmed = true+ m.quitArmedKey = key+ m.status = status+}++func (m chatModel) updateEsc() (tea.Model, tea.Cmd) {+ if (m.running || m.compacting) && m.cancel != nil {+ m.cancel()+ m.disarmQuit()+ m.escArmed = false+ m.status = "canceling"+ return m, nil+ }+ if !m.escArmed {+ m.escArmed = true+ switch {+ case len(m.input) > 0:+ m.status = "press esc again to clear input"+ default:+ m.status = "ready"+ }+ return m, nil+ }++ m.escArmed = false+ cleared := false+ if len(m.input) > 0 {+ m.clearInput()+ m.resetPromptHistoryCursor()+ cleared = true+ }+ if cleared {+ m.status = "ready"+ } else {+ m.status = "ready"+ }+ return m, nil+}++func (m *chatModel) clearInput() {+ m.input = nil+ m.inputCursor = 0+ m.inputCursorSet = false+ m.inputAttachments = nil+ m.inputPastedTexts = nil+ m.complete = 0+}++func (m chatModel) updateUpKey() (tea.Model, tea.Cmd) {+ if m.promptActive && m.movePromptHistory(-1) {+ return m, nil+ }+ if m.moveCompletion(-1) {+ return m, nil+ }+ if m.moveInputCursorVertical(-1) {+ return m, nil+ }+ if slices.Contains(m.input, '\n') {+ return m, nil+ }+ m.movePromptHistory(-1)+ return m, nil+}++func (m chatModel) updateDownKey() (tea.Model, tea.Cmd) {+ if m.promptActive && m.movePromptHistory(1) {+ return m, nil+ }+ if m.moveCompletion(1) {+ return m, nil+ }+ if m.moveInputCursorVertical(1) {+ return m, nil+ }+ if slices.Contains(m.input, '\n') {+ return m, nil+ }+ m.movePromptHistory(1)+ return m, nil+}++func (m chatModel) View() string {+ if m.quitting {+ return ""+ }++ width, height := m.viewSize()++ if m.promptDebug != nil {+ return m.renderPromptDebug(width, height)+ }+ if m.modelPicker != nil && m.openModelOnInit {+ return m.renderModelPicker(width)+ }+ if m.cloudAuthPrompt != nil {+ return m.renderCloudAuthPrompt(width)+ }+ if m.thinkPicker != nil {+ return m.renderThinkPicker(width)+ }+ return m.flowView(width)+}++func (m chatModel) flowView(width int) string {+ allTranscriptLines := m.transcriptLines(width)+ bottomLines := m.bottomLines(width, 0)+ bottomGap := transcriptInputGap(0, len(bottomLines), len(allTranscriptLines))++ printed := clamp(m.flowPrintedLines, 0, len(allTranscriptLines))+ lines := slices.Clone(allTranscriptLines[printed:])+ for range bottomGap {+ lines = append(lines, "")+ }+ lines = append(lines, bottomLines...)+ return strings.Join(lines, "\n")+}++func (m chatModel) withFlowTranscriptFlush(cmd tea.Cmd) (tea.Model, tea.Cmd) {+ next, printCmd := m.flowTranscriptFlushCmd()+ return next, tea.Batch(printCmd, cmd)+}++func (m chatModel) withFlowTranscriptRepaint(cmd tea.Cmd) (tea.Model, tea.Cmd) {+ if m.flowPrintedLines == 0 {+ return m.withFlowTranscriptFlush(cmd)+ }+ m.flowPrintedLines = 0+ next, printCmd := m.flowTranscriptFlushCmd()+ return next, tea.Sequence(tea.ClearScreen, printCmd, cmd)+}++func (m chatModel) withFlowTranscriptRefreshAfter(before []string, printed int, cmd tea.Cmd) (tea.Model, tea.Cmd) {+ next, printCmd := m.flowTranscriptRefreshAfterCmd(before, printed)+ return next, tea.Batch(printCmd, cmd)+}++func (m chatModel) flowTranscriptRefreshAfterCmd(before []string, printed int) (chatModel, tea.Cmd) {+ width := m.viewWidth()+ after := m.transcriptLines(width)+ start := flowTranscriptChangedPrefixStart(before, after, printed)+ if start < 0 {+ return m.flowTranscriptFlushCmd()+ }++ printed = clamp(printed, 0, len(before))+ start = clamp(start, 0, len(after))+ rewind := printed - start+ if rewind <= 0 {+ return m.flowTranscriptFlushCmd()+ }++ flushCount := m.flowTranscriptFlushCount(after, width)+ flushCount = clamp(flushCount, start, len(after))+ rewriteLines := slices.Clone(after[start:flushCount])+ m.flowPrintedLines = flushCount+ return m, tea.Printf("%s", flowTranscriptRewriteSequence(rewind, rewriteLines))+}++func flowTranscriptChangedPrefixStart(before, after []string, printed int) int {+ printed = clamp(printed, 0, len(before))+ if printed == 0 {+ return -1+ }+ limit := min(printed, len(after))+ for i := range limit {+ if before[i] != after[i] {+ return i+ }+ }+ if len(after) < printed {+ return len(after)+ }+ return -1+}++func flowTranscriptRewriteSequence(rewind int, lines []string) string {+ var b strings.Builder+ if rewind > 0 {+ fmt.Fprintf(&b, "\x1b[%dA", rewind)+ }+ b.WriteString("\r\x1b[J")+ b.WriteString(strings.Join(lines, "\n"))+ return b.String()+}++func (m chatModel) flowTranscriptFlushCmd() (chatModel, tea.Cmd) {+ if m.promptDebug != nil || m.modelPicker != nil || m.thinkPicker != nil || m.cloudAuthPrompt != nil {+ return m, nil+ }+ width := m.viewWidth()+ lines := m.transcriptLines(width)+ if len(lines) == 0 {+ m.flowPrintedLines = 0+ return m, nil+ }+ m.flowPrintedLines = clamp(m.flowPrintedLines, 0, len(lines))+ flushCount := m.flowTranscriptFlushCount(lines, width)+ if flushCount <= m.flowPrintedLines {+ return m, nil+ }+ pending := strings.Join(lines[m.flowPrintedLines:flushCount], "\n")+ m.flowPrintedLines = flushCount+ return m, tea.Println(pending)+}++func (m chatModel) flowTranscriptFlushCount(lines []string, width int) int {+ holdFrom := m.flowTranscriptHoldEntryIndex()+ if holdFrom < 0 {+ return len(lines)+ }+ clone := m+ clone.entries = slices.Clone(m.entries[:holdFrom])+ clone.selection = chatSelection{}+ return len(clone.transcriptLines(width))+}++func (m chatModel) flowTranscriptHoldEntryIndex() int {+ if !m.running && !m.compacting {+ return -1+ }+ if len(m.entries) == 0 {+ return -1+ }+ index := len(m.entries) - 1+ entry := m.entries[index]+ switch entry.role {+ case "assistant":+ if entry.content != "" {+ return index+ }+ case "tool":+ if isToolActiveStatus(entry.status) {+ return index+ }+ }+ return -1+}++func (m chatModel) emptyChatHint() string {+ if len(chatEmptyPrompts) == 0 {+ return "Try asking the agent to inspect files, run tools, or explain a repo."+ }+ h := fnv.New32a()+ _, _ = h.Write([]byte(m.chatID))+ prompt := chatEmptyPrompts[int(h.Sum32())%len(chatEmptyPrompts)]+ return prompt+}++func (m chatModel) headerLines() []string {+ return nil+}++func (m *chatModel) resetChat(status string) (tea.Model, tea.Cmd) {+ m.messages = nil+ m.liveMessages = nil+ m.entries = nil+ m.inputAttachments = nil+ m.inputPastedTexts = nil+ m.modelPicker = nil+ m.modelPickerModels = nil+ m.approvalController = nil+ m.resetApprovalState()+ m.nextImageID = 0+ m.nextAudioID = 0+ m.nextPastedTextID = 1+ m.resetPromptHistoryCursor()+ m.resetWorkingDir()+ m.opts.AllowAllTools = m.defaultAllowAll+ m.permissionNotice = ""+ m.thinking = false+ m.thinkingTokens = 0+ m.contextTokens = 0+ m.contextEstimate = true+ m.scroll = 0+ m.flowPrintedLines = 0+ m.status = status+ return *m, tea.ClearScreen+}++func (m *chatModel) resetWorkingDir() {+ if m.opts.RootDir != "" {+ m.workingDir = m.opts.RootDir+ return+ }+ m.workingDir = m.opts.WorkingDir+}++func (m *chatModel) startRun(input string) (tea.Model, tea.Cmd) {+ displayInput, message, err := m.userMessageFromInput(input, input)+ if err != nil {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "error", content: err.Error(), err: err.Error()}))+ m.status = "error"+ return *m, nil+ }+ return m.startRunWithMessages(displayInput, message.Content, []api.Message{message}, "")+}++func (m *chatModel) userMessageFromInput(displayInput, userInput string) (string, api.Message, error) {+ content := m.expandPastedTextPlaceholders(userInput)+ images := slices.Clone(m.opts.Images)+ preloaded := len(images)+ placeholderAttachments := m.activeInputAttachmentsFor(userInput)+ for _, attachment := range placeholderAttachments {+ images = append(images, attachment.data)+ }+ extracted := 0++ if m.opts.MultiModal {+ cleaned, files, err := filedata.ExtractWithFiles(content)+ if err != nil {+ return "", api.Message{}, err+ }+ content = cleaned+ extracted = len(files)+ for _, file := range files {+ images = append(images, file.Data)+ }+ }+ m.opts.Images = nil+ m.inputAttachments = nil+ m.inputPastedTexts = nil++ if len(images) > 0 {+ base := displayInput+ if extracted > 0 {+ base = content+ }+ if len(placeholderAttachments) > 0 && extracted == 0 && preloaded == 0 {+ displayInput = strings.TrimSpace(content)+ } else {+ displayInput = chatDisplayInputWithAttachments(base, len(images))+ }+ }++ return displayInput, api.Message{Role: "user", Content: content, Images: images}, nil+}++func chatDisplayInputWithAttachments(input string, count int) string {+ note := fmt.Sprintf("[attached %d file%s]", count, pluralSuffix(count))+ input = strings.TrimSpace(input)+ if input == "" {+ return note+ }+ return input + "\n\n" + note+}++func pluralSuffix(count int) string {+ if count == 1 {+ return ""+ }+ return "s"+}++func (m *chatModel) startRunWithMessages(displayInput, historyInput string, newMessages []api.Message, extraSystemPrompt string) (tea.Model, tea.Cmd) {+ m.refreshContextWindowTokens(m.opts.Model)+ m.addPromptHistory(historyInput)+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "user", content: displayInput}))+ if len(newMessages) > 1 {+ m.entries = append(m.entries, entriesFromMessages(newMessages[1:])...)+ }+ m.running = true+ m.awaitingModel = true+ m.status = "running"+ m.spinner = 0+ m.scroll = 0+ m.detectedToolCalls = nil+ m.thinking = false+ m.thinkingTokens = 0+ m.eventErrorRendered = false+ systemPrompt := m.systemPrompt(extraSystemPrompt)+ m.liveMessages = append(slices.Clone(m.messages), newMessages...)+ m.contextTokens = m.estimatePromptTokens(m.liveMessages, systemPrompt)+ m.contextEstimate = true++ runCtx, cancel := context.WithCancel(m.ctx)+ m.cancel = cancel+ events := make(chan tea.Msg, 128)+ m.events = events+ m.approvalController = newChatApprovalController(events, m.ensureApprovalState())++ var newMessagesPersisted bool+ eventSinks := []coreagent.EventSink{chatEventSink{ctx: runCtx, ch: events, newMessagesPersisted: &newMessagesPersisted}}+ eventSinks = append(eventSinks, m.opts.EventSinks...)++ session := &coreagent.Session{+ Client: m.opts.Client,+ EventSinks: eventSinks,+ Tools: m.opts.Tools,+ DisableTools: m.opts.ToolsDisabled,+ ApprovalPrompter: m.approvalPrompterForRun(m.approvalController),+ ApprovalState: m.ensureApprovalState(),+ WorkingDir: m.currentWorkingDir(),+ Compactor: m.opts.Compactor,+ }+ opts := coreagent.RunOptions{+ ChatID: m.chatID,+ Model: m.opts.Model,+ SystemPrompt: systemPrompt,+ Messages: slices.Clone(m.messages),+ NewMessages: slices.Clone(newMessages),+ Format: m.opts.Format,+ Options: m.opts.Options,+ Think: m.opts.Think,+ KeepAlive: m.opts.KeepAlive,+ }++ persistedMessages := make([]api.Message, 0, len(m.messages)+len(newMessages))+ persistedMessages = append(persistedMessages, slices.Clone(m.messages)...)+ persistedMessages = append(persistedMessages, slices.Clone(newMessages)...)+ go func() {+ defer close(events)+ result, err := session.Run(runCtx, opts)+ select {+ case events <- chatRunDoneMsg{result: result, err: err, newMessagesPersisted: newMessagesPersisted, persistedMessages: persistedMessages}:+ case <-runCtx.Done():+ }+ }()++ tickCmd := m.scheduleTick()+ flushModel, flushCmd := m.flowTranscriptFlushCmd()+ *m = flushModel+ return *m, tea.Batch(flushCmd, waitForChatMsg(events), tickCmd)+}++func (m *chatModel) finishLiveMessagesForStoppedRun(promote bool, persistedMessages []api.Message) {+ if len(m.liveMessages) == 0 {+ return+ }+ if promote {+ if len(persistedMessages) > 0 {+ m.messages = slices.Clone(persistedMessages)+ } else if !messagesHavePendingToolCalls(m.liveMessages) {+ m.messages = slices.Clone(m.liveMessages)+ }+ }+ m.liveMessages = nil+ m.contextTokens = m.estimatePromptTokens(m.messages, "")+ m.contextEstimate = true+}++func messagesHavePendingToolCalls(messages []api.Message) bool {+ pending := map[string]struct{}{}+ for _, msg := range messages {+ if msg.Role == "assistant" {+ for _, call := range msg.ToolCalls {+ pending[call.ID] = struct{}{}+ }+ }+ if msg.Role == "tool" && msg.ToolCallID != "" {+ delete(pending, msg.ToolCallID)+ }+ }+ return len(pending) > 0+}++func (m *chatModel) disarmQuit() {+ if !m.quitArmed {+ return+ }+ m.quitArmed = false+ m.quitArmedKey = ""+ if strings.HasPrefix(m.status, "press ctrl+") && strings.HasSuffix(m.status, "again to quit") {+ m.status = "ready"+ }+}++func (m *chatModel) disarmEsc() {+ if !m.escArmed {+ return+ }+ m.escArmed = false+ if strings.HasPrefix(m.status, "press esc again") {+ m.status = "ready"+ }+}++func (m chatModel) canEditInput() bool {+ return m.promptDebug == nil && m.approvalPrompt == nil && m.cloudAuthPrompt == nil && m.modelPicker == nil && m.thinkPicker == nil+}++func isChatContextCanceledError(err error) bool {+ return err != nil && (errors.Is(err, context.Canceled) || strings.Contains(err.Error(), "context canceled"))+}diff --git a/cmd/tui/chat/clipboard.go b/cmd/tui/chat/clipboard.gonew file mode 100644index 000000000..337cd37f6--- /dev/null+++ b/cmd/tui/chat/clipboard.go@@ -0,0 +1,66 @@+package chat++import (+ "context"+ "errors"+ "fmt"+ "os/exec"+ "runtime"+ "strings"++ tea "github.com/charmbracelet/bubbletea"+)++type chatClipboardErrorMsg struct {+ err error+}++var writeClipboard = writeSystemClipboard++func copyTextCmd(ctx context.Context, text string) tea.Cmd {+ return func() tea.Msg {+ if err := writeClipboard(ctx, text); err != nil {+ return chatClipboardErrorMsg{err: err}+ }+ return nil+ }+}++func writeSystemClipboard(ctx context.Context, text string) error {+ if ctx == nil {+ ctx = context.Background()+ }+ switch runtime.GOOS {+ case "darwin":+ return runClipboardCommand(ctx, text, "pbcopy")+ case "windows":+ return runClipboardCommand(ctx, text, "clip")+ default:+ for _, candidate := range []struct {+ name string+ args []string+ }{+ {name: "wl-copy"},+ {name: "xclip", args: []string{"-selection", "clipboard"}},+ {name: "xsel", args: []string{"--clipboard", "--input"}},+ } {+ if _, err := exec.LookPath(candidate.name); err != nil {+ continue+ }+ return runClipboardCommand(ctx, text, candidate.name, candidate.args...)+ }+ return errors.New("no clipboard command found")+ }+}++func runClipboardCommand(ctx context.Context, text, name string, args ...string) error {+ cmd := exec.CommandContext(ctx, name, args...)+ cmd.Stdin = strings.NewReader(text)+ if output, err := cmd.CombinedOutput(); err != nil {+ if len(output) > 0 {+ return fmt.Errorf("%s: %w: %s", name, err, strings.TrimSpace(string(output)))+ }+ return fmt.Errorf("%s: %w", name, err)+ }+ return nil+}diff --git a/cmd/tui/chat/cloudauth.go b/cmd/tui/chat/cloudauth.gonew file mode 100644index 000000000..adf74cab8--- /dev/null+++ b/cmd/tui/chat/cloudauth.go@@ -0,0 +1,434 @@+package chat++import (+ "context"+ "errors"+ "fmt"+ "net/http"+ "strings"+ "time"++ tea "github.com/charmbracelet/bubbletea"+ "github.com/ollama/ollama/api"+ "github.com/ollama/ollama/cmd/launch"+ "github.com/ollama/ollama/internal/modelref"+)++type cloudAuthKind string++const (+ cloudAuthSignIn cloudAuthKind = "signin"+ cloudAuthUpgrade cloudAuthKind = "upgrade"+ cloudAuthChecking cloudAuthKind = "checking"+)++const cloudPlanVerificationUnavailable = "Could not verify Ollama plan. Try again in a moment or use a local model."++// Sign-in/upgrade verification polling bounds. While the check is healthy but+// the user hasn't signed in yet, polling stays prompt so completion is detected+// quickly. When the check itself fails, polling backs off so a down server+// isn't hammered, and gives up after maxPollFailures consecutive errors (or+// pollHardCap elapsed) so the user isn't stuck on a spinner with no recourse+// beyond Esc.+const (+ maxPollFailures = 6+ pollBackoffBase = 3 * time.Second+ pollBackoffCap = 30 * time.Second+ pollHardCap = 2 * time.Minute+)++// cloudAuthPrompt is an inline modal that handles sign-in and plan-upgrade+// flows when a user selects a cloud model from the picker.+type cloudAuthPrompt struct {+ modelName string+ requiredPlan string+ signInURL string+ upgradeURL string+ kind cloudAuthKind+ spinner int+ openNow bool+ polling bool+ // pollStarted tracks when sign-in/upgrade verification polling began, for+ // the hard-cap timeout. Lazily set on the first poll response.+ pollStarted time.Time+ // pollFailures counts consecutive verification-check errors; once it+ // reaches maxPollFailures the modal gives up and surfaces an error.+ pollFailures int+ // pollErr holds the last verification error, rendered while retrying.+ pollErr string+}++type cloudAuthCheckMsg struct {+ err error+ signInURL string+}++type cloudModelPreflightMsg struct {+ model string+ err error+ signInURL string+}++type cloudAuthTickMsg struct{}++type cloudAuthPollMsg struct {+ done bool+ err error+}++func checkCloudModelCmd(ctx context.Context, check func(context.Context, string, string) error, model, requiredPlan string) tea.Cmd {+ if check == nil {+ return nil+ }+ return func() tea.Msg {+ if ctx == nil {+ ctx = context.Background()+ }+ err := check(ctx, model, requiredPlan)+ var signInURL string+ if err != nil {+ var authErr api.AuthorizationError+ if errors.As(err, &authErr) && authErr.SigninURL != "" {+ signInURL = authErr.SigninURL+ }+ }+ return cloudAuthCheckMsg{err: err, signInURL: signInURL}+ }+}++func cloudModelPreflightCmd(ctx context.Context, opts Options, modelName, requiredPlan string) tea.Cmd {+ modelName = strings.TrimSpace(modelName)+ if opts.CheckCloudModel == nil || modelName == "" || !modelref.HasExplicitCloudSource(modelName) {+ return nil+ }+ return func() tea.Msg {+ if ctx == nil {+ ctx = context.Background()+ }+ plan := strings.TrimSpace(requiredPlan)+ if plan == "" && opts.ModelOptions != nil {+ models, err := opts.ModelOptions(ctx)+ if err == nil {+ for _, model := range models {+ if strings.EqualFold(strings.TrimSpace(model.Name), modelName) {+ plan = strings.TrimSpace(model.RequiredPlan)+ break+ }+ }+ }+ }+ err := opts.CheckCloudModel(ctx, modelName, plan)+ return cloudModelPreflightMsg{+ model: modelName,+ err: err,+ signInURL: cloudAuthSignInURL(err),+ }+ }+}++func cloudAuthSignInURL(err error) string {+ if err == nil {+ return ""+ }+ var authErr api.AuthorizationError+ if errors.As(err, &authErr) && (authErr.StatusCode == http.StatusUnauthorized || authErr.SigninURL != "") {+ return authErr.SigninURL+ }+ return ""+}++func cloudAuthTickCmd() tea.Cmd {+ return tea.Tick(200*time.Millisecond, func(t time.Time) tea.Msg {+ return cloudAuthTickMsg{}+ })+}++func (m chatModel) updateCloudModelPreflight(msg cloudModelPreflightMsg) (tea.Model, tea.Cmd) {+ if msg.model == "" || !strings.EqualFold(strings.TrimSpace(m.opts.Model), strings.TrimSpace(msg.model)) {+ return m, nil+ }+ if msg.err == nil {+ if m.status == cloudPlanVerificationUnavailable {+ m.status = "ready"+ }+ return m, nil+ }+ if msg.signInURL != "" {+ return m.startCloudAuthSignIn(msg.model, "", msg.signInURL)+ }+ m.status = cloudPlanVerificationUnavailable+ return m, nil+}++func pollCloudAuthCmd(ctx context.Context, poll func(context.Context) (string, bool, error), delay time.Duration) tea.Cmd {+ if poll == nil {+ return nil+ }+ return func() tea.Msg {+ if ctx == nil {+ ctx = context.Background()+ }+ // Back off before the next check when the previous one failed. Honor+ // context cancellation so an abandoned modal doesn't block on the+ // full delay.+ if delay > 0 {+ timer := time.NewTimer(delay)+ defer timer.Stop()+ select {+ case <-ctx.Done():+ case <-timer.C:+ }+ }+ pollCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ defer cancel()+ _, done, err := poll(pollCtx)+ return cloudAuthPollMsg{done: done, err: err}+ }+}++func (m *chatModel) startCloudAuthSignIn(modelName, requiredPlan, signInURL string) (tea.Model, tea.Cmd) {+ // When no sign-in URL is available yet, show the "checking" state while+ // we verify the plan, rather than rendering a blank "Navigate to:" URL.+ kind := cloudAuthSignIn+ if signInURL == "" {+ kind = cloudAuthChecking+ }+ m.cloudAuthPrompt = &cloudAuthPrompt{+ modelName: modelName,+ requiredPlan: requiredPlan,+ kind: kind,+ signInURL: signInURL,+ polling: true,+ }+ m.status = "cloud-auth"+ m.modelPicker = nil+ m.modelPickerModels = nil+ if m.opts.OpenBrowser != nil && signInURL != "" {+ m.opts.OpenBrowser(signInURL)+ }+ if signInURL == "" {+ return m, checkCloudModelCmd(m.ctx, m.opts.CheckCloudModel, modelName, requiredPlan)+ }+ return m, tea.Batch(cloudAuthTickCmd(), pollCloudAuthCmd(m.ctx, m.opts.PollCloudAuth, 0))+}++func (m *chatModel) startCloudAuthUpgrade(modelName, requiredPlan string) (tea.Model, tea.Cmd) {+ m.cloudAuthPrompt = &cloudAuthPrompt{+ modelName: modelName,+ requiredPlan: requiredPlan,+ kind: cloudAuthUpgrade,+ upgradeURL: launch.DefaultUpgradeURL,+ openNow: true,+ }+ m.status = "cloud-auth"+ m.modelPicker = nil+ m.modelPickerModels = nil+ return m, nil+}++func (m chatModel) updateCloudAuthPrompt(msg tea.Msg) (tea.Model, tea.Cmd) {+ switch msg := msg.(type) {+ case cloudAuthCheckMsg:+ if msg.err == nil {+ // Auth passed — apply the pending model.+ return m.completeCloudAuth()+ }+ // Determine if sign-in or upgrade is needed.+ if msg.signInURL != "" {+ m.cloudAuthPrompt.kind = cloudAuthSignIn+ m.cloudAuthPrompt.signInURL = msg.signInURL+ m.cloudAuthPrompt.polling = true+ if m.opts.OpenBrowser != nil {+ m.opts.OpenBrowser(msg.signInURL)+ }+ return m, tea.Batch(cloudAuthTickCmd(), pollCloudAuthCmd(m.ctx, m.opts.PollCloudAuth, 0))+ }+ // Could be a plan upgrade error or unknown error.+ m.cloudAuthPrompt = nil+ m.openModelOnInit = false+ m.status = "ready"+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "error", content: fmt.Sprintf("Could not switch model: %v", msg.err), err: msg.err.Error()}))+ return m, nil++ case cloudAuthTickMsg:+ if m.cloudAuthPrompt == nil {+ return m, nil+ }+ m.cloudAuthPrompt.spinner+++ return m, cloudAuthTickCmd()++ case cloudAuthPollMsg:+ if m.cloudAuthPrompt == nil {+ return m, nil+ }+ if msg.done {+ // Signed in — re-check auth to see if plan is satisfied.+ m.cloudAuthPrompt.polling = false+ m.cloudAuthPrompt.pollFailures = 0+ m.cloudAuthPrompt.pollErr = ""+ return m, checkCloudModelCmd(m.ctx, m.opts.CheckCloudModel, m.cloudAuthPrompt.modelName, m.cloudAuthPrompt.requiredPlan)+ }+ // Lazily mark the start of the polling window on the first response.+ if m.cloudAuthPrompt.pollStarted.IsZero() {+ m.cloudAuthPrompt.pollStarted = time.Now()+ }+ // Hard cap: give up if verification drags on too long for any reason.+ if time.Since(m.cloudAuthPrompt.pollStarted) > pollHardCap {+ return m.failCloudAuthPoll(errors.New("sign-in is taking longer than expected; check your connection and try again"))+ }+ if msg.err != nil {+ // The verification check itself failed (network down, server 5xx).+ // Back off and retry, but give up after a handful of consecutive+ // failures so the user isn't stuck on a spinner with no signal.+ m.cloudAuthPrompt.pollFailures+++ m.cloudAuthPrompt.pollErr = msg.err.Error()+ if m.cloudAuthPrompt.pollFailures >= maxPollFailures {+ return m.failCloudAuthPoll(fmt.Errorf("couldn't verify sign-in: %w", msg.err))+ }+ delay := pollBackoffCap+ if d := pollBackoffBase << (m.cloudAuthPrompt.pollFailures - 1); d < pollBackoffCap {+ delay = d+ }+ return m, pollCloudAuthCmd(m.ctx, m.opts.PollCloudAuth, delay)+ }+ // Healthy but not signed in yet — keep polling promptly so sign-in+ // completion is detected without added latency.+ m.cloudAuthPrompt.pollFailures = 0+ m.cloudAuthPrompt.pollErr = ""+ return m, pollCloudAuthCmd(m.ctx, m.opts.PollCloudAuth, 0)++ case tea.KeyMsg:+ if msg.Type == tea.KeyEsc || msg.Type == tea.KeyCtrlC {+ m.cloudAuthPrompt = nil+ m.pendingModel = ""+ m.openModelOnInit = false+ m.status = "ready"+ return m, nil+ }+ if m.cloudAuthPrompt.kind == cloudAuthUpgrade && !m.cloudAuthPrompt.polling {+ switch msg.Type {+ case tea.KeyLeft, tea.KeyRight, tea.KeyTab:+ m.cloudAuthPrompt.openNow = !m.cloudAuthPrompt.openNow+ case tea.KeyEnter:+ if m.cloudAuthPrompt.openNow {+ m.cloudAuthPrompt.polling = true+ if m.opts.OpenBrowser != nil && m.cloudAuthPrompt.upgradeURL != "" {+ m.opts.OpenBrowser(m.cloudAuthPrompt.upgradeURL)+ }+ return m, tea.Batch(cloudAuthTickCmd(), pollCloudAuthCmd(m.ctx, m.opts.PollCloudAuth, 0))+ }+ m.cloudAuthPrompt = nil+ m.pendingModel = ""+ m.openModelOnInit = false+ m.status = "ready"+ return m, nil+ }+ }+ }++ return m, nil+}++// failCloudAuthPoll abandons the sign-in/upgrade verification modal, surfaces+// an error entry to the user, and returns to the ready state so they can+// re-pick a model and retry.+func (m chatModel) failCloudAuthPoll(err error) (tea.Model, tea.Cmd) {+ m.cloudAuthPrompt = nil+ m.pendingModel = ""+ m.openModelOnInit = false+ m.status = "ready"+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "error", content: fmt.Sprintf("Could not switch model: %v", err), err: err.Error()}))+ return m, nil+}++func (m chatModel) completeCloudAuth() (tea.Model, tea.Cmd) {+ pending := m.cloudAuthPrompt.modelName+ m.cloudAuthPrompt = nil+ m.pendingModel = ""+ m.modelPicker = nil+ m.modelPickerModels = nil+ m.openModelOnInit = false+ m.status = "ready"+ if err := m.applyModelSelection(pending, true); err != nil {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "error", content: fmt.Sprintf("Could not switch model: %v", err), err: err.Error()}))+ m.status = "error"+ return m, nil+ }+ return m, m.startModelPreload(pending)+}++func (m chatModel) renderCloudAuthPrompt(width int) string {+ if m.cloudAuthPrompt == nil {+ return ""+ }+ if width <= 0 {+ width = 80+ }++ p := m.cloudAuthPrompt+ spinnerFrames := []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}+ frame := spinnerFrames[p.spinner%len(spinnerFrames)]++ var b strings.Builder++ switch p.kind {+ case cloudAuthChecking:+ fmt.Fprintf(&b, "%s Checking %s...\n\n", frame, chatPickerSelectedStyle.Render(p.modelName))+ b.WriteString(chatPickerMetaStyle.Render("esc cancel"))+ case cloudAuthSignIn:+ fmt.Fprintf(&b, "To use %s, please sign in.\n\n", chatPickerSelectedStyle.Render(p.modelName))+ b.WriteString("Navigate to:\n")+ urlWrap := chatPickerTextStyle+ if width > 4 {+ urlWrap = chatPickerTextStyle.Width(width - 4)+ }+ b.WriteString(urlWrap.Render(p.signInURL))+ b.WriteString("\n\n")+ if p.pollErr != "" {+ b.WriteString(chatPickerMetaStyle.Render(frame + " Couldn't verify sign-in: " + p.pollErr + " — retrying..."))+ } else {+ b.WriteString(chatPickerMetaStyle.Render(frame + " Waiting for sign in to complete..."))+ }+ b.WriteString("\n\n")+ b.WriteString(chatPickerMetaStyle.Render("esc cancel"))+ case cloudAuthUpgrade:+ fmt.Fprintf(&b, "To use %s, upgrade your Ollama plan.\n\n", chatPickerSelectedStyle.Render(p.modelName))+ if !p.polling {+ var yesBtn, noBtn string+ if p.openNow {+ yesBtn = chatPickerSelectedStyle.Render("› Yes ")+ noBtn = chatPickerMetaStyle.Render(" No ")+ } else {+ yesBtn = chatPickerMetaStyle.Render(" Yes ")+ noBtn = chatPickerSelectedStyle.Render("› No ")+ }+ b.WriteString("Open upgrade page now?\n")+ b.WriteString(yesBtn + " " + noBtn)+ b.WriteString("\n\n")+ if !p.openNow {+ b.WriteString("Or navigate to:\n")+ urlWrap := chatPickerTextStyle+ if width > 4 {+ urlWrap = chatPickerTextStyle.Width(width - 4)+ }+ if u := p.upgradeURL; u != "" {+ b.WriteString(urlWrap.Render(u))+ } else {+ b.WriteString(urlWrap.Render(launch.DefaultUpgradeURL))+ }+ b.WriteString("\n\n")+ }+ b.WriteString(chatPickerMetaStyle.Render("←/→ navigate • enter confirm • esc cancel"))+ } else {+ if p.pollErr != "" {+ b.WriteString(chatPickerMetaStyle.Render(frame + " Couldn't verify upgrade: " + p.pollErr + " — retrying..."))+ } else {+ b.WriteString(chatPickerMetaStyle.Render(frame + " Waiting for upgrade to complete..."))+ }+ b.WriteString("\n\n")+ b.WriteString(chatPickerMetaStyle.Render("esc cancel"))+ }+ }++ return b.String()+}diff --git a/cmd/tui/chat/cloudauth_test.go b/cmd/tui/chat/cloudauth_test.gonew file mode 100644index 000000000..74f85c867--- /dev/null+++ b/cmd/tui/chat/cloudauth_test.go@@ -0,0 +1,247 @@+package chat++import (+ "context"+ "errors"+ "strings"+ "testing"+)++func TestCloudAuthTickDoesNotPoll(t *testing.T) {+ polls := 0+ m := chatModel{+ cloudAuthPrompt: &cloudAuthPrompt{polling: true},+ opts: Options{+ PollCloudAuth: func(context.Context) (string, bool, error) {+ polls+++ return "", false, nil+ },+ },+ }++ updated, cmd := m.updateCloudAuthPrompt(cloudAuthTickMsg{})+ m = updated.(chatModel)++ if m.cloudAuthPrompt.spinner != 1 {+ t.Fatalf("spinner = %d, want 1", m.cloudAuthPrompt.spinner)+ }+ if polls != 0 {+ t.Fatalf("polls = %d, want 0 before running returned tick command", polls)+ }+ if cmd == nil {+ t.Fatal("tick should schedule the next tick")+ }+ if _, ok := cmd().(cloudAuthTickMsg); !ok {+ t.Fatal("tick should schedule another tick, not a poll")+ }+ if polls != 0 {+ t.Fatalf("polls = %d, want 0 after running returned tick command", polls)+ }+}++func TestCloudAuthPollSchedulesNextPoll(t *testing.T) {+ polls := 0+ m := chatModel{+ cloudAuthPrompt: &cloudAuthPrompt{polling: true},+ opts: Options{+ PollCloudAuth: func(context.Context) (string, bool, error) {+ polls+++ return "", false, nil+ },+ },+ }++ _, cmd := m.updateCloudAuthPrompt(cloudAuthPollMsg{})+ if cmd == nil {+ t.Fatal("poll should schedule the next poll")+ }+ msg, ok := cmd().(cloudAuthPollMsg)+ if !ok {+ t.Fatal("poll should schedule another poll, not a tick")+ }+ if msg.done {+ t.Fatal("poll should report not done")+ }+ if polls != 1 {+ t.Fatalf("polls = %d, want 1", polls)+ }+}++func TestCloudModelPreflightFailureShowsPlanVerificationNotice(t *testing.T) {+ m := chatModel{+ opts: Options{+ Model: "glm-5.2:cloud",+ },+ }++ updated, cmd := m.updateCloudModelPreflight(cloudModelPreflightMsg{+ model: "glm-5.2:cloud",+ err: errors.New("temporary network failure"),+ })+ if cmd != nil {+ t.Fatal("transient preflight failure should not start an auth modal")+ }+ m = updated.(chatModel)++ if got := m.status; got != cloudPlanVerificationUnavailable {+ t.Fatalf("status = %q", got)+ }+ if m.cloudAuthPrompt != nil {+ t.Fatalf("cloud auth prompt = %#v, want nil", m.cloudAuthPrompt)+ }+}++func TestCloudModelPreflightIgnoresStaleModel(t *testing.T) {+ m := chatModel{+ opts: Options{+ Model: "glm-5.2:cloud",+ },+ status: "ready",+ }++ updated, _ := m.updateCloudModelPreflight(cloudModelPreflightMsg{+ model: "kimi-k2.7-code:cloud",+ err: errors.New("temporary network failure"),+ })+ m = updated.(chatModel)++ if got := m.status; got != "ready" {+ t.Fatalf("status = %q, want unchanged", got)+ }+}++func TestCloudModelPreflightCommandChecksCloudModel(t *testing.T) {+ var checkedModel, checkedPlan string+ cmd := cloudModelPreflightCmd(context.Background(), Options{+ CheckCloudModel: func(_ context.Context, model, requiredPlan string) error {+ checkedModel = model+ checkedPlan = requiredPlan+ return errors.New("temporary network failure")+ },+ ModelOptions: func(context.Context) ([]ModelOption, error) {+ return []ModelOption{{Name: "glm-5.2:cloud", RequiredPlan: "pro", Cloud: true}}, nil+ },+ }, "glm-5.2:cloud", "")+ if cmd == nil {+ t.Fatal("cloud preflight command should be scheduled")+ }+ raw := cmd()+ msg, ok := raw.(cloudModelPreflightMsg)+ if !ok {+ t.Fatalf("message = %T, want cloudModelPreflightMsg", raw)+ }+ if checkedModel != "glm-5.2:cloud" || checkedPlan != "pro" {+ t.Fatalf("checked model/plan = %q/%q", checkedModel, checkedPlan)+ }+ if msg.model != "glm-5.2:cloud" || msg.err == nil || !strings.Contains(msg.err.Error(), "temporary") {+ t.Fatalf("message = %#v", msg)+ }+}++func TestCloudAuthPollGivesUpAfterConsecutiveFailures(t *testing.T) {+ pollErr := errors.New("whoami: connection refused")+ m := chatModel{+ cloudAuthPrompt: &cloudAuthPrompt{polling: true, kind: cloudAuthSignIn},+ opts: Options{+ PollCloudAuth: func(context.Context) (string, bool, error) {+ return "", false, pollErr+ },+ },+ }++ // The first maxPollFailures-1 failures should keep retrying.+ for i := 1; i < maxPollFailures; i++ {+ updated, _ := m.updateCloudAuthPrompt(cloudAuthPollMsg{done: false, err: pollErr})+ m = updated.(chatModel)+ if m.cloudAuthPrompt == nil {+ t.Fatalf("failure %d: prompt cleared early", i)+ }+ if got := m.cloudAuthPrompt.pollFailures; got != i {+ t.Fatalf("failure %d: pollFailures = %d, want %d", i, got, i)+ }+ if m.cloudAuthPrompt.pollErr != pollErr.Error() {+ t.Fatalf("failure %d: pollErr = %q, want %q", i, m.cloudAuthPrompt.pollErr, pollErr.Error())+ }+ }++ // The threshold failure gives up: prompt cleared, back to ready, error entry.+ updated, cmd := m.updateCloudAuthPrompt(cloudAuthPollMsg{done: false, err: pollErr})+ m = updated.(chatModel)+ if cmd != nil {+ t.Fatalf("threshold failure should not reschedule, got cmd %T", cmd)+ }+ if m.cloudAuthPrompt != nil {+ t.Fatalf("prompt = %#v, want nil after give-up", m.cloudAuthPrompt)+ }+ if m.status != "ready" {+ t.Fatalf("status = %q, want ready", m.status)+ }+ if len(m.entries) == 0 {+ t.Fatal("expected an error entry after give-up")+ }+ last := m.entries[len(m.entries)-1]+ if last.role != "error" || !strings.Contains(last.content, "couldn't verify sign-in") {+ t.Fatalf("last entry = %+v, want error containing sign-in failure", last)+ }+}++func TestCloudAuthPollResetsFailuresOnHealthyResponse(t *testing.T) {+ pollErr := errors.New("whoami: timeout")+ m := chatModel{+ cloudAuthPrompt: &cloudAuthPrompt{polling: true, kind: cloudAuthSignIn},+ opts: Options{+ PollCloudAuth: func(context.Context) (string, bool, error) {+ return "", false, pollErr+ },+ },+ }++ // Accumulate some failures without hitting the threshold.+ for range maxPollFailures - 2 {+ updated, _ := m.updateCloudAuthPrompt(cloudAuthPollMsg{done: false, err: pollErr})+ m = updated.(chatModel)+ }+ if got := m.cloudAuthPrompt.pollFailures; got != maxPollFailures-2 {+ t.Fatalf("pollFailures = %d, want %d", got, maxPollFailures-2)+ }++ // A healthy (no-error, not-done) response resets the streak so a later+ // transient blip isn't counted against a recovered connection.+ updated, _ := m.updateCloudAuthPrompt(cloudAuthPollMsg{done: false, err: nil})+ m = updated.(chatModel)+ if m.cloudAuthPrompt == nil {+ t.Fatal("healthy response should keep the prompt open")+ }+ if got := m.cloudAuthPrompt.pollFailures; got != 0 {+ t.Fatalf("pollFailures = %d, want 0 after healthy response", got)+ }+ if m.cloudAuthPrompt.pollErr != "" {+ t.Fatalf("pollErr = %q, want empty after healthy response", m.cloudAuthPrompt.pollErr)+ }+}++func TestCloudAuthPollCompletesAfterFailures(t *testing.T) {+ pollErr := errors.New("whoami: timeout")+ m := chatModel{+ cloudAuthPrompt: &cloudAuthPrompt{+ modelName: "glm-5.2:cloud",+ polling: true,+ kind: cloudAuthSignIn,+ pollFailures: maxPollFailures - 1,+ },+ opts: Options{+ CheckCloudModel: func(context.Context, string, string) error { return nil },+ PollCloudAuth: func(context.Context) (string, bool, error) { return "", false, pollErr },+ },+ }++ // A successful sign-in mid-retry should clear the failure state and re-check.+ updated, _ := m.updateCloudAuthPrompt(cloudAuthPollMsg{done: true})+ m = updated.(chatModel)+ if m.cloudAuthPrompt.polling {+ t.Fatal("done should stop polling")+ }+ if m.cloudAuthPrompt.pollFailures != 0 || m.cloudAuthPrompt.pollErr != "" {+ t.Fatalf("failure state not reset: failures=%d err=%q", m.cloudAuthPrompt.pollFailures, m.cloudAuthPrompt.pollErr)+ }+}diff --git a/cmd/tui/chat/compaction.go b/cmd/tui/chat/compaction.gonew file mode 100644index 000000000..51e035b5f--- /dev/null+++ b/cmd/tui/chat/compaction.go@@ -0,0 +1,101 @@+package chat++import (+ "context"+ "slices"++ tea "github.com/charmbracelet/bubbletea"++ coreagent "github.com/ollama/ollama/agent"+ "github.com/ollama/ollama/api"+)++func (m *chatModel) startManualCompaction() (tea.Model, tea.Cmd) {+ if m.running || m.compacting {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "system", content: "Wait for the current response to finish before compacting."}))+ return *m, nil+ }+ m.refreshContextWindowTokens(m.opts.Model)+ if m.opts.Compactor == nil {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "system", content: coreagent.CompactionSkippedMessage("compaction is unavailable")}))+ m.status = "compact skipped"+ return *m, nil+ }++ ctx := m.ctx+ if ctx == nil {+ ctx = context.Background()+ }+ runCtx, cancel := context.WithCancel(ctx)+ compactor := m.opts.Compactor+ events := make(chan tea.Msg, 128)+ m.compacting = true+ m.compactingTokens = 0+ m.cancel = cancel+ m.compactEvents = events+ m.status = "compacting"+ messages := slices.Clone(m.messages)+ var tools api.Tools+ if m.opts.Tools != nil {+ tools = m.opts.Tools.Tools()+ }+ req := coreagent.CompactionRequest{+ ChatID: m.chatID,+ Model: m.opts.Model,+ SystemPrompt: m.systemPrompt(""),+ Messages: messages,+ Tools: tools,+ Format: m.opts.Format,+ Options: m.opts.Options,+ KeepAlive: m.opts.KeepAlive,+ Force: true,+ Progress: func(progress coreagent.CompactionProgress) {+ select {+ case events <- chatCompactProgressMsg{tokens: progress.Tokens}:+ case <-runCtx.Done():+ }+ },+ }+ go func() {+ defer close(events)+ result, err := compactor.MaybeCompact(runCtx, req)+ select {+ case events <- chatCompactDoneMsg{result: result, err: err}:+ case <-runCtx.Done():+ }+ }()+ tickCmd := m.scheduleTick()+ return *m, tea.Batch(waitForChatMsg(events), tickCmd)+}++func (m chatModel) finishManualCompaction(msg chatCompactDoneMsg) (tea.Model, tea.Cmd) {+ wasCanceling := m.status == "canceling"+ m.compacting = false+ m.compactEvents = nil+ m.cancel = nil+ m.compactingTokens = 0+ if wasCanceling || isChatContextCanceledError(msg.err) {+ m.status = "compact canceled"+ return m.withFlowTranscriptFlush(nil)+ }+ if msg.err != nil {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "system", content: coreagent.CompactionSkippedMessage(msg.err.Error())}))+ m.status = "compact skipped"+ return m.withFlowTranscriptFlush(nil)+ }+ if !msg.result.Compacted {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "system", content: coreagent.CompactionSkippedMessage(msg.result.Reason)}))+ m.status = "compact skipped"+ return m.withFlowTranscriptFlush(nil)+ }++ m.messages = msg.result.Messages+ m.liveMessages = nil+ m.entries = entriesFromMessages(m.messages)+ m.contextTokens = m.estimatePromptTokens(m.messages, "")+ m.contextEstimate = true+ m.scroll = 0+ m.flowPrintedLines = 0+ m.status = "compacted"+ return m.withFlowTranscriptFlush(nil)+}diff --git a/cmd/tui/chat/debug.go b/cmd/tui/chat/debug.gonew file mode 100644index 000000000..796626240--- /dev/null+++ b/cmd/tui/chat/debug.go@@ -0,0 +1,558 @@+package chat++import (+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "slices"+ "strings"++ tea "github.com/charmbracelet/bubbletea"+ "github.com/charmbracelet/lipgloss"++ coreagent "github.com/ollama/ollama/agent"+ "github.com/ollama/ollama/api"+)++type chatPromptDebug struct {+ request api.ChatRequest+ tokens int+ scroll int+}++const maxPromptDebugToolResultRunes = 400++func (m *chatModel) handleSaveCommand(args string) (tea.Model, tea.Cmd) {+ filename, err := saveRequestFilename(args)+ if err != nil {+ return m.addDebugError(err)+ }+ raw, err := m.rawRequestJSON()+ if err != nil {+ return m.addDebugError(err)+ }++ dir, err := m.debugWorkingDir()+ if err != nil {+ return m.addDebugError(err)+ }+ path := filepath.Join(dir, filename)+ if err := os.WriteFile(path, []byte(raw+"\n"), 0o644); err != nil {+ return m.addDebugError(err)+ }+ m.entries = append(m.entries, newSlashEntry(fmt.Sprintf("saved as %s", filename)))+ m.status = "saved"+ return *m, nil+}++func (m *chatModel) handlePromptCommand(args string) (tea.Model, tea.Cmd) {+ if strings.TrimSpace(args) != "" {+ return m.addDebugError(fmt.Errorf("usage: /prompt"))+ }+ req, tokens := m.requestPreview()+ m.promptDebug = &chatPromptDebug{+ request: req,+ tokens: tokens,+ }+ m.flowPrintedLines = 0+ m.selection = chatSelection{}+ m.status = "prompt"+ return *m, tea.Batch(tea.ClearScreen, tea.EnableMouseCellMotion)+}++func (m chatModel) updatePromptDebug(msg tea.KeyMsg) (tea.Model, tea.Cmd) {+ if m.promptDebug == nil {+ return m, nil+ }+ switch msg.Type {+ case tea.KeyEsc, tea.KeyCtrlC, tea.KeyEnter:+ return m.closePromptDebug()+ case tea.KeyUp, tea.KeyCtrlP:+ m.promptDebug.scroll--+ case tea.KeyDown, tea.KeyCtrlN:+ m.promptDebug.scroll+++ case tea.KeyPgUp:+ m.promptDebug.scroll -= max(1, m.promptDebugPageSize())+ case tea.KeyPgDown:+ m.promptDebug.scroll += max(1, m.promptDebugPageSize())+ case tea.KeyHome, tea.KeyCtrlHome:+ m.promptDebug.scroll = 0+ case tea.KeyEnd, tea.KeyCtrlEnd:+ m.promptDebug.scroll = m.promptDebugMaxScroll()+ }+ if m.promptDebug != nil {+ m.promptDebug.scroll = clamp(m.promptDebug.scroll, 0, m.promptDebugMaxScroll())+ }+ return m, nil+}++func (m chatModel) closePromptDebug() (tea.Model, tea.Cmd) {+ m.promptDebug = nil+ m.status = "ready"+ m.flowPrintedLines = 0+ next, printCmd := m.flowTranscriptFlushCmd()+ return next, tea.Sequence(tea.DisableMouse, tea.ClearScreen, printCmd)+}++func (m chatModel) renderPromptDebug(width, height int) string {+ if width <= 0 {+ width = 80+ }+ if height <= 0 {+ height = 24+ }+ if m.promptDebug == nil {+ return renderFullFrame("", width, height)+ }++ header := []string{+ chatPickerTitleStyle.Render("Prompt"),+ chatPickerMetaStyle.Render("full request preview • /save <filename> saved as <filename>.json"),+ "",+ }+ footer := chatPickerMetaStyle.Render("↑/↓ scroll • pgup/pgdn page • enter/esc close")+ bodyHeight := max(0, height-len(header)-1)+ body := m.promptDebugLines(width)+ maxScroll := max(0, len(body)-bodyHeight)+ scroll := clamp(m.promptDebug.scroll, 0, maxScroll)+ if bodyHeight < len(body) {+ body = body[scroll:min(len(body), scroll+bodyHeight)]+ }++ lines := slices.Clone(header)+ lines = append(lines, body...)+ for len(lines) < height-1 {+ lines = append(lines, "")+ }+ lines = append(lines, footer)+ return renderFrameLines(lines, width, height)+}++func (m chatModel) promptDebugPageSize() int {+ height := m.height+ if height <= 0 {+ height = 24+ }+ return max(1, height-5)+}++func (m chatModel) promptDebugMaxScroll() int {+ if m.promptDebug == nil {+ return 0+ }+ width := m.viewWidth()+ height := m.height+ if height <= 0 {+ height = 24+ }+ bodyHeight := max(0, height-4)+ return max(0, len(m.promptDebugLines(width))-bodyHeight)+}++func (m *chatModel) addDebugError(err error) (tea.Model, tea.Cmd) {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "error", content: err.Error(), err: err.Error()}))+ m.status = "error"+ return *m, nil+}++func (m chatModel) rawRequestJSON() (string, error) {+ req, _ := m.requestPreview()+ data, err := json.MarshalIndent(req, "", " ")+ if err != nil {+ return "", err+ }+ return string(data), nil+}++func (m chatModel) requestPreview() (api.ChatRequest, int) {+ opts := m.previewRunOptions()+ messages := m.previewMessages()+ req := m.previewChatRequest(opts, messages)+ return req, m.estimatePromptTokens(messages, opts.SystemPrompt)+}++func (m chatModel) previewRunOptions() coreagent.RunOptions {+ return coreagent.RunOptions{+ ChatID: m.chatID,+ Model: m.opts.Model,+ SystemPrompt: m.systemPrompt(""),+ Format: m.opts.Format,+ Options: m.opts.Options,+ Think: m.opts.Think,+ KeepAlive: m.opts.KeepAlive,+ }+}++func (m chatModel) previewMessages() []api.Message {+ if len(m.liveMessages) > 0 {+ return slices.Clone(m.liveMessages)+ }+ return slices.Clone(m.messages)+}++func (m chatModel) previewChatRequest(opts coreagent.RunOptions, messages []api.Message) api.ChatRequest {+ requestMessages := slices.Clone(messages)+ if strings.TrimSpace(opts.SystemPrompt) != "" {+ withSystem := make([]api.Message, 0, len(requestMessages)+1)+ withSystem = append(withSystem, api.Message{Role: "system", Content: opts.SystemPrompt})+ requestMessages = append(withSystem, requestMessages...)+ }++ format := opts.Format+ if format == "json" {+ format = `"` + format + `"`+ }++ req := api.ChatRequest{+ Model: opts.Model,+ Messages: requestMessages,+ Format: json.RawMessage(format),+ Options: opts.Options,+ Think: opts.Think,+ }+ if opts.KeepAlive != nil {+ req.KeepAlive = opts.KeepAlive+ }+ if m.opts.Tools != nil && !m.opts.ToolsDisabled {+ req.Tools = m.opts.Tools.Tools()+ }+ return req+}++func (m chatModel) promptDebugLines(width int) []string {+ if m.promptDebug == nil {+ return nil+ }+ req := m.promptDebug.request+ innerWidth := max(20, width-2)+ lines := []string{+ chatHeaderStyle.Render("Request"),+ promptDebugFieldLine("model", req.Model, innerWidth),+ promptDebugFieldLine("estimated prompt", m.promptTokenText(m.promptDebug.tokens), innerWidth),+ promptDebugFieldLine("messages", fmt.Sprint(len(req.Messages)), innerWidth),+ promptDebugFieldLine("tools", fmt.Sprint(len(req.Tools)), innerWidth),+ }+ if len(req.Format) > 0 {+ lines = append(lines, promptDebugFieldLine("format", strings.TrimSpace(string(req.Format)), innerWidth))+ }+ if req.Options != nil {+ lines = append(lines, promptDebugMapLines("options", req.Options, innerWidth)...)+ }+ if req.Think != nil {+ lines = append(lines, promptDebugBlockLines("think", req.Think.String(), innerWidth, chatHistoryTextStyle)...)+ }+ if req.KeepAlive != nil {+ lines = append(lines, promptDebugFieldLine("keep_alive", req.KeepAlive.String(), innerWidth))+ }+ lines = append(lines, "", chatHeaderStyle.Render("Messages"))+ if len(req.Messages) == 0 {+ lines = append(lines, chatMetaStyle.Render("none"))+ } else {+ for i, msg := range req.Messages {+ if i > 0 {+ lines = append(lines, "")+ }+ lines = append(lines, promptDebugMessageLines(i+1, msg, innerWidth)...)+ }+ }+ lines = append(lines, "", chatHeaderStyle.Render("Tools"))+ if len(req.Tools) == 0 {+ lines = append(lines, chatMetaStyle.Render("none"))+ return lines+ }+ for i, tool := range req.Tools {+ if i > 0 {+ lines = append(lines, "")+ }+ lines = append(lines, promptDebugToolLines(i+1, tool, innerWidth)...)+ }+ return lines+}++func promptDebugFieldLine(label, value string, width int) string {+ labelText := label + ":"+ value = strings.TrimSpace(value)+ if value == "" {+ value = "_empty_"+ }+ line := chatHistoryLabelStyle.Render(labelText) + " " + chatHistoryTextStyle.Render(value)+ return truncateRenderedLine(line, width)+}++func promptDebugMessageLines(index int, msg api.Message, width int) []string {+ role := promptMessageLabel(msg)+ header := fmt.Sprintf("%d. %s", index, role)+ lines := []string{historyRoleStyle(msg.Role).Render(header)}++ if strings.TrimSpace(msg.Thinking) != "" {+ lines = append(lines, promptDebugBlockLines("thinking", msg.Thinking, width, chatHistoryTextStyle)...)+ }+ if msg.Role != "tool" && (strings.TrimSpace(msg.Content) != "" || (msg.Role != "assistant" && len(msg.ToolCalls) == 0 && len(msg.Images) == 0 && msg.Thinking == "")) {+ lines = append(lines, promptDebugBlockLines("content", msg.Content, width, chatHistoryTextStyle)...)+ }+ if len(msg.ToolCalls) > 0 {+ for i, call := range msg.ToolCalls {+ lines = append(lines, promptDebugToolCallLines(i+1, call, width)...)+ }+ }+ if msg.Role == "tool" {+ if msg.ToolName != "" {+ lines = append(lines, " "+chatHistoryLabelStyle.Render("tool_name:")+" "+chatHistoryTextStyle.Render(msg.ToolName))+ }+ if msg.ToolCallID != "" {+ lines = append(lines, " "+chatHistoryLabelStyle.Render("tool_call_id:")+" "+chatHistoryTextStyle.Render(msg.ToolCallID))+ }+ lines = append(lines, promptDebugBlockLines("tool result", promptDebugToolResult(msg.Content), width, chatHistoryTextStyle)...)+ }+ if len(msg.Images) > 0 {+ lines = append(lines, " "+chatHistoryLabelStyle.Render(fmt.Sprintf("%d image%s", len(msg.Images), pluralSuffix(len(msg.Images)))))+ }+ return lines+}++func promptDebugToolResult(content string) string {+ runes := []rune(content)+ if len(runes) <= maxPromptDebugToolResultRunes {+ return content+ }+ return string(runes[:maxPromptDebugToolResultRunes-3]) + "..."+}++func promptDebugMapLines(label string, values map[string]any, width int) []string {+ lines := []string{" " + chatHistoryLabelStyle.Render(label+":")}+ if len(values) == 0 {+ return append(lines, " "+chatMetaStyle.Render("_empty_"))+ }+ keys := make([]string, 0, len(values))+ for key := range values {+ keys = append(keys, key)+ }+ slices.Sort(keys)+ for _, key := range keys {+ lines = append(lines, promptDebugValueLine(4, key, values[key], width)...)+ }+ return lines+}++func promptDebugToolLines(index int, tool api.Tool, width int) []string {+ name := strings.TrimSpace(tool.Function.Name)+ if name == "" {+ name = "_unnamed_"+ }+ lines := []string{historyRoleStyle("tool").Render(fmt.Sprintf("%d. %s", index, name))}+ if strings.TrimSpace(tool.Function.Description) != "" {+ lines = append(lines, promptDebugBlockLines("description", tool.Function.Description, width, chatHistoryTextStyle)...)+ }++ params := tool.Function.Parameters+ if params.Type != "" || params.Properties != nil {+ kind := params.Type+ if kind == "" {+ kind = "object"+ }+ lines = append(lines, " "+chatHistoryLabelStyle.Render("parameters:")+" "+chatHistoryTextStyle.Render(kind))+ }+ if params.Properties == nil || params.Properties.Len() == 0 {+ return lines+ }++ lines = append(lines, " "+chatHistoryLabelStyle.Render("properties:"))+ required := map[string]bool{}+ for _, name := range params.Required {+ required[name] = true+ }+ for name, property := range params.Properties.All() {+ label := name+ propertyType := property.ToTypeScriptType()+ switch {+ case propertyType != "" && required[name]:+ label += " (" + propertyType + ", required)"+ case propertyType != "":+ label += " (" + propertyType + ")"+ case required[name]:+ label += " (required)"+ }+ value := strings.TrimSpace(property.Description)+ if value == "" {+ value = promptDebugPropertyDetails(property)+ }+ lines = append(lines, promptDebugTextLine(4, label, value, width)...)+ }+ return lines+}++func promptDebugToolCallLines(index int, call api.ToolCall, width int) []string {+ name := strings.TrimSpace(call.Function.Name)+ if name == "" {+ name = "_unnamed_"+ }+ lines := []string{" " + chatHistoryLabelStyle.Render(fmt.Sprintf("tool call %d:", index)) + " " + chatHistoryTextStyle.Render(name)}+ if strings.TrimSpace(call.ID) != "" {+ lines = append(lines, promptDebugTextLine(4, "id", call.ID, width)...)+ }+ if call.Function.Arguments.Len() == 0 {+ lines = append(lines, " "+chatHistoryLabelStyle.Render("arguments:")+" "+chatMetaStyle.Render("none"))+ return lines+ }+ lines = append(lines, " "+chatHistoryLabelStyle.Render("arguments:"))+ for key, value := range call.Function.Arguments.All() {+ lines = append(lines, promptDebugValueLine(6, key, value, width)...)+ }+ return lines+}++func promptDebugPropertyDetails(property api.ToolProperty) string {+ var parts []string+ if len(property.Enum) > 0 {+ values := make([]string, 0, len(property.Enum))+ for _, value := range property.Enum {+ values = append(values, promptDebugValueText(value))+ }+ parts = append(parts, "one of "+strings.Join(values, ", "))+ }+ if property.Properties != nil && property.Properties.Len() > 0 {+ count := property.Properties.Len()+ noun := "property"+ if count != 1 {+ noun = "properties"+ }+ parts = append(parts, fmt.Sprintf("%d nested %s", count, noun))+ }+ if property.Items != nil {+ parts = append(parts, "array items: "+promptDebugValueText(property.Items))+ }+ if len(parts) == 0 {+ return "_empty_"+ }+ return strings.Join(parts, "; ")+}++func promptDebugValueLine(indent int, label string, value any, width int) []string {+ return promptDebugTextLine(indent, label, promptDebugValueText(value), width)+}++func promptDebugTextLine(indent int, label, value string, width int) []string {+ prefix := strings.Repeat(" ", indent) + chatHistoryLabelStyle.Render(label+":")+ value = strings.TrimSpace(value)+ if value == "" {+ value = "_empty_"+ }+ wrapWidth := max(20, width-indent-lipgloss.Width(label)-2)+ wrapped := wrapChatText(value, wrapWidth)+ if len(wrapped) == 0 {+ return []string{prefix + " " + chatMetaStyle.Render("_empty_")}+ }+ lines := []string{prefix + " " + chatHistoryTextStyle.Render(wrapped[0])}+ for _, line := range wrapped[1:] {+ lines = append(lines, strings.Repeat(" ", indent+2)+chatHistoryTextStyle.Render(line))+ }+ return lines+}++func promptDebugValueText(value any) string {+ switch v := value.(type) {+ case nil:+ return "null"+ case string:+ return v+ case fmt.Stringer:+ return v.String()+ case []any:+ parts := make([]string, 0, len(v))+ for _, item := range v {+ parts = append(parts, promptDebugValueText(item))+ }+ return strings.Join(parts, ", ")+ case map[string]any:+ keys := make([]string, 0, len(v))+ for key := range v {+ keys = append(keys, key)+ }+ slices.Sort(keys)+ parts := make([]string, 0, len(keys))+ for _, key := range keys {+ parts = append(parts, key+": "+promptDebugValueText(v[key]))+ }+ return strings.Join(parts, ", ")+ default:+ return fmt.Sprint(value)+ }+}++func promptDebugBlockLines(label, value string, width int, style lipgloss.Style) []string {+ lines := []string{" " + chatHistoryLabelStyle.Render(label+":")}+ if value == "" {+ return append(lines, " "+chatMetaStyle.Render("_empty_"))+ }+ for _, raw := range strings.Split(strings.TrimRight(value, "\n"), "\n") {+ if raw == "" {+ lines = append(lines, "")+ continue+ }+ for _, wrapped := range wrapChatText(raw, max(20, width-4)) {+ lines = append(lines, " "+style.Render(wrapped))+ }+ }+ return lines+}++func (m chatModel) promptTokenText(tokens int) string {+ window := m.displayContextWindowTokens()+ if window > 0 {+ return fmt.Sprintf("%s / %s tokens", formatPromptTokenCount(max(tokens, 0)), formatPromptTokenCount(window))+ }+ return formatTokenCount(tokens)+}++func formatPromptTokenCount(count int) string {+ sign := ""+ if count < 0 {+ sign = "-"+ count = -count+ }+ if count < 100_000 {+ return sign + fmt.Sprint(count)+ }+ if count >= 950_000 {+ return fmt.Sprintf("%s%dM", sign, int(float64(count)/1_000_000+0.5))+ }+ return fmt.Sprintf("%s%dk", sign, int(float64(count)/1024+0.5))+}++func promptMessageLabel(msg api.Message) string {+ if msg.Role == "tool" && msg.ToolName != "" {+ return msg.Role + ":" + msg.ToolName+ }+ return msg.Role+}++func saveRequestFilename(args string) (string, error) {+ args = strings.TrimSpace(args)+ if args == "" {+ return "", fmt.Errorf("usage: /save <filename>")+ }+ if strings.HasPrefix(args, ">") {+ args = strings.TrimSpace(strings.TrimPrefix(args, ">"))+ }+ fields := strings.Fields(args)+ if len(fields) != 1 {+ return "", fmt.Errorf("usage: /save <filename>")+ }+ filename := strings.TrimSpace(fields[0])+ if filename == "" || filename == "." || filename == ".." || strings.ContainsAny(filename, `/\`) || filepath.IsAbs(filename) {+ return "", fmt.Errorf("save filename must be a file name, not a path")+ }+ if !strings.HasSuffix(strings.ToLower(filename), ".json") {+ filename += ".json"+ }+ return filename, nil+}++func (m chatModel) debugWorkingDir() (string, error) {+ dir := strings.TrimSpace(m.currentWorkingDir())+ if dir != "" {+ return dir, nil+ }+ return os.Getwd()+}diff --git a/cmd/tui/chat/events.go b/cmd/tui/chat/events.gonew file mode 100644index 000000000..b9eba9aab--- /dev/null+++ b/cmd/tui/chat/events.go@@ -0,0 +1,374 @@+package chat++import (+ "context"+ "slices"+ "strings"+ "time"++ tea "github.com/charmbracelet/bubbletea"++ coreagent "github.com/ollama/ollama/agent"+ "github.com/ollama/ollama/api"+)++type chatAgentMsg struct {+ event coreagent.Event+}++type chatApprovalPromptMsg struct {+ request coreagent.ApprovalRequest+ reply chan<- coreagent.Approval+}++type chatRunDoneMsg struct {+ result *coreagent.RunResult+ err error+ newMessagesPersisted bool+ persistedMessages []api.Message+}++type chatCompactDoneMsg struct {+ result coreagent.CompactionResult+ err error+}++type chatCompactProgressMsg struct {+ tokens int+}++// resetStreamingState clears the transient streaming flags that every+// non-streaming event resets before applying its own state.+func (m *chatModel) resetStreamingState() {+ m.finishThinkingEntry()+ m.awaitingModel = false+ m.thinking = false+ m.thinkingTokens = 0+}++// resetRunState clears all run-progress flags (streaming plus compaction+// progress) for terminal events that fully reset the run view.+func (m *chatModel) resetRunState() {+ m.finishThinkingEntry()+ m.awaitingModel = false+ m.compacting = false+ m.compactingTokens = 0+ m.detectedToolCalls = nil+ m.thinking = false+ m.thinkingTokens = 0+}++type chatModelPreloadDoneMsg struct {+ model string+ contextWindowTokens int+ err error+}++type chatEventsClosedMsg struct{}++type chatTickMsg struct{}++func (m *chatModel) applyAgentEvent(event coreagent.Event) {+ contextChanged := false++ switch event.Type {+ case coreagent.EventThinkingDelta:+ m.awaitingModel = false+ if event.Thinking != "" {+ m.thinking = true+ if event.Tokens > 0 {+ m.thinkingTokens = max(m.thinkingTokens, event.Tokens)+ } else {+ m.thinkingTokens += approximateTokenCount(event.Thinking)+ }+ idx := m.ensureLiveAssistantMessage()+ m.liveMessages[idx].Thinking += event.Thinking+ m.syncThinkingEntry()+ contextChanged = true+ }+ case coreagent.EventMessageDelta:+ m.resetStreamingState()+ m.spinner = 0+ m.detectedToolCalls = nil+ idx := m.ensureAssistantEntry()+ m.entries[idx].content += event.Content+ m.markEntryDirty(idx)+ msgIdx := m.ensureLiveAssistantMessage()+ m.liveMessages[msgIdx].Content += event.Content+ contextChanged = true+ case coreagent.EventToolCallDetected:+ m.finishThinkingEntry()+ m.awaitingModel = m.running+ m.thinking = false+ m.thinkingTokens = 0+ m.groupCompletedToolHistory()+ m.detectedToolCalls = nil+ m.addDetectedToolCalls(event.ToolCalls)+ idx := m.ensureLiveAssistantMessage()+ m.liveMessages[idx].ToolCalls = append(m.liveMessages[idx].ToolCalls, event.ToolCalls...)+ contextChanged = true+ case coreagent.EventToolStarted:+ m.resetStreamingState()+ m.refreshContextWindowTokens(m.opts.Model)+ startedAt := time.Now()+ idx := m.findActiveToolEntry(event.ToolCallID)+ if idx < 0 {+ m.groupCompletedToolHistory()+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "tool"}))+ idx = len(m.entries) - 1+ }+ m.entries[idx].detail = event.ToolName+ m.entries[idx].label = toolInvocationLabel(event.ToolName, event.Args)+ m.entries[idx].status = "running"+ m.entries[idx].toolID = event.ToolCallID+ m.entries[idx].args = event.Args+ m.entries[idx].startedAt = startedAt+ m.applyToolOutputModeTo(idx)+ m.markEntryDirty(idx)+ case coreagent.EventToolFinished:+ m.resetStreamingState()+ m.refreshContextWindowTokens(m.opts.Model)+ if event.WorkingDir != "" {+ m.workingDir = event.WorkingDir+ }+ startedAt := m.toolStartedAt(event.ToolCallID)+ status := toolFinishedStatus(event)+ idx := m.findToolEntry(event.ToolCallID)+ if idx < 0 {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "tool"}))+ idx = len(m.entries) - 1+ }+ m.entries[idx].content = event.Content+ m.entries[idx].label = toolInvocationLabel(event.ToolName, event.Args)+ m.entries[idx].detail = event.ToolName+ m.entries[idx].status = status+ if status != "denied" {+ m.entries[idx].err = event.Error+ }+ m.entries[idx].toolID = event.ToolCallID+ m.entries[idx].args = event.Args+ m.entries[idx].startedAt = startedAt+ m.entries[idx].finishedAt = time.Now()+ m.applyToolOutputModeTo(idx)+ m.markEntryDirty(idx)+ m.liveMessages = append(m.liveMessages, api.Message{+ Role: "tool",+ Content: event.Content,+ ToolName: event.ToolName,+ ToolCallID: event.ToolCallID,+ })+ if m.running && status != "denied" && !m.hasPendingDetectedToolCalls() {+ m.awaitingModel = true+ }+ contextChanged = true+ case coreagent.EventCompacted:+ m.resetRunState()+ if len(event.Messages) > 0 {+ m.liveMessages = slices.Clone(event.Messages)+ m.messages = slices.Clone(event.Messages)+ contextChanged = true+ }+ m.status = "compacted"+ case coreagent.EventCompactionStarted:+ m.awaitingModel = false+ m.compacting = true+ m.compactingTokens = 0+ m.thinking = false+ m.thinkingTokens = 0+ m.status = "compacting"+ case coreagent.EventCompactionProgress:+ m.awaitingModel = false+ m.compacting = true+ m.thinking = false+ m.thinkingTokens = 0+ if event.Tokens > m.compactingTokens {+ m.compactingTokens = event.Tokens+ }+ case coreagent.EventCompactionSkipped:+ m.resetRunState()+ message := event.Content+ if strings.TrimSpace(message) == "" {+ message = coreagent.CompactionSkippedMessage(event.Error)+ }+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "system", content: message}))+ m.status = "compact skipped"+ case coreagent.EventError:+ m.resetRunState()+ m.eventErrorRendered = true+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "error", content: event.Error, err: event.Error}))+ }++ if contextChanged {+ m.refreshLiveContextEstimate()+ }+}++func (m *chatModel) addDetectedToolCalls(calls []api.ToolCall) {+ if len(calls) == 0 {+ return+ }+ seen := make(map[string]struct{}, len(m.detectedToolCalls)+len(calls))+ for _, entry := range m.detectedToolCalls {+ if entry.toolID != "" {+ seen[entry.toolID] = struct{}{}+ }+ }+ for _, call := range calls {+ if call.ID != "" {+ if _, ok := seen[call.ID]; ok {+ continue+ }+ seen[call.ID] = struct{}{}+ }+ args := call.Function.Arguments.ToMap()+ m.detectedToolCalls = append(m.detectedToolCalls, newChatEntry(chatEntry{+ role: "tool",+ label: toolInvocationLabel(call.Function.Name, args),+ detail: call.Function.Name,+ status: "queued",+ toolID: call.ID,+ args: args,+ }))+ }+}++func toolFinishedStatus(event coreagent.Event) string {+ switch strings.TrimSpace(event.Status) {+ case "denied":+ return "denied"+ case "disabled":+ return "disabled"+ case "done":+ return "done"+ case "error":+ return "error"+ }+ if isDeniedToolResult(event.Content) || isDeniedToolResult(event.Error) {+ return "denied"+ }+ if event.Error != "" {+ return "error"+ }+ return "done"+}++func messagesEndWithCompactionResult(messages []api.Message) bool {+ if len(messages) == 0 {+ return false+ }+ return coreagent.IsCompactionToolResult(messages[len(messages)-1])+}++func (m chatModel) awaitingToolStart() bool {+ for i := len(m.liveMessages) - 1; i >= 0; i-- {+ msg := m.liveMessages[i]+ if msg.Role != "assistant" {+ continue+ }+ if len(msg.ToolCalls) == 0 {+ return false+ }+ for _, call := range msg.ToolCalls {+ if call.ID == "" || m.findToolEntry(call.ID) < 0 {+ return true+ }+ }+ return false+ }+ return false+}++func (m *chatModel) ensureLiveAssistantMessage() int {+ if len(m.liveMessages) > 0 && m.liveMessages[len(m.liveMessages)-1].Role == "assistant" {+ return len(m.liveMessages) - 1+ }+ m.liveMessages = append(m.liveMessages, api.Message{Role: "assistant"})+ return len(m.liveMessages) - 1+}++func (m *chatModel) refreshLiveContextEstimate() {+ messages := m.liveMessages+ if len(messages) == 0 {+ messages = m.messages+ }+ m.contextTokens = m.estimatePromptTokens(messages, "")+ m.contextEstimate = true+}++//nolint:containedctx // event sinks need the session context to unblock sends on cancellation.+type chatEventSink struct {+ ctx context.Context+ ch chan<- tea.Msg+ newMessagesPersisted *bool+}++func (s chatEventSink) Emit(event coreagent.Event) error {+ if s.newMessagesPersisted != nil {+ *s.newMessagesPersisted = true+ }+ select {+ case s.ch <- chatAgentMsg{event: event}:+ return nil+ case <-s.ctx.Done():+ return s.ctx.Err()+ }+}++func waitForChatMsg(ch <-chan tea.Msg) tea.Cmd {+ if ch == nil {+ return nil+ }+ return func() tea.Msg {+ msg, ok := <-ch+ if !ok {+ return chatEventsClosedMsg{}+ }+ return msg+ }+}++func (m *chatModel) scheduleTick() tea.Cmd {+ if m.tickActive {+ return nil+ }+ m.tickActive = true+ return chatTickCmd()+}++func chatTickCmd() tea.Cmd {+ return tea.Tick(350*time.Millisecond, func(time.Time) tea.Msg {+ return chatTickMsg{}+ })+}++func preloadModelCmd(ctx context.Context, preload func(context.Context, string, *api.ThinkValue) (int, error), model string, think *api.ThinkValue) tea.Cmd {+ if preload == nil || strings.TrimSpace(model) == "" {+ return nil+ }+ if think != nil {+ copied := *think+ think = &copied+ }+ return func() tea.Msg {+ if ctx == nil {+ ctx = context.Background()+ }+ tokens, err := preload(ctx, model, think)+ return chatModelPreloadDoneMsg{model: model, contextWindowTokens: tokens, err: err}+ }+}++func isUnsupportedThinkingError(err error) bool {+ if err == nil {+ return false+ }+ text := strings.ToLower(err.Error())+ return strings.Contains(text, "does not support thinking")+}++func thinkRequestsThinking(think *api.ThinkValue) bool {+ if think == nil {+ return false+ }+ return think.Bool()+}diff --git a/cmd/tui/chat/events_test.go b/cmd/tui/chat/events_test.gonew file mode 100644index 000000000..3d24d39db--- /dev/null+++ b/cmd/tui/chat/events_test.go@@ -0,0 +1,376 @@+package chat++import (+ "strings"+ "testing"++ coreagent "github.com/ollama/ollama/agent"+ "github.com/ollama/ollama/api"+)++func TestApplyAgentEventStreamsAssistantContent(t *testing.T) {+ m := chatModel{running: true}++ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventMessageDelta, Content: "hello"})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventMessageDelta, Content: " world"})++ if len(m.entries) != 1 || m.entries[0].role != "assistant" || m.entries[0].content != "hello world" {+ t.Fatalf("entries = %#v", m.entries)+ }+ if len(m.liveMessages) != 1 || m.liveMessages[0].Content != "hello world" {+ t.Fatalf("live messages = %#v", m.liveMessages)+ }+}++func TestApplyAgentEventTracksToolLifecycle(t *testing.T) {+ m := chatModel{running: true}+ args := map[string]any{"command": "pwd"}++ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolStarted,+ ToolCallID: "call-1",+ ToolName: "bash",+ Args: args,+ })+ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolFinished,+ ToolCallID: "call-1",+ ToolName: "bash",+ Args: args,+ Content: "ok",+ })++ if len(m.entries) != 1 {+ t.Fatalf("entries = %#v", m.entries)+ }+ entry := m.entries[0]+ if entry.status != "done" || entry.content != "ok" || !strings.Contains(entry.label, "Bash") {+ t.Fatalf("tool entry = %#v", entry)+ }+ if line := stripANSI(toolStatusLine(entry)); line != `Bash("pwd")` {+ t.Fatalf("tool status line = %q, want command label", line)+ }+ if len(m.liveMessages) != 1 || m.liveMessages[0].Role != "tool" || m.liveMessages[0].Content != "ok" {+ t.Fatalf("live messages = %#v", m.liveMessages)+ }+}++func TestApplyAgentEventRendersDeniedCommandAsDenied(t *testing.T) {+ m := chatModel{running: true}+ args := map[string]any{"command": "pwd"}++ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolFinished,+ Status: "denied",+ ToolCallID: "call-1",+ ToolName: "bash",+ Args: args,+ Content: "Tool execution denied.",+ Error: "Tool execution denied.",+ })++ if len(m.entries) != 1 {+ t.Fatalf("entries = %#v", m.entries)+ }+ entry := m.entries[0]+ if entry.status != "denied" {+ t.Fatalf("tool status = %q, want denied: %#v", entry.status, entry)+ }+ if line := stripANSI(toolStatusLine(entry)); line != `Bash("pwd") denied` {+ t.Fatalf("tool status line = %q, want denied command label", line)+ }+}++func TestApplyAgentEventShowsWorkingWhileAwaitingCloudToolStart(t *testing.T) {+ args := api.NewToolCallFunctionArguments()+ args.Set("command", "pwd")+ m := chatModel{+ running: true,+ }++ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolCallDetected,+ ToolCalls: []api.ToolCall{{+ ID: "call-1",+ Function: api.ToolCallFunction{+ Name: "bash",+ Arguments: args,+ },+ }},+ })++ if line := stripANSI(m.activityLine()); !strings.Contains(line, "Working") {+ t.Fatalf("activityLine = %q, want Working while tool call is pending", line)+ }+}++func TestActivityLineShowsWorkingWhileAwaitingModelBeforeFirstEvent(t *testing.T) {+ m := chatModel{+ running: true,+ awaitingModel: true,+ spinner: 0,+ }++ if line := stripANSI(m.activityLine()); !strings.Contains(line, "Working") {+ t.Fatalf("activityLine = %q, want Working while stream is open before first event", line)+ }+}++func TestActivityLineShowsWorkingAfterAssistantContentGoesIdle(t *testing.T) {+ m := chatModel{+ running: true,+ spinner: idleWorkingDelayTicks,+ }++ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventMessageDelta, Content: "I will inspect that next."})+ if line := strings.TrimSpace(stripANSI(m.activityLine())); line != "" {+ t.Fatalf("activityLine immediately after content = %q, want quiet until the idle delay", line)+ }++ m.spinner = idleWorkingDelayTicks+ if line := stripANSI(m.activityLine()); !strings.Contains(line, "Working") {+ t.Fatalf("activityLine after idle content stream = %q, want Working while stream remains open", line)+ }+}++func TestApplyAgentEventKeepsDetectedBatchStableUntilComplete(t *testing.T) {+ firstArgs := api.NewToolCallFunctionArguments()+ firstArgs.Set("command", "pwd")+ secondArgs := api.NewToolCallFunctionArguments()+ secondArgs.Set("command", "ls")+ m := chatModel{+ running: true,+ spinner: idleWorkingDelayTicks,+ }++ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolCallDetected,+ ToolCalls: []api.ToolCall{+ {ID: "call-1", Function: api.ToolCallFunction{Name: "bash", Arguments: firstArgs}},+ {ID: "call-2", Function: api.ToolCallFunction{Name: "bash", Arguments: secondArgs}},+ },+ })+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-1", ToolName: "bash", Args: firstArgs.ToMap()})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, ToolCallID: "call-1", ToolName: "bash", Args: firstArgs.ToMap(), Content: "one"})++ if len(m.entries) != 1 {+ t.Fatalf("entries = %d, want first completed command row: %#v", len(m.entries), m.entries)+ }+ if m.entries[0].role != "tool" || m.entries[0].status != "done" {+ t.Fatalf("first command should remain stable while second is pending: %#v", m.entries[0])+ }+ if line := stripANSI(toolStatusLine(m.entries[0])); line != `Bash("pwd")` {+ t.Fatalf("completed command line = %q", line)+ }+ if line := stripANSI(m.activityLine()); !strings.Contains(line, "Working") {+ t.Fatalf("activityLine = %q, want Working while second command is pending", line)+ }++ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-2", ToolName: "bash", Args: secondArgs.ToMap()})+ if len(m.entries) != 2 {+ t.Fatalf("entries after second start = %d, want finished command plus running command: %#v", len(m.entries), m.entries)+ }+ if line := stripANSI(toolStatusLine(m.entries[0])); line != `Bash("pwd")` {+ t.Fatalf("finished command line after second start = %q", line)+ }+ if line := stripANSI(toolStatusLine(m.entries[1])); line != `Bash("ls")` {+ t.Fatalf("running command line = %q", line)+ }++ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, ToolCallID: "call-2", ToolName: "bash", Args: secondArgs.ToMap(), Content: "two"})+ if line := stripANSI(m.activityLine()); !strings.Contains(line, "Working") {+ t.Fatalf("activityLine after completed batch = %q, want Working while waiting for next model response", line)+ }+ if len(m.entries) != 2 {+ t.Fatalf("entries after batch completion = %d, want stable command rows until the next tool boundary: %#v", len(m.entries), m.entries)+ }+ for i, want := range []string{`Bash("pwd")`, `Bash("ls")`} {+ if line := stripANSI(toolStatusLine(m.entries[i])); line != want {+ t.Fatalf("completed command row %d = %q, want %q", i, line, want)+ }+ }++ thirdArgs := api.NewToolCallFunctionArguments()+ thirdArgs.Set("command", "date")+ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolCallDetected,+ ToolCalls: []api.ToolCall{+ {ID: "call-3", Function: api.ToolCallFunction{Name: "bash", Arguments: thirdArgs}},+ },+ })+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-3", ToolName: "bash", Args: thirdArgs.ToMap()})++ if len(m.entries) != 2 {+ t.Fatalf("entries after next tool boundary = %d, want grouped history plus running command: %#v", len(m.entries), m.entries)+ }+ if m.entries[0].role != "tool_group" || len(m.entries[0].tools) != 2 {+ t.Fatalf("completed detected batch should collapse at the next tool boundary: %#v", m.entries[0])+ }+ if line := stripANSI(toolGroupStatusLine(m.entries[0])); line != "Ran 2 commands" {+ t.Fatalf("grouped command line = %q", line)+ }+ if line := stripANSI(toolStatusLine(m.entries[1])); line != `Bash("date")` {+ t.Fatalf("running command line = %q", line)+ }+}++func TestApplyAgentEventDoesNotCollapsePartialDetectedBatch(t *testing.T) {+ firstArgs := api.NewToolCallFunctionArguments()+ firstArgs.Set("command", "pwd")+ secondArgs := api.NewToolCallFunctionArguments()+ secondArgs.Set("command", "ls")+ thirdArgs := api.NewToolCallFunctionArguments()+ thirdArgs.Set("command", "date")+ m := chatModel{running: true}++ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolCallDetected,+ ToolCalls: []api.ToolCall{+ {ID: "call-1", Function: api.ToolCallFunction{Name: "bash", Arguments: firstArgs}},+ {ID: "call-2", Function: api.ToolCallFunction{Name: "bash", Arguments: secondArgs}},+ {ID: "call-3", Function: api.ToolCallFunction{Name: "bash", Arguments: thirdArgs}},+ },+ })+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-1", ToolName: "bash", Args: firstArgs.ToMap()})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, ToolCallID: "call-1", ToolName: "bash", Args: firstArgs.ToMap(), Content: "one"})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-2", ToolName: "bash", Args: secondArgs.ToMap()})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, ToolCallID: "call-2", ToolName: "bash", Args: secondArgs.ToMap(), Content: "two"})++ if line := stripANSI(m.activityLine()); !strings.Contains(line, "Working") {+ t.Fatalf("activityLine before final detected call = %q, want Working while final tool is pending", line)+ }+ if len(m.entries) != 2 {+ t.Fatalf("entries before final detected call = %d, want two stable rows: %#v", len(m.entries), m.entries)+ }+ for i, want := range []string{`Bash("pwd")`, `Bash("ls")`} {+ if line := stripANSI(toolStatusLine(m.entries[i])); line != want {+ t.Fatalf("tool row %d = %q, want %q", i, line, want)+ }+ }++ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-3", ToolName: "bash", Args: thirdArgs.ToMap()})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, ToolCallID: "call-3", ToolName: "bash", Args: thirdArgs.ToMap(), Content: "three"})++ if len(m.entries) != 3 {+ t.Fatalf("entries after full detected batch = %#v, want stable tool rows until the next tool boundary", m.entries)+ }+ for i, want := range []string{`Bash("pwd")`, `Bash("ls")`, `Bash("date")`} {+ if line := stripANSI(toolStatusLine(m.entries[i])); line != want {+ t.Fatalf("tool row %d = %q, want %q", i, line, want)+ }+ }++ fourthArgs := api.NewToolCallFunctionArguments()+ fourthArgs.Set("command", "whoami")+ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolCallDetected,+ ToolCalls: []api.ToolCall{+ {ID: "call-4", Function: api.ToolCallFunction{Name: "bash", Arguments: fourthArgs}},+ },+ })+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-4", ToolName: "bash", Args: fourthArgs.ToMap()})++ if len(m.entries) != 2 || m.entries[0].role != "tool_group" || len(m.entries[0].tools) != 3 {+ t.Fatalf("entries after next detected batch starts = %#v, want one grouped history entry plus active tool", m.entries)+ }+ if line := stripANSI(toolGroupStatusLine(m.entries[0])); line != "Ran 3 commands" {+ t.Fatalf("grouped command line = %q", line)+ }+}++func TestApplyAgentEventGroupsCompletedCommandsAtNextToolBoundary(t *testing.T) {+ m := chatModel{running: true}+ firstArgs := map[string]any{"command": "pwd"}+ secondArgs := map[string]any{"command": "ls"}+ thirdArgs := map[string]any{"command": "date"}++ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-1", ToolName: "bash", Args: firstArgs})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, ToolCallID: "call-1", ToolName: "bash", Args: firstArgs, Content: "one"})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-2", ToolName: "bash", Args: secondArgs})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, ToolCallID: "call-2", ToolName: "bash", Args: secondArgs, Content: "two"})++ if len(m.entries) != 2 {+ t.Fatalf("entries after second finish = %d, want two stable command rows: %#v", len(m.entries), m.entries)+ }+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-3", ToolName: "bash", Args: thirdArgs})++ if len(m.entries) != 2 {+ t.Fatalf("entries = %d, want grouped command history plus active command: %#v", len(m.entries), m.entries)+ }+ if m.entries[0].role != "tool_group" || len(m.entries[0].tools) != 2 {+ t.Fatalf("completed commands should be grouped when the next command starts: %#v", m.entries[0])+ }+ if line := stripANSI(toolGroupStatusLine(m.entries[0])); line != "Ran 2 commands" {+ t.Fatalf("grouped command line = %q", line)+ }++ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, ToolCallID: "call-3", ToolName: "bash", Args: thirdArgs, Content: "three"})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventMessageDelta, Content: "done"})++ if len(m.entries) != 3 {+ t.Fatalf("entries after assistant content = %d, want grouped history, last command, assistant: %#v", len(m.entries), m.entries)+ }+ transcript := stripANSI(m.renderTranscript(100))+ if !strings.Contains(transcript, "• Ran 2 commands\n\n• Bash(\"date\")\n\n done") {+ t.Fatalf("tool history should stay visually separated from assistant content:\n%s", transcript)+ }+}++func TestApplyAgentEventDoesNotGroupCompletedCommandsOnMessageDelta(t *testing.T) {+ m := chatModel{running: true}+ firstArgs := map[string]any{"command": "pwd"}+ secondArgs := map[string]any{"command": "ls"}++ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-1", ToolName: "bash", Args: firstArgs})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, ToolCallID: "call-1", ToolName: "bash", Args: firstArgs, Content: "one"})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-2", ToolName: "bash", Args: secondArgs})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, ToolCallID: "call-2", ToolName: "bash", Args: secondArgs, Content: "two"})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventMessageDelta, Content: "done"})++ if len(m.entries) != 3 {+ t.Fatalf("entries = %d, want two command rows plus assistant content: %#v", len(m.entries), m.entries)+ }+ if m.entries[0].role != "tool" || m.entries[1].role != "tool" || m.entries[2].role != "assistant" {+ t.Fatalf("completed commands should not collapse on assistant content: %#v", m.entries)+ }+}++func TestApplyAgentEventGroupsPreviouslyDeniedCommandsAtNextToolBoundary(t *testing.T) {+ m := chatModel{running: true}+ firstArgs := map[string]any{"command": "pwd"}+ secondArgs := map[string]any{"command": "ls"}+ thirdArgs := map[string]any{"command": "date"}++ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, Status: "denied", ToolCallID: "call-1", ToolName: "bash", Args: firstArgs, Content: "Tool execution denied.", Error: "Tool execution denied."})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, Status: "denied", ToolCallID: "call-2", ToolName: "bash", Args: secondArgs, Content: "Tool execution denied.", Error: "Tool execution denied."})++ if len(m.entries) != 2 {+ t.Fatalf("entries = %d, want two stable denied command rows: %#v", len(m.entries), m.entries)+ }+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-3", ToolName: "bash", Args: thirdArgs})++ if len(m.entries) != 2 {+ t.Fatalf("entries = %d, want grouped denied command entry plus active command: %#v", len(m.entries), m.entries)+ }+ if m.entries[0].role != "tool_group" || len(m.entries[0].tools) != 2 {+ t.Fatalf("denied commands should be grouped at the next tool boundary: %#v", m.entries[0])+ }+ if line := stripANSI(toolGroupStatusLine(m.entries[0])); line != "Denied 2 commands" {+ t.Fatalf("grouped command line = %q", line)+ }+ if line := stripANSI(toolStatusLine(m.entries[1])); line != `Bash("date")` {+ t.Fatalf("running command line = %q", line)+ }+}++func TestMessagesEndWithCompactionResult(t *testing.T) {+ messages := []api.Message{{+ Role: "tool",+ ToolName: coreagent.CompactionToolName,+ ToolCallID: coreagent.CompactionToolCallID,+ Content: coreagent.CompactionSummaryMessagePrefix + "summary",+ }}+ if !messagesEndWithCompactionResult(messages) {+ t.Fatal("expected compaction result")+ }+}diff --git a/cmd/tui/chat/input.go b/cmd/tui/chat/input.gonew file mode 100644index 000000000..7de4a656c--- /dev/null+++ b/cmd/tui/chat/input.go@@ -0,0 +1,1305 @@+package chat++import (+ "context"+ "fmt"+ "os"+ "path/filepath"+ "regexp"+ "slices"+ "sort"+ "strconv"+ "strings"+ "unicode"+ "unicode/utf8"++ tea "github.com/charmbracelet/bubbletea"+ "github.com/charmbracelet/lipgloss"+ "github.com/mattn/go-runewidth"++ coreagent "github.com/ollama/ollama/agent"+ "github.com/ollama/ollama/api"+ "github.com/ollama/ollama/cmd/internal/filedata"+)++type chatSlashCommand struct {+ name string+ usage string+ description string+ aliases []string+ hidden bool+}++type chatCompletion struct {+ value string+ label string+ description string+ directory bool+}++const (+ chatPromptPrefix = ""+ inputBoxHorizontalPadding = 1+ inputCursorGlyph = "█"+ inputCursorMarker = "\x00"+ maxInputBoxBodyLines = 12+)++const (+ pastedTextPlaceholderMinRunes = 1000+ pastedTextPlaceholderMinLines = 8+)++var chatSlashCommands = []chatSlashCommand{+ {name: "/clear", description: "clear this chat"},+ {name: "/model", description: "switch models"},+ {name: "/new", description: "start a new chat"},+ {name: "/think", description: "set thinking mode"},+ {name: "/tools", description: "toggle tools on or off"},+ {name: "/compact", description: "summarize older context"},+ {name: "/help", description: "show commands", aliases: []string{"/?"}},+ {name: "/bye", description: "exit", aliases: []string{"/exit"}},+ {name: "/prompt", description: "show full prompt, tools, and messages"},+ {name: "/save", usage: "/save <filename>", description: "save request JSON; saved as <filename>.json"},+}++func (m *chatModel) handleSubmit() (tea.Model, tea.Cmd) {+ m.syncInputPlaceholders()+ input := strings.TrimSpace(string(m.input))+ if selected, ok := m.selectedSlashCommand(); ok {+ input = selected+ }+ if input == "" {+ return *m, nil+ }+ _, _, hasSlashCommand := slashCommandInvocation(input)+ if (m.running || m.compacting) && !hasSlashCommand {+ m.status = "wait for current response"+ return *m, nil+ }++ attachments := cloneInputAttachments(m.inputAttachments)+ pastedTexts := cloneInputPastedTexts(m.inputPastedTexts)+ m.input = nil+ m.inputCursor = 0+ m.inputCursorSet = false+ m.inputAttachments = attachments+ m.inputPastedTexts = pastedTexts+ m.complete = 0+ m.resetPromptHistoryCursor()+ return m.submitInput(input)+}++func (m chatModel) selectedSlashCommand() (string, bool) {+ input := strings.TrimSpace(string(m.input))+ if !strings.HasPrefix(input, "/") {+ return "", false+ }+ completions := m.slashCompletions()+ if len(completions) == 0 || !completionIsSelectable(completions) {+ return "", false+ }+ return completions[clamp(m.complete, 0, len(completions)-1)].value, true+}++func (m *chatModel) submitInput(input string) (tea.Model, tea.Cmd) {+ command, args, _ := slashCommandInvocation(input)+ if command != "" {+ input = strings.TrimSpace(command + " " + args)+ }++ switch {+ case command == "/bye":+ m.quitting = true+ return *m, m.quitCmd()+ case command == "/help":+ m.entries = append(m.entries, newSlashEntry(m.helpSummary()))+ return *m, nil+ case command == "/clear" && args == "":+ return m.resetChat("cleared")+ case command == "/model":+ return m.openModelPicker(args)+ case command == "/think" && args == "":+ return m.openThinkPicker()+ case command == "/think":+ return m.handleThinkCommand(args)+ case command == "/tools":+ return m.handleToolsCommand(args)+ case command == "/prompt":+ return m.handlePromptCommand(args)+ case command == "/save":+ return m.handleSaveCommand(args)+ case command == "/new" && args == "":+ return m.resetChat("new chat")+ case command == "/compact" && args == "":+ return m.startManualCompaction()+ case strings.HasPrefix(input, "/") && m.slashInputIsMultimodalFile(input):+ return m.startRun(input)+ case strings.HasPrefix(input, "/"):+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "error", content: fmt.Sprintf("Unknown command %q", strings.Fields(input)[0])}))+ return *m, nil+ }++ return m.startRun(input)+}++func (m *chatModel) handleToolsCommand(args string) (tea.Model, tea.Cmd) {+ if strings.TrimSpace(args) != "" {+ m.status = "error"+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "error", content: "usage: /tools"}))+ return *m, nil+ }+ if m.opts.ToolsDisabled {+ m.opts.ToolsDisabled = false+ if m.opts.ToolRegistryForModel != nil {+ m.opts.Tools = m.opts.ToolRegistryForModel(m.ctx, m.opts.Model)+ }+ m.status = "tools on"+ } else {+ m.opts.ToolsDisabled = true+ m.status = "tools off"+ }+ return *m, nil+}++func (m chatModel) slashInputIsMultimodalFile(input string) bool {+ if !m.opts.MultiModal {+ return false+ }+ fields := strings.Fields(input)+ if len(fields) == 0 {+ return false+ }+ for _, file := range filedata.ExtractNames(input) {+ if strings.HasPrefix(file, fields[0]) {+ return true+ }+ }+ return false+}++func initialPromptHistory(ctx context.Context, opts Options) []string {+ var prompts []string+ for _, msg := range opts.Messages {+ if msg.Role == "user" {+ prompts = append(prompts, msg.Content)+ }+ }+ return normalizePromptHistory(prompts)+}++func normalizePromptHistory(prompts []string) []string {+ history := make([]string, 0, min(len(prompts), maxPromptHistory))+ for _, prompt := range prompts {+ prompt = strings.TrimSpace(prompt)+ if prompt == "" || coreagent.IsCompactionSummary(api.Message{Role: "user", Content: prompt}) {+ continue+ }+ history = append(history, prompt)+ }+ if len(history) > maxPromptHistory {+ history = history[len(history)-maxPromptHistory:]+ }+ return history+}++func (m *chatModel) addPromptHistory(prompt string) {+ prompt = strings.TrimSpace(prompt)+ if prompt == "" {+ return+ }+ m.promptHistory = append(m.promptHistory, prompt)+ if len(m.promptHistory) > maxPromptHistory {+ m.promptHistory = m.promptHistory[len(m.promptHistory)-maxPromptHistory:]+ }+ m.resetPromptHistoryCursor()+}++func (m *chatModel) movePromptHistory(delta int) bool {+ if len(m.promptHistory) == 0 || delta == 0 {+ return false+ }+ if !m.promptActive {+ if delta > 0 {+ return false+ }+ m.promptDraft = slices.Clone(m.input)+ m.promptCursor = len(m.promptHistory) - 1+ m.promptActive = true+ } else {+ m.promptCursor += delta+ if m.promptCursor >= len(m.promptHistory) {+ m.input = slices.Clone(m.promptDraft)+ m.inputCursor = len(m.input)+ m.inputCursorSet = true+ m.inputAttachments = nil+ m.inputPastedTexts = nil+ m.resetPromptHistoryCursor()+ m.complete = 0+ return true+ }+ if m.promptCursor < 0 {+ m.promptCursor = 0+ }+ }++ m.inputPastedTexts = nil+ input := m.promptHistory[m.promptCursor]+ if placeholder, ok := m.pastedTextPlaceholder(input); ok {+ input = placeholder+ }+ m.input = []rune(input)+ m.inputCursor = len(m.input)+ m.inputCursorSet = true+ m.inputAttachments = nil+ m.complete = 0+ return true+}++func (m *chatModel) resetPromptHistoryCursor() {+ m.promptActive = false+ m.promptCursor = 0+ m.promptDraft = nil+}++func (m *chatModel) insertInputNewline() {+ m.insertInputRunes([]rune{'\n'})+}++func (m *chatModel) insertInputRunesFromKey(runes []rune, pasted bool) {+ if len(runes) == 0 {+ return+ }+ if m.opts.MultiModal && (pasted || len(runes) > 1) && m.insertInputFilePlaceholders(string(runes)) {+ return+ }+ if pasted && m.insertPastedTextPlaceholder(string(runes)) {+ return+ }+ m.insertInputRunes(runes)+}++func (m *chatModel) insertInputFilePlaceholders(input string) bool {+ cleaned, files, err := filedata.ExtractWithFiles(input)+ if err != nil {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "error", content: err.Error(), err: err.Error()}))+ m.status = "attachment failed"+ return true+ }+ if len(files) == 0 {+ return false+ }++ var parts []string+ if strings.TrimSpace(cleaned) != "" {+ if placeholder, ok := m.pastedTextPlaceholder(cleaned); ok {+ parts = append(parts, placeholder)+ } else {+ parts = append(parts, cleaned)+ }+ }+ for _, file := range files {+ kind := filedata.Kind(file.Path)+ placeholder := m.nextInputAttachmentPlaceholder(kind)+ m.inputAttachments = append(m.inputAttachments, chatInputAttachment{+ placeholder: placeholder,+ kind: kind,+ data: file.Data,+ })+ parts = append(parts, placeholder)+ }+ m.insertInputRunes([]rune(strings.Join(parts, " ")))+ return true+}++func (m *chatModel) insertPastedTextPlaceholder(input string) bool {+ placeholder, ok := m.pastedTextPlaceholder(input)+ if !ok {+ return false+ }+ m.insertInputRunes([]rune(placeholder))+ return true+}++func (m *chatModel) pastedTextPlaceholder(input string) (string, bool) {+ if !shouldCollapsePastedText(input) {+ return "", false+ }+ placeholder := m.nextInputPastedTextPlaceholder(input)+ m.inputPastedTexts = append(m.inputPastedTexts, chatInputPastedText{+ placeholder: placeholder,+ content: input,+ })+ return placeholder, true+}++func shouldCollapsePastedText(input string) bool {+ trimmed := strings.TrimSpace(input)+ if trimmed == "" {+ return false+ }+ return len([]rune(trimmed)) >= pastedTextPlaceholderMinRunes || pastedTextLineCount(trimmed) >= pastedTextPlaceholderMinLines+}++func pastedTextLineCount(input string) int {+ if input == "" {+ return 0+ }+ return strings.Count(input, "\n") + 1+}++func (m *chatModel) insertInputRunes(runes []rune) {+ runes = normalizeInputRunes(runes)+ if len(runes) == 0 {+ return+ }+ m.resetPromptHistoryCursor()+ m.disarmQuit()+ cursor := m.normalizedInputCursor()+ next := make([]rune, 0, len(m.input)+len(runes))+ next = append(next, m.input[:cursor]...)+ next = append(next, runes...)+ next = append(next, m.input[cursor:]...)+ m.input = next+ m.inputCursor = cursor + len(runes)+ m.inputCursorSet = true+ m.complete = 0+}++func normalizeInputRunes(runes []rune) []rune {+ for _, r := range runes {+ if r == '\r' {+ return normalizeInputRunesSlow(runes)+ }+ }+ return runes+}++func normalizeInputRunesSlow(runes []rune) []rune {+ out := make([]rune, 0, len(runes))+ for i := 0; i < len(runes); i++ {+ if runes[i] != '\r' {+ out = append(out, runes[i])+ continue+ }+ out = append(out, '\n')+ if i+1 < len(runes) && runes[i+1] == '\n' {+ i+++ }+ }+ return out+}++func (m *chatModel) deleteInputBackward() {+ cursor := m.normalizedInputCursor()+ if cursor <= 0 {+ return+ }+ start, end, ok := m.placeholderRangeForBackspace(cursor)+ if !ok {+ start, end = cursor-1, cursor+ }+ m.deleteInputRange(start, end)+}++func (m *chatModel) deleteInputWordBackward() {+ cursor := m.normalizedInputCursor()+ if cursor <= 0 {+ return+ }+ start, end, ok := m.placeholderRangeForWordDelete(cursor)+ if !ok {+ start, end = previousInputWordStart(m.input, cursor), cursor+ }+ m.deleteInputRange(start, end)+}++func (m *chatModel) deleteInputForward() {+ cursor := m.normalizedInputCursor()+ if cursor >= len(m.input) {+ return+ }+ start, end, ok := m.placeholderRangeForForwardDelete(cursor)+ if !ok {+ start, end = cursor, cursor+1+ }+ m.deleteInputRange(start, end)+}++func (m *chatModel) deleteInputRange(start, end int) {+ start = clamp(start, 0, len(m.input))+ end = clamp(end, start, len(m.input))+ m.input = append(slices.Clone(m.input[:start]), m.input[end:]...)+ m.inputCursor = start+ m.inputCursorSet = true+ m.complete = 0+ m.syncInputPlaceholders()+}++func (m chatModel) placeholderRangeForBackspace(cursor int) (int, int, bool) {+ cursor = clamp(cursor, 0, len(m.input))+ input := string(m.input)+ for _, placeholder := range m.inputPlaceholders() {+ if placeholder == "" {+ continue+ }+ start, end, ok := inputPlaceholderRuneRange(input, placeholder)+ if ok && cursor > start && cursor <= end {+ return start, end, true+ }+ }+ return 0, 0, false+}++func (m chatModel) placeholderRangeForForwardDelete(cursor int) (int, int, bool) {+ cursor = clamp(cursor, 0, len(m.input))+ input := string(m.input)+ for _, placeholder := range m.inputPlaceholders() {+ if placeholder == "" {+ continue+ }+ start, end, ok := inputPlaceholderRuneRange(input, placeholder)+ if ok && cursor >= start && cursor < end {+ return start, end, true+ }+ }+ return 0, 0, false+}++func (m chatModel) placeholderRangeForWordDelete(cursor int) (int, int, bool) {+ cursor = clamp(cursor, 0, len(m.input))+ end := cursor+ for end > 0 && unicode.IsSpace(m.input[end-1]) {+ end--+ }+ input := string(m.input)+ for _, placeholder := range m.inputPlaceholders() {+ if placeholder == "" {+ continue+ }+ start, placeholderEnd, ok := inputPlaceholderRuneRange(input, placeholder)+ if ok && end > start && end <= placeholderEnd {+ return start, cursor, true+ }+ }+ return 0, 0, false+}++func (m chatModel) inputPlaceholders() []string {+ placeholders := make([]string, 0, len(m.inputAttachments)+len(m.inputPastedTexts))+ for _, attachment := range m.inputAttachments {+ placeholders = append(placeholders, attachment.placeholder)+ }+ for _, pastedText := range m.inputPastedTexts {+ placeholders = append(placeholders, pastedText.placeholder)+ }+ return placeholders+}++func inputPlaceholderRuneRange(input, placeholder string) (int, int, bool) {+ byteStart := strings.Index(input, placeholder)+ if byteStart < 0 {+ return 0, 0, false+ }+ start := len([]rune(input[:byteStart]))+ end := start + len([]rune(placeholder))+ return start, end, true+}++func previousInputWordStart(input []rune, cursor int) int {+ end := clamp(cursor, 0, len(input))+ for end > 0 && unicode.IsSpace(input[end-1]) {+ end--+ }+ start := end+ for start > 0 && !unicode.IsSpace(input[start-1]) {+ start--+ }+ return start+}++func (m *chatModel) syncInputPlaceholders() {+ m.inputAttachments = m.activeInputAttachmentsFor(string(m.input))+ m.inputPastedTexts = m.activeInputPastedTextsFor(string(m.input))+}++func (m chatModel) activeInputAttachmentsFor(input string) []chatInputAttachment {+ if len(m.inputAttachments) == 0 {+ return nil+ }+ active := make([]chatInputAttachment, 0, len(m.inputAttachments))+ for _, attachment := range m.inputAttachments {+ if strings.Contains(input, attachment.placeholder) {+ active = append(active, attachment)+ }+ }+ return active+}++func cloneInputAttachments(in []chatInputAttachment) []chatInputAttachment {+ return slices.Clone(in)+}++type chatInputPastedText struct {+ placeholder string+ content string+}++func (m chatModel) activeInputPastedTextsFor(input string) []chatInputPastedText {+ if len(m.inputPastedTexts) == 0 {+ return nil+ }+ active := make([]chatInputPastedText, 0, len(m.inputPastedTexts))+ for _, pastedText := range m.inputPastedTexts {+ if strings.Contains(input, pastedText.placeholder) {+ active = append(active, pastedText)+ }+ }+ return active+}++func cloneInputPastedTexts(in []chatInputPastedText) []chatInputPastedText {+ return slices.Clone(in)+}++func (m chatModel) expandPastedTextPlaceholders(input string) string {+ for _, pastedText := range m.activeInputPastedTextsFor(input) {+ input = strings.ReplaceAll(input, pastedText.placeholder, pastedText.content)+ }+ return input+}++func (m *chatModel) nextInputPastedTextPlaceholder(content string) string {+ if m.nextPastedTextID <= 0 {+ m.nextPastedTextID = 1+ }+ id := m.nextPastedTextID+ m.nextPastedTextID+++ return fmt.Sprintf("[Pasted text #%d +%d lines]", id, pastedTextLineCount(strings.TrimSpace(content)))+}++func (m *chatModel) nextInputAttachmentPlaceholder(kind string) string {+ label := inputAttachmentLabel(kind)+ switch kind {+ case "audio":+ id := m.nextAudioID+ m.nextAudioID+++ return fmt.Sprintf("[%s #%d]", label, id)+ default:+ id := m.nextImageID+ m.nextImageID+++ return fmt.Sprintf("[%s #%d]", label, id)+ }+}++func inputAttachmentLabel(kind string) string {+ switch kind {+ case "audio":+ return "Audio"+ default:+ return "Image"+ }+}++var (+ inputAttachmentPlaceholderPattern = regexp.MustCompile(`\[(Image|Audio) #([0-9]+)\]`)+ inputPastedTextPlaceholderPattern = regexp.MustCompile(`\[Pasted text #([0-9]+) \+[0-9]+ lines?\]`)+)++func nextInputAttachmentIDsFromMessages(messages []api.Message) (imageID int, audioID int) {+ for _, msg := range messages {+ for _, match := range inputAttachmentPlaceholderPattern.FindAllStringSubmatch(msg.Content, -1) {+ if len(match) != 3 {+ continue+ }+ id, err := strconv.Atoi(match[2])+ if err != nil {+ continue+ }+ switch match[1] {+ case "Image":+ imageID = max(imageID, id+1)+ case "Audio":+ audioID = max(audioID, id+1)+ }+ }+ }+ return imageID, audioID+}++func nextInputPastedTextIDFromMessages(messages []api.Message) int {+ nextID := 1+ for _, msg := range messages {+ for _, match := range inputPastedTextPlaceholderPattern.FindAllStringSubmatch(msg.Content, -1) {+ if len(match) != 2 {+ continue+ }+ id, err := strconv.Atoi(match[1])+ if err != nil {+ continue+ }+ nextID = max(nextID, id+1)+ }+ }+ return nextID+}++func (m *chatModel) moveInputCursorHorizontal(delta int) bool {+ if delta == 0 {+ return false+ }+ cursor := clamp(m.normalizedInputCursor()+delta, 0, len(m.input))+ if cursor == m.normalizedInputCursor() {+ return false+ }+ m.inputCursor = cursor+ m.inputCursorSet = true+ m.resetPromptHistoryCursor()+ m.complete = 0+ return true+}++func (m *chatModel) moveInputCursorToLineStart() bool {+ cursor := m.normalizedInputCursor()+ start, _ := inputLineBounds(m.input, cursor)+ if start == cursor {+ return false+ }+ m.inputCursor = start+ m.inputCursorSet = true+ m.resetPromptHistoryCursor()+ m.complete = 0+ return true+}++func (m *chatModel) moveInputCursorToLineEnd() bool {+ cursor := m.normalizedInputCursor()+ _, end := inputLineBounds(m.input, cursor)+ if end == cursor {+ return false+ }+ m.inputCursor = end+ m.inputCursorSet = true+ m.resetPromptHistoryCursor()+ m.complete = 0+ return true+}++func (m *chatModel) moveInputCursorWord(delta int) bool {+ if delta == 0 || len(m.input) == 0 {+ return false+ }+ cursor := m.normalizedInputCursor()+ target := cursor+ if delta < 0 {+ for target > 0 && unicode.IsSpace(m.input[target-1]) {+ target--+ }+ for target > 0 && !unicode.IsSpace(m.input[target-1]) {+ target--+ }+ } else {+ for target < len(m.input) && !unicode.IsSpace(m.input[target]) {+ target+++ }+ for target < len(m.input) && unicode.IsSpace(m.input[target]) {+ target+++ }+ }+ if target == cursor {+ return false+ }+ m.inputCursor = target+ m.inputCursorSet = true+ m.resetPromptHistoryCursor()+ m.complete = 0+ return true+}++func (m *chatModel) handleInputAltRunes(runes []rune) bool {+ if len(runes) != 1 {+ return false+ }+ switch runes[0] {+ case 'b', 'B':+ m.moveInputCursorWord(-1)+ return true+ case 'f', 'F':+ m.moveInputCursorWord(1)+ return true+ default:+ return false+ }+}++func (m *chatModel) moveInputCursorVertical(delta int) bool {+ if delta == 0 || len(m.input) == 0 {+ return false+ }+ cursor := m.normalizedInputCursor()+ lineStart, lineEnd := inputLineBounds(m.input, cursor)+ column := cursor - lineStart+ var targetStart, targetEnd int+ if delta < 0 {+ if lineStart == 0 {+ return false+ }+ targetEnd = lineStart - 1+ targetStart, _ = inputLineBounds(m.input, targetEnd)+ } else {+ if lineEnd >= len(m.input) {+ return false+ }+ targetStart = lineEnd + 1+ _, targetEnd = inputLineBounds(m.input, targetStart)+ }+ target := min(targetStart+column, targetEnd)+ m.inputCursor = target+ m.inputCursorSet = true+ m.resetPromptHistoryCursor()+ m.complete = 0+ return true+}++func inputLineBounds(input []rune, cursor int) (int, int) {+ cursor = clamp(cursor, 0, len(input))+ start := cursor+ for start > 0 && input[start-1] != '\n' {+ start--+ }+ end := cursor+ for end < len(input) && input[end] != '\n' {+ end+++ }+ return start, end+}++func (m chatModel) normalizedInputCursor() int {+ if !m.inputCursorSet {+ return len(m.input)+ }+ return clamp(m.inputCursor, 0, len(m.input))+}++func inputWithCursor(input []rune, cursor int) string {+ cursor = clamp(cursor, 0, len(input))+ next := make([]rune, 0, len(input)+1)+ next = append(next, input[:cursor]...)+ next = append(next, []rune(inputCursorMarker)...)+ next = append(next, input[cursor:]...)+ return string(next)+}++func isShiftEnterCSI(msg tea.Msg) bool {+ switch fmt.Sprint(msg) {+ case "?CSI[49 51 59 50 117]?", // \x1b[13;2u+ "?CSI[49 51 59 50 126]?", // \x1b[13;2~+ "?CSI[50 55 59 50 59 49 51 126]?": // \x1b[27;2;13~+ return true+ default:+ return false+ }+}++func (m chatModel) emptyInputPlaceholder() string {+ if m.promptDebug != nil || m.modelPicker != nil || m.thinkPicker != nil || m.approvalPrompt != nil || m.cloudAuthPrompt != nil {+ return ""+ }+ if len(m.entries) > 0 || len(m.messages) > 0 || len(m.input) > 0 || len(m.inputAttachments) > 0 || len(m.inputPastedTexts) > 0 {+ return ""+ }+ return m.emptyChatHint()+}++func renderInputBoxLines(input string, cursor int, width, maxBodyLines int, placeholder string) []string {+ if width < 12 {+ width = 12+ }+ if maxBodyLines < 1 {+ maxBodyLines = 1+ }++ prefix := chatPromptPrefix+ continuationPrefix := strings.Repeat(" ", lipgloss.Width(prefix))+ prefixWidth := lipgloss.Width(prefix)+ innerWidth := max(1, width-2)+ contentWidth := max(1, innerWidth-inputBoxHorizontalPadding*2)+ bodyWidth := max(1, contentWidth-prefixWidth)++ var raw []string+ placeholderMode := input == "" && strings.TrimSpace(placeholder) != ""+ if input == "" && strings.TrimSpace(placeholder) != "" {+ raw = renderInputPromptRawLines(inputWithCursor([]rune(placeholder), 0), prefix, continuationPrefix, bodyWidth)+ } else {+ if cursor >= 0 {+ input = inputWithCursor([]rune(input), cursor)+ }+ raw = renderInputPromptRawLines(input, prefix, continuationPrefix, bodyWidth)+ }+ if len(raw) > maxBodyLines {+ raw = slices.Clone(raw[len(raw)-maxBodyLines:])+ raw[0] = truncateInputLine(continuationPrefix+trimInputPromptPrefix(raw[0]), contentWidth)+ }++ lines := make([]string, 0, len(raw)+2)+ lines = append(lines, chatInputBorderStyle.Render(inputBoxTopBorderLine(width)))+ for i, line := range raw {+ rendered := line+ if placeholderMode {+ if i == 0 && strings.HasPrefix(line, prefix) {+ rest := strings.TrimPrefix(line, prefix)+ if strings.HasPrefix(rest, inputCursorMarker) {+ rendered = chatUserStyle.Render(prefix) + renderInputTextWithCursorStyle(rest, chatInputPlaceholderStyle)+ lines = append(lines, renderInputBoxBodyLine(rendered, contentWidth))+ continue+ }+ rendered = chatUserStyle.Render(prefix) + chatInputPlaceholderStyle.Render(rest)+ lines = append(lines, renderInputBoxBodyLine(rendered, contentWidth))+ continue+ }+ if strings.HasPrefix(line, continuationPrefix) {+ rendered = chatInputPlaceholderStyle.Render(continuationPrefix + strings.TrimPrefix(line, continuationPrefix))+ lines = append(lines, renderInputBoxBodyLine(rendered, contentWidth))+ continue+ }+ rendered = chatInputPlaceholderStyle.Render(line)+ lines = append(lines, renderInputBoxBodyLine(rendered, contentWidth))+ continue+ }+ lines = append(lines, renderInputBoxBodyLine(renderInputTextWithCursor(rendered), contentWidth))+ }+ lines = append(lines, chatInputBorderStyle.Render(inputBoxBottomBorderLine(width)))+ return lines+}++func renderInputTextWithCursor(line string) string {+ return renderInputTextWithCursorStyle(line, chatUserStyle)+}++func renderInputTextWithCursorStyle(line string, style lipgloss.Style) string {+ before, after, ok := strings.Cut(line, inputCursorMarker)+ if !ok {+ return style.Render(line)+ }+ cell, rest := inputCursorCell(after)+ return style.Render(before) + renderInputCursorCell(cell) + style.Render(rest)+}++func inputCursorCell(after string) (string, string) {+ if after == "" {+ return "", ""+ }+ r, size := utf8.DecodeRuneInString(after)+ if r == '\n' {+ return "", after+ }+ return after[:size], after[size:]+}++func renderInputCursorCell(cell string) string {+ if cell == "" {+ return chatBlankCursorStyle.Render(inputCursorGlyph)+ }+ return chatCursorStyle.Render(cell)+}++func renderInputPromptRawLines(text, prefix, continuationPrefix string, width int) []string {+ if width <= 0 {+ width = 1+ }+ text = string(normalizeInputRunes([]rune(text)))+ body := wrapChatText(text, width)+ for i, line := range body {+ if i == 0 {+ body[i] = prefix + line+ continue+ }+ body[i] = continuationPrefix + line+ }+ if len(body) == 0 {+ return []string{prefix}+ }+ return body+}++func trimInputPromptPrefix(line string) string {+ for _, prefix := range []string{chatPromptPrefix, strings.Repeat(" ", lipgloss.Width(chatPromptPrefix))} {+ if prefix == "" {+ continue+ }+ if strings.HasPrefix(line, prefix) {+ return strings.TrimPrefix(line, prefix)+ }+ }+ return strings.TrimSpace(line)+}++func inputBoxTopBorderLine(width int) string {+ return inputBoxBorderLine(width, "╭", "╮")+}++func inputBoxBottomBorderLine(width int) string {+ return inputBoxBorderLine(width, "╰", "╯")+}++func inputBoxBorderLine(width int, left, right string) string {+ if width < 4 {+ width = 4+ }+ return left + strings.Repeat("─", max(0, width-2)) + right+}++func renderInputBoxBodyLine(line string, width int) string {+ padding := strings.Repeat(" ", inputBoxHorizontalPadding)+ return chatInputBorderStyle.Render("│") + padding + padRenderedLine(line, width) + padding + chatInputBorderStyle.Render("│")+}++func padRenderedLine(line string, width int) string {+ if width <= 0 {+ return line+ }+ if renderedWidth := lipgloss.Width(line); renderedWidth < width {+ return line + strings.Repeat(" ", width-renderedWidth)+ }+ return line+}++func truncateInputLine(line string, width int) string {+ if width <= 0 {+ return line+ }+ if runewidth.StringWidth(line) <= width {+ return line+ }+ return runewidth.Truncate(line, width, "")+}++func (m chatModel) slashCommandLines(width int) []string {+ return m.renderCompletions(m.slashCompletions(), width)+}++func (m chatModel) completionLines(width int) []string {+ return m.renderCompletions(m.completions(), width)+}++func (m chatModel) renderCompletions(completions []chatCompletion, width int) []string {+ if len(completions) == 0 {+ return nil+ }+ selected := clamp(m.complete, 0, len(completions)-1)+ start, end := completionWindow(len(completions), selected, m.completionVisibleLimit(len(completions)))+ completions = completions[start:end]++ nameWidth := 0+ for _, completion := range completions {+ nameWidth = max(nameWidth, lipgloss.Width(completion.label))+ }++ lines := make([]string, 0, len(completions))+ for i, completion := range completions {+ marker := " "+ if start+i == selected {+ marker = "› "+ }+ name := chatCommandNameStyle.Render(completion.label)+ padding := strings.Repeat(" ", max(1, nameWidth-lipgloss.Width(completion.label)+2))+ line := marker + name + padding + chatMetaStyle.Render(completion.description)+ lines = append(lines, truncateRenderedLine(line, width))+ }+ return lines+}++func (m chatModel) completionVisibleLimit(total int) int {+ if strings.HasPrefix(strings.TrimSpace(string(m.input)), "/") {+ return min(maxSlashCompletions, total)+ }+ return total+}++func completionWindow(total, selected, limit int) (int, int) {+ if total <= 0 || limit <= 0 || limit >= total {+ return 0, total+ }+ selected = clamp(selected, 0, total-1)+ start := selected - limit + 1+ if start < 0 {+ start = 0+ }+ end := start + limit+ if end > total {+ end = total+ start = max(0, end-limit)+ }+ return start, end+}++func (m chatModel) completions() []chatCompletion {+ if completions := m.slashCompletions(); len(completions) > 0 {+ return completions+ }+ return m.mentionCompletions()+}++func (m chatModel) slashCompletions() []chatCompletion {+ input := strings.TrimSpace(string(m.input))+ if !strings.HasPrefix(input, "/") {+ return nil+ }++ commands := matchingSlashCommands(input)+ if len(commands) == 0 {+ return []chatCompletion{{label: "No matching commands"}}+ }++ completions := make([]chatCompletion, 0, len(commands))+ for _, command := range commands {+ completions = append(completions, chatCompletion{+ value: command.name,+ label: command.name,+ description: command.description,+ })+ }+ return completions+}++func matchingSlashCommands(input string) []chatSlashCommand {+ prefix := strings.ToLower(strings.TrimSpace(input))+ if prefix == "" {+ return nil+ }++ var commands []chatSlashCommand+ for _, command := range chatSlashCommands {+ if command.hidden {+ continue+ }+ if command.matchesPrefix(prefix) {+ commands = append(commands, command)+ }+ }+ return commands+}++func (c chatSlashCommand) matchesPrefix(prefix string) bool {+ if strings.HasPrefix(c.name, prefix) {+ return true+ }+ for _, alias := range c.aliases {+ if strings.HasPrefix(alias, prefix) {+ return true+ }+ }+ return false+}++func slashCommandInvocation(input string) (string, string, bool) {+ input = strings.TrimSpace(input)+ if !strings.HasPrefix(input, "/") {+ return "", "", false+ }+ token, args, _ := strings.Cut(input, " ")+ token = strings.ToLower(token)+ for _, command := range chatSlashCommands {+ if command.name == token || slices.Contains(command.aliases, token) {+ return command.name, strings.TrimSpace(args), true+ }+ }+ return "", "", false+}++func (m chatModel) mentionCompletions() []chatCompletion {+ input := string(m.input)+ _, query, ok := activeMentionToken(input)+ if !ok {+ return nil+ }++ workingDir := m.currentWorkingDir()+ if strings.TrimSpace(workingDir) == "" {+ var err error+ workingDir, err = os.Getwd()+ if err != nil {+ return []chatCompletion{{label: "No working directory"}}+ }+ }++ dirPart, prefix := splitMentionQuery(query)+ dir, err := resolveCompletionDir(workingDir, dirPart)+ if err != nil {+ return []chatCompletion{{label: "No matching files"}}+ }+ entries, err := os.ReadDir(dir)+ if err != nil {+ return []chatCompletion{{label: "No matching files"}}+ }+ sort.SliceStable(entries, func(i, j int) bool {+ if entries[i].IsDir() != entries[j].IsDir() {+ return entries[i].IsDir()+ }+ return strings.ToLower(entries[i].Name()) < strings.ToLower(entries[j].Name())+ })++ includeHidden := strings.HasPrefix(prefix, ".")+ completions := make([]chatCompletion, 0, 8)+ for _, entry := range entries {+ name := entry.Name()+ if !includeHidden && strings.HasPrefix(name, ".") {+ continue+ }+ if !strings.HasPrefix(strings.ToLower(name), strings.ToLower(prefix)) {+ continue+ }+ value := filepath.ToSlash(filepath.Join(dirPart, name))+ label := "@" + value+ description := "file"+ if entry.IsDir() {+ value += "/"+ label += "/"+ description = "directory"+ }+ completions = append(completions, chatCompletion{+ value: value,+ label: label,+ description: description,+ directory: entry.IsDir(),+ })+ if len(completions) >= 8 {+ break+ }+ }+ if len(completions) == 0 {+ return []chatCompletion{{label: "No matching files"}}+ }+ return completions+}++func activeMentionToken(input string) (int, string, bool) {+ runes := []rune(input)+ start := len(runes)+ for start > 0 && !unicode.IsSpace(runes[start-1]) {+ start--+ }+ token := string(runes[start:])+ if !strings.HasPrefix(token, "@") {+ return 0, "", false+ }+ return start, token[1:], true+}++func splitMentionQuery(query string) (string, string) {+ query = filepath.ToSlash(query)+ index := strings.LastIndex(query, "/")+ if index < 0 {+ return ".", query+ }+ return query[:index+1], query[index+1:]+}++func resolveCompletionDir(workingDir, dir string) (string, error) {+ if filepath.IsAbs(dir) {+ return "", fmt.Errorf("absolute paths are not allowed")+ }+ base := workingDir+ if base == "" {+ base = "."+ }+ base, err := filepath.Abs(base)+ if err != nil {+ return "", err+ }+ resolved := filepath.Clean(filepath.Join(base, dir))+ rel, err := filepath.Rel(base, resolved)+ if err != nil {+ return "", err+ }+ if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {+ return "", fmt.Errorf("path escapes working directory")+ }+ return resolved, nil+}++func (m *chatModel) moveCompletion(delta int) bool {+ completions := m.completions()+ if len(completions) == 0 || !completionIsSelectable(completions) {+ return false+ }+ m.complete = (m.complete + delta) % len(completions)+ if m.complete < 0 {+ m.complete += len(completions)+ }+ return true+}++func (m *chatModel) applyCompletion() bool {+ completions := m.completions()+ if len(completions) == 0 || !completionIsSelectable(completions) {+ return false+ }+ m.resetPromptHistoryCursor()+ selected := completions[clamp(m.complete, 0, len(completions)-1)]+ input := string(m.input)+ if strings.HasPrefix(strings.TrimSpace(input), "/") {+ m.input = []rune(selected.value)+ m.inputCursor = len(m.input)+ m.inputCursorSet = true+ m.complete = 0+ return true+ }++ start, _, ok := activeMentionToken(input)+ if !ok {+ return false+ }+ suffix := ""+ if !selected.directory {+ suffix = " "+ }+ next := string([]rune(input)[:start]) + "@" + selected.value + suffix+ m.input = []rune(next)+ m.inputCursor = len(m.input)+ m.inputCursorSet = true+ m.complete = 0+ return true+}++func completionIsSelectable(completions []chatCompletion) bool {+ return len(completions) > 0 && completions[0].value != ""+}++func (m chatModel) helpSummary() string {+ lines := []string{+ "**Commands**",+ "",+ }+ for _, command := range chatSlashCommands {+ if command.hidden || strings.TrimSpace(command.description) == "" {+ continue+ }+ usage := command.name+ if command.usage != "" {+ usage = command.usage+ }+ lines = append(lines, fmt.Sprintf("- `%s`: %s", usage, command.description))+ }+ lines = append(lines,+ "",+ "**Shortcuts**",+ "",+ "- `shift+enter`: insert a newline",+ "- `shift+tab`: toggle permission mode",+ "- `↑/↓`: previous or next prompt",+ "- `ctrl+a/e`: move to line start or end",+ )+ return strings.Join(lines, "\n")+}++func (m chatModel) systemPrompt(extra string) string {+ var parts []string+ if strings.TrimSpace(m.opts.SystemPrompt) != "" {+ parts = append(parts, strings.TrimSpace(m.opts.SystemPrompt))+ }+ if strings.TrimSpace(extra) != "" {+ parts = append(parts, strings.TrimSpace(extra))+ }+ return strings.Join(parts, "\n\n")+}diff --git a/cmd/tui/chat/input_test.go b/cmd/tui/chat/input_test.gonew file mode 100644index 000000000..af8192878--- /dev/null+++ b/cmd/tui/chat/input_test.go@@ -0,0 +1,762 @@+package chat++import (+ "context"+ "os"+ "path/filepath"+ "strings"+ "testing"++ tea "github.com/charmbracelet/bubbletea"+ "github.com/charmbracelet/lipgloss"++ coreagent "github.com/ollama/ollama/agent"+ "github.com/ollama/ollama/api"+)++func TestChatHelpCommandShowsV1Commands(t *testing.T) {+ m := chatModel{input: []rune("/help")}++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("help command should not return a command")+ }++ fm := updated.(chatModel)+ if len(fm.entries) != 1 {+ t.Fatalf("entries = %d, want 1", len(fm.entries))+ }+ for _, want := range []string{+ "**Commands**",+ "- `/model`: switch models",+ "- `/think`: set thinking mode",+ "- `/compact`: summarize older context",+ "- `/help`: show commands",+ "- `/bye`: exit",+ "- `/prompt`: show full prompt, tools, and messages",+ "- `/save <filename>`: save request JSON; saved as <filename>.json",+ "**Shortcuts**",+ "- `shift+enter`: insert a newline",+ "- `shift+tab`: toggle permission mode",+ } {+ if !strings.Contains(fm.entries[0].content, want) {+ t.Fatalf("help output missing %q:\n%s", want, fm.entries[0].content)+ }+ }+ for _, removed := range []string{"/history", "/load", "/raw", "/resume", "/set", "/show", "/skills", "/verbose"} {+ if strings.Contains(fm.entries[0].content, removed) {+ t.Fatalf("removed command %q should stay hidden from help:\n%s", removed, fm.entries[0].content)+ }+ }+}++func TestChatNewCommandRepaintsFromTop(t *testing.T) {+ m := chatModel{+ input: []rune("/new"),+ flowPrintedLines: 4,+ entries: []chatEntry{{role: "assistant", content: "old transcript"}},+ messages: []api.Message{{Role: "user", Content: "old prompt"}},+ approvalState: testApprovalState(true, map[string]bool{"edit": true}),+ opts: Options{AllowAllTools: true},+ permissionNotice: "full access enabled",+ }++ updated, cmd := m.handleSubmit()+ if cmd == nil {+ t.Fatal("/new should return a repaint command")+ }+ m = updated.(chatModel)+ if m.status != "new chat" {+ t.Fatalf("status = %q, want new chat", m.status)+ }+ if len(m.entries) != 0 || len(m.messages) != 0 {+ t.Fatalf("chat was not reset: entries=%#v messages=%#v", m.entries, m.messages)+ }+ if m.flowPrintedLines != 0 {+ t.Fatalf("flowPrintedLines = %d, want 0", m.flowPrintedLines)+ }+ if m.approvalState.AllowAll() || m.opts.AllowAllTools || m.approvalState.Allows("edit") || m.permissionNotice != "" {+ t.Fatalf("permissions were not reset: allowAll=%v opts=%v editAllowed=%v notice=%q", m.approvalState.AllowAll(), m.opts.AllowAllTools, m.approvalState.Allows("edit"), m.permissionNotice)+ }+ if msg := cmd(); msg == nil {+ t.Fatal("repaint command returned nil")+ }+}++func TestChatNewCommandPreservesLaunchFullAccessDefault(t *testing.T) {+ m := chatModel{+ input: []rune("/new"),+ defaultAllowAll: true,+ approvalState: testApprovalState(false, map[string]bool{"edit": true}),+ }++ updated, _ := m.handleSubmit()+ fm := updated.(chatModel)+ if !fm.approvalState.AllowAll() || !fm.opts.AllowAllTools {+ t.Fatalf("full access default was not restored: allowAll=%v opts=%v", fm.approvalState.AllowAll(), fm.opts.AllowAllTools)+ }+ fm.approvalState.SetAllowAll(false)+ if fm.approvalState.Allows("edit") {+ t.Fatal("edit scope should be cleared")+ }+}++func TestChatSaveCommandRequiresFilename(t *testing.T) {+ m := chatModel{+ input: []rune("/save"),+ opts: Options{Model: "llama3.2"},+ }++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("/save should not start a command")+ }+ fm := updated.(chatModel)+ if fm.status != "error" {+ t.Fatalf("status = %q, want error", fm.status)+ }+ if len(fm.entries) != 1 || !strings.Contains(fm.entries[0].content, "usage: /save <filename>") {+ t.Fatalf("entries = %#v, want usage error", fm.entries)+ }+}++func TestChatSaveCommandWritesRequestJSON(t *testing.T) {+ dir := t.TempDir()+ m := chatModel{+ input: []rune("/save request"),+ workingDir: dir,+ opts: Options{+ Model: "llama3.2",+ SystemPrompt: "You are Ollama.",+ },+ messages: []api.Message{{Role: "user", Content: "hello"}},+ }++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("/save redirect should not start a command")+ }+ fm := updated.(chatModel)+ if fm.status != "saved" {+ t.Fatalf("status = %q, want saved", fm.status)+ }++ data, err := os.ReadFile(filepath.Join(dir, "request.json"))+ if err != nil {+ t.Fatal(err)+ }+ raw := string(data)+ for _, want := range []string{+ `"model": "llama3.2"`,+ `"role": "system"`,+ `"content": "You are Ollama."`,+ `"role": "user"`,+ `"content": "hello"`,+ } {+ if !strings.Contains(raw, want) {+ t.Fatalf("saved request missing %q:\n%s", want, raw)+ }+ }+ if got := fm.entries[len(fm.entries)-1].content; got != "saved as request.json" {+ t.Fatalf("save entry = %q, want saved filename", got)+ }+}++func TestChatSaveCommandRejectsPath(t *testing.T) {+ dir := t.TempDir()+ m := chatModel{+ input: []rune("/save ../request"),+ workingDir: dir,+ opts: Options{Model: "llama3.2"},+ }++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("invalid /save should not start a command")+ }+ fm := updated.(chatModel)+ if fm.status != "error" {+ t.Fatalf("status = %q, want error", fm.status)+ }+ if _, err := os.Stat(filepath.Join(filepath.Dir(dir), "request.json")); !os.IsNotExist(err) {+ t.Fatalf("/save wrote outside working dir, stat err = %v", err)+ }+}++func TestChatPromptCommandOpensPromptDebugScreen(t *testing.T) {+ registry := &coreagent.Registry{}+ registry.Register(chatTestTool{})+ toolArgs := api.NewToolCallFunctionArguments()+ toolArgs.Set("query", "show me everything")+ m := chatModel{+ input: []rune("/prompt"),+ width: 100,+ height: 20,+ opts: Options{+ Model: "llama3.2",+ SystemPrompt: "You are Ollama.",+ Tools: registry,+ ContextWindowTokens: 1024,+ },+ messages: []api.Message{+ {Role: "user", Content: "hello\nsecond line"},+ {+ Role: "assistant",+ Content: "I'll call a tool.",+ Thinking: "I should call the fake tool first.",+ ToolCalls: []api.ToolCall{{+ ID: "call-1",+ Function: api.ToolCallFunction{+ Name: "fake_tool",+ Arguments: toolArgs,+ },+ }},+ },+ {Role: "tool", ToolName: "fake_tool", ToolCallID: "call-1", Content: "tool result line 1\ntool result line 2"},+ },+ }++ updated, cmd := m.handleSubmit()+ if cmd == nil {+ t.Fatal("/prompt should enable managed prompt screen")+ }+ fm := updated.(chatModel)+ if fm.promptDebug == nil {+ t.Fatal("/prompt should open prompt debug screen")+ }+ if len(fm.entries) != 0 {+ t.Fatalf("/prompt should not append a transcript entry: %#v", fm.entries)+ }+ out := stripANSI(fm.View())+ body := stripANSI(strings.Join(fm.promptDebugLines(160), "\n"))+ for _, want := range []string{+ "Prompt",+ "full request preview",+ } {+ if !strings.Contains(out, want) {+ t.Fatalf("/prompt view missing %q:\n%s", want, out)+ }+ }+ for _, want := range []string{+ "model: llama3.2",+ "estimated prompt:",+ "/ 1024 tokens",+ "messages: 4",+ "tools: 1",+ "Tools",+ "1. fake_tool",+ "description:",+ "does test work",+ "parameters: object",+ "1. system",+ "You are Ollama.",+ "2. user",+ "hello",+ "second line",+ "3. assistant",+ "thinking:",+ "I should call the fake tool first.",+ "content:",+ "I'll call a tool.",+ "tool call 1: fake_tool",+ "id: call-1",+ "arguments:",+ "query: show me everything",+ "4. tool:fake_tool",+ "tool_name: fake_tool",+ "tool_call_id: call-1",+ "tool result",+ "tool result line 1",+ "tool result line 2",+ } {+ if !strings.Contains(body, want) {+ t.Fatalf("/prompt output missing %q:\n%s", want, body)+ }+ }+ assistantStart := strings.Index(body, "3. assistant")+ if assistantStart < 0 {+ t.Fatalf("/prompt output missing assistant message:\n%s", body)+ }+ assistantBody := body[assistantStart:]+ thinkingIndex := strings.Index(assistantBody, "thinking:")+ contentIndex := strings.Index(assistantBody, "content:")+ if thinkingIndex < 0 || contentIndex < 0 {+ t.Fatalf("/prompt assistant output missing thinking/content labels:\n%s", body)+ }+ if thinkingIndex > contentIndex {+ t.Fatalf("/prompt assistant thinking should render before content:\n%s", body)+ }+ for _, unwanted := range []string{`"query":`, `"name": "fake_tool"`} {+ if strings.Contains(body, unwanted) {+ t.Fatalf("/prompt output should be rendered, not raw JSON; found %q:\n%s", unwanted, body)+ }+ }+ messagesIndex := strings.Index(body, "Messages")+ toolsIndex := strings.Index(body, "Tools")+ if messagesIndex < 0 || toolsIndex < 0 || toolsIndex < messagesIndex {+ t.Fatalf("/prompt should render tools after messages:\n%s", body)+ }++ updated, cmd = fm.Update(tea.KeyMsg{Type: tea.KeyEsc})+ if cmd == nil {+ t.Fatal("closing prompt debug should disable prompt mouse mode")+ }+ fm = updated.(chatModel)+ if fm.promptDebug != nil {+ t.Fatal("esc should close prompt debug screen")+ }+}++func TestChatPromptDebugCapsToolResultPreview(t *testing.T) {+ longResult := strings.Repeat("x", maxPromptDebugToolResultRunes+25) + "tail-marker"+ m := chatModel{+ width: 120,+ height: 20,+ promptDebug: &chatPromptDebug{+ request: api.ChatRequest{+ Model: "llama3.2",+ Messages: []api.Message{{+ Role: "tool",+ ToolName: "bash",+ ToolCallID: "call-1",+ Content: longResult,+ }},+ },+ },+ }++ body := stripANSI(strings.Join(m.promptDebugLines(120), "\n"))+ if strings.Contains(body, "tail-marker") {+ t.Fatalf("/prompt should cap rendered tool results:\n%s", body)+ }+ if !strings.Contains(body, "...") {+ t.Fatalf("/prompt capped tool result should show ellipsis:\n%s", body)+ }+ if got := strings.Count(body, "x"); got != maxPromptDebugToolResultRunes-3 {+ t.Fatalf("rendered tool result x count = %d, want %d:\n%s", got, maxPromptDebugToolResultRunes-3, body)+ }+ if got := m.promptDebug.request.Messages[0].Content; got != longResult {+ t.Fatal("/prompt rendering should not mutate the request")+ }+}++func TestChatPromptDebugMouseWheelScrolls(t *testing.T) {+ m := chatModel{+ width: 80,+ height: 8,+ opts: Options{Model: "llama3.2", ContextWindowTokens: 1024},+ promptDebug: &chatPromptDebug{+ request: api.ChatRequest{Model: "llama3.2"},+ tokens: 10,+ },+ }+ for range 30 {+ m.promptDebug.request.Messages = append(m.promptDebug.request.Messages, api.Message{Role: "user", Content: "line"})+ }+ if m.promptDebugMaxScroll() == 0 {+ t.Fatal("test setup should produce a scrollable prompt debug screen")+ }++ updated, _ := m.Update(tea.MouseMsg{Type: tea.MouseWheelDown})+ m = updated.(chatModel)+ if m.promptDebug.scroll == 0 {+ t.Fatal("mouse wheel down should scroll prompt debug screen")+ }++ updated, _ = m.Update(tea.MouseMsg{Type: tea.MouseWheelUp})+ m = updated.(chatModel)+ if m.promptDebug.scroll != 0 {+ t.Fatalf("mouse wheel up should return prompt debug screen to top, got scroll %d", m.promptDebug.scroll)+ }+}++func TestTruncateInputLineUsesDisplayWidth(t *testing.T) {+ line := truncateInputLine(strings.Repeat("界", 10), 10)+ if got := lipgloss.Width(line); got > 10 {+ t.Fatalf("line %q width = %d, want <= 10", line, got)+ }+}++func TestRenderInputBoxTruncationUsesSingleContinuationMarker(t *testing.T) {+ lines := renderInputBoxLines("one two three four five six seven", len("one two three four five six seven"), 16, 1, "")+ rendered := strings.Join(lines, "\n")+ if strings.Contains(rendered, "... ...") {+ t.Fatalf("input rendered duplicate continuation marker: %q", rendered)+ }+ if strings.Contains(rendered, "one two") {+ t.Fatalf("input should keep the latest truncated line: %q", rendered)+ }+}++type shiftEnterCSITestMsg string++func (m shiftEnterCSITestMsg) String() string {+ return string(m)+}++func TestChatInputHandlesShiftEnterCSIMessage(t *testing.T) {+ m := chatModel{input: []rune("line one")}++ updated, _ := m.Update(shiftEnterCSITestMsg("?CSI[49 51 59 50 117]?"))+ m = updated.(chatModel)+ if got := string(m.input); got != "line one\n" {+ t.Fatalf("input = %q, want newline inserted", got)+ }+}++func TestChatInputAcceptsSpace(t *testing.T) {+ m := chatModel{}++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("hello")})+ m = updated.(chatModel)+ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeySpace, Runes: []rune(" ")})+ m = updated.(chatModel)+ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("world")})+ m = updated.(chatModel)++ if got := string(m.input); got != "hello world" {+ t.Fatalf("input = %q, want hello world", got)+ }+}++func TestChatLargePasteUsesPlaceholderAndExpandsOnSubmit(t *testing.T) {+ pasted := strings.Repeat("line\n", pastedTextPlaceholderMinLines-1) + "line"+ m := chatModel{+ ctx: context.Background(),+ opts: Options{+ Model: "test",+ Client: chatTestClient{},+ },+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(pasted), Paste: true})+ m = updated.(chatModel)+ if got, want := string(m.input), "[Pasted text #1 +8 lines]"; got != want {+ t.Fatalf("input = %q, want %q", got, want)+ }++ updated, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})+ m = updated.(chatModel)+ if cmd == nil {+ t.Fatal("enter should start a run")+ }+ done := waitForRunDone(t, m.events)+ if done.err != nil {+ t.Fatal(done.err)+ }+ if done.result == nil || len(done.result.Messages) < 1 || done.result.Messages[0].Content != pasted {+ t.Fatalf("messages = %#v, want expanded pasted text", done.result)+ }+}++func TestChatBackspaceDeletesWholePastedTextPlaceholder(t *testing.T) {+ m := chatModel{+ input: []rune("use [Pasted text #1 +8 lines]"),+ inputPastedTexts: []chatInputPastedText{{+ placeholder: "[Pasted text #1 +8 lines]",+ content: "hidden",+ }},+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyBackspace})+ m = updated.(chatModel)+ if got := string(m.input); got != "use " {+ t.Fatalf("input after backspace = %q, want pasted text placeholder removed", got)+ }+ if got := len(m.inputPastedTexts); got != 0 {+ t.Fatalf("pasted texts after backspace = %d, want 0", got)+ }+}++func TestInitialPromptHistoryLoadsFromMessages(t *testing.T) {+ history := initialPromptHistory(context.Background(), Options{+ Messages: []api.Message{+ {Role: "user", Content: "old prompt"},+ {Role: "assistant", Content: "answer"},+ {Role: "user", Content: "new prompt"},+ },+ })++ if got, want := strings.Join(history, "|"), "old prompt|new prompt"; got != want {+ t.Fatalf("history = %#v, want %s", history, want)+ }+}++func TestChatDeletedSlashCommandsAreUnknown(t *testing.T) {+ for _, command := range []string{"/copy", "/copy-all", "/launch", "/system", "/history", "/load", "/raw", "/resume", "/set", "/show", "/skills", "/verbose"} {+ t.Run(command, func(t *testing.T) {+ m := chatModel{input: []rune(command)}++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("deleted slash command should not return a command")+ }+ m = updated.(chatModel)+ if len(m.entries) != 1 || m.entries[0].role != "error" || !strings.Contains(m.entries[0].content, "Unknown command") {+ t.Fatalf("entries = %#v, want unknown command error", m.entries)+ }+ })+ }+}++func TestChatViewRendersSlashCommandSuggestions(t *testing.T) {+ m := chatModel{+ input: []rune("/"),+ width: 80,+ height: 18,+ }++ view := stripANSI(m.View())+ for _, want := range []string{"/clear", "/model", "/new", "/think", "/tools"} {+ if !strings.Contains(view, want) {+ t.Fatalf("view missing %s suggestion: %q", want, view)+ }+ }+ for _, removed := range []string{"/copy", "/copy-all", "/history", "/load", "/raw", "/resume", "/set", "/show", "/skills", "/verbose"} {+ if strings.Contains(view, removed) {+ t.Fatalf("bare slash should hide removed command %s: %q", removed, view)+ }+ }+ if got := len(m.slashCommandLines(80)); got != maxSlashCompletions {+ t.Fatalf("slash suggestions = %d, want %d", got, maxSlashCompletions)+ }+}++func TestChatToolsCommandTogglesToolRegistry(t *testing.T) {+ registry := &coreagent.Registry{}+ registry.Register(chatTestTool{})+ calls := 0+ m := chatModel{+ ctx: context.Background(),+ input: []rune("/tools"),+ opts: Options{+ Model: "llama3.2",+ Tools: registry,+ ToolRegistryForModel: func(context.Context, string) *coreagent.Registry {+ calls+++ return registry+ },+ },+ }++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("/tools should not start a command")+ }+ m = updated.(chatModel)+ if !m.opts.ToolsDisabled || m.opts.Tools == nil {+ t.Fatalf("tools off state = disabled:%v tools:%#v", m.opts.ToolsDisabled, m.opts.Tools)+ }+ if len(m.entries) != 0 {+ t.Fatalf("/tools should only update action space, got entries:%#v", m.entries)+ }+ req, _ := m.requestPreview()+ if got := len(req.Tools); got != 0 {+ t.Fatalf("request preview tools = %d, want 0", got)+ }++ m.input = []rune("/tools")+ updated, cmd = m.handleSubmit()+ if cmd != nil {+ t.Fatal("/tools should not start a command")+ }+ m = updated.(chatModel)+ if m.opts.ToolsDisabled || m.opts.Tools == nil {+ t.Fatalf("tools on state = disabled:%v tools:%#v", m.opts.ToolsDisabled, m.opts.Tools)+ }+ if calls != 1 {+ t.Fatalf("tool registry calls = %d, want 1", calls)+ }+ if len(m.entries) != 0 {+ t.Fatalf("/tools should only update action space, got entries:%#v", m.entries)+ }+ req, _ = m.requestPreview()+ if got := len(req.Tools); got != 1 {+ t.Fatalf("request preview tools = %d, want 1", got)+ }+}++func TestChatToolsCommandUsage(t *testing.T) {+ m := chatModel{input: []rune("/tools off")}++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("invalid /tools should not start a command")+ }+ m = updated.(chatModel)+ if m.status != "error" || len(m.entries) != 1 || !strings.Contains(m.entries[0].content, "usage: /tools") {+ t.Fatalf("invalid /tools result = status:%q entries:%#v", m.status, m.entries)+ }+}++func TestChatSlashCommandSuggestionsIncludePromptAndSave(t *testing.T) {+ for _, tt := range []struct {+ input string+ command string+ description string+ }{+ {input: "/pr", command: "/prompt", description: "show full prompt, tools, and messages"},+ {input: "/sa", command: "/save", description: "save request JSON; saved as <filename>.json"},+ } {+ t.Run(tt.command, func(t *testing.T) {+ m := chatModel{input: []rune(tt.input)}++ lines := stripANSI(strings.Join(m.slashCommandLines(80), "\n"))+ if !strings.Contains(lines, tt.command) || !strings.Contains(lines, tt.description) {+ t.Fatalf("suggestions missing %s: %q", tt.command, lines)+ }+ })+ }+}++func TestChatSlashCommandSuggestionsIncludeThink(t *testing.T) {+ m := chatModel{input: []rune("/th")}++ lines := stripANSI(strings.Join(m.slashCommandLines(80), "\n"))+ if !strings.Contains(lines, "/think") || !strings.Contains(lines, "set thinking mode") {+ t.Fatalf("suggestions missing /think: %q", lines)+ }+}++func TestChatEnterAcceptsSelectedSlashCommand(t *testing.T) {+ m := chatModel{input: []rune("/th")}++ updated, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})+ m = updated.(chatModel)+ if cmd != nil {+ t.Fatal("think command should not return a command")+ }+ if m.thinkPicker == nil {+ t.Fatal("selected /think command should open picker")+ }+}++func TestChatSlashCommandsRunWhileModelResponds(t *testing.T) {+ m := chatModel{running: true, input: []rune("/help")}++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("help command should not return a command")+ }+ m = updated.(chatModel)+ if len(m.entries) != 1 || m.entries[0].role != "slash" {+ t.Fatalf("entries = %#v, want immediate slash output", m.entries)+ }+}++func TestChatMessageSubmitWhileRunningPreservesDraft(t *testing.T) {+ attachment := chatInputAttachment{placeholder: "[image 1]", kind: "image"}+ pasted := chatInputPastedText{placeholder: "[pasted 1]", content: "long paste"}+ m := chatModel{+ running: true,+ input: []rune("next prompt [image 1] [pasted 1]"),+ inputCursor: 4,+ inputCursorSet: true,+ inputAttachments: []chatInputAttachment{attachment},+ inputPastedTexts: []chatInputPastedText{pasted},+ }++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("busy submit should not start a command")+ }+ m = updated.(chatModel)+ if got := string(m.input); got != "next prompt [image 1] [pasted 1]" {+ t.Fatalf("input = %q, want draft preserved", got)+ }+ if m.inputCursor != 4 || !m.inputCursorSet {+ t.Fatalf("cursor not preserved: cursor=%d set=%v", m.inputCursor, m.inputCursorSet)+ }+ if len(m.inputAttachments) != 1 || m.inputAttachments[0].placeholder != attachment.placeholder || m.inputAttachments[0].kind != attachment.kind {+ t.Fatalf("attachments not preserved: %#v", m.inputAttachments)+ }+ if len(m.inputPastedTexts) != 1 || m.inputPastedTexts[0] != pasted {+ t.Fatalf("pasted text not preserved: %#v", m.inputPastedTexts)+ }+ if len(m.entries) != 0 {+ t.Fatalf("busy submit should not add entries: %#v", m.entries)+ }+}++func TestChatThinkCommandOpensPicker(t *testing.T) {+ m := chatModel{input: []rune("/think")}++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("think command should not return a command")+ }+ m = updated.(chatModel)+ if m.thinkPicker == nil {+ t.Fatal("think picker should open")+ }+ if view := stripANSI(m.renderThinkPicker(80)); !strings.Contains(view, "Thinking mode") || !strings.Contains(view, "high") {+ t.Fatalf("think picker view missing options: %q", view)+ }+}++func TestChatThinkCommandSetsModes(t *testing.T) {+ for _, tt := range []struct {+ input string+ want any+ }{+ {input: "/think on", want: true},+ {input: "/think off", want: false},+ {input: "/think high", want: "high"},+ } {+ t.Run(tt.input, func(t *testing.T) {+ m := chatModel{input: []rune(tt.input)}+ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("think command should not return a command")+ }+ m = updated.(chatModel)+ if m.opts.Think == nil || m.opts.Think.Value != tt.want {+ t.Fatalf("think = %#v, want %#v", m.opts.Think, tt.want)+ }+ })+ }+}++func TestChatViewRendersFileMentionSuggestions(t *testing.T) {+ dir := t.TempDir()+ if err := os.Mkdir(filepath.Join(dir, "cmd"), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("hi"), 0o644); err != nil {+ t.Fatal(err)+ }+ m := chatModel{+ workingDir: dir,+ input: []rune("open @"),+ width: 80,+ height: 18,+ }++ view := stripANSI(m.View())+ if !strings.Contains(view, "@cmd/") || !strings.Contains(view, "@README.md") {+ t.Fatalf("file mention suggestions missing: %q", view)+ }+}++func TestChatFileMentionSuggestionsFilterAndComplete(t *testing.T) {+ dir := t.TempDir()+ if err := os.Mkdir(filepath.Join(dir, "cmd"), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("hi"), 0o644); err != nil {+ t.Fatal(err)+ }+ m := chatModel{+ workingDir: dir,+ input: []rune("open @REA"),+ }++ lines := stripANSI(strings.Join(m.completionLines(80), "\n"))+ if !strings.Contains(lines, "@README.md") || strings.Contains(lines, "@cmd/") {+ t.Fatalf("filtered file suggestions = %q", lines)+ }+ m.applyCompletion()+ if got := string(m.input); got != "open @README.md " {+ t.Fatalf("completed input = %q", got)+ }+}diff --git a/cmd/tui/chat/markdown.go b/cmd/tui/chat/markdown.gonew file mode 100644index 000000000..9d617f590--- /dev/null+++ b/cmd/tui/chat/markdown.go@@ -0,0 +1,294 @@+package chat++import (+ "strings"++ "github.com/charmbracelet/lipgloss"+)++func renderMarkdownForView(markdown string, width int) string {+ if width < 20 {+ width = 20+ }++ source := strings.Split(strings.TrimRight(markdown, "\n"), "\n")+ var rendered []string+ inCodeBlock := false+ for i := 0; i < len(source); i++ {+ line := strings.TrimRight(source[i], "\r")+ trimmed := strings.TrimSpace(line)++ if strings.HasPrefix(trimmed, "```") {+ inCodeBlock = !inCodeBlock+ continue+ }+ if inCodeBlock {+ rendered = append(rendered, renderMarkdownCodeLine(line, width)...)+ continue+ }++ if table, consumed := renderMarkdownTable(source[i:], width); consumed > 0 {+ rendered = append(rendered, table...)+ i += consumed - 1+ continue+ }++ if heading, ok := markdownHeading(trimmed); ok {+ rendered = append(rendered, chatHeaderStyle.Render(heading))+ continue+ }++ if trimmed == "" {+ rendered = append(rendered, "")+ continue+ }+ for _, wrapped := range wrapChatText(line, width) {+ rendered = append(rendered, renderMarkdownInline(wrapped))+ }+ }+ return strings.Join(rendered, "\n")+}++func splitRenderedBody(body string) []string {+ body = strings.TrimRight(body, "\n")+ if body == "" {+ return []string{""}+ }+ return strings.Split(body, "\n")+}++func markdownHeading(line string) (string, bool) {+ if !strings.HasPrefix(line, "#") {+ return "", false+ }+ level := 0+ for level < len(line) && line[level] == '#' {+ level+++ }+ if level == 0 || level > 6 || level >= len(line) || line[level] != ' ' {+ return "", false+ }+ return strings.TrimSpace(line[level:]), true+}++func renderMarkdownInline(line string) string {+ var b strings.Builder+ for {+ before, rest, ok := strings.Cut(line, "`")+ b.WriteString(before)+ if !ok {+ break+ }+ code, after, ok := strings.Cut(rest, "`")+ if !ok {+ b.WriteString("`")+ b.WriteString(rest)+ break+ }+ b.WriteString(chatInlineCodeStyle.Render(code))+ line = after+ }+ return b.String()+}++func renderMarkdownCodeLine(line string, width int) []string {+ codeWidth := max(1, width-2)+ lines := wrapChatText(line, codeWidth)+ for i, wrapped := range lines {+ lines[i] = " " + chatCodeBlockStyle.Render(wrapped)+ }+ return lines+}++func renderMarkdownTable(lines []string, width int) ([]string, int) {+ if len(lines) < 2 || !looksLikeMarkdownTableRow(lines[0]) || !isMarkdownTableSeparator(lines[1]) {+ return nil, 0+ }++ var rows [][]string+ consumed := 0+ for consumed < len(lines) && looksLikeMarkdownTableRow(lines[consumed]) {+ if consumed == 1 && isMarkdownTableSeparator(lines[consumed]) {+ consumed+++ continue+ }+ rows = append(rows, parseMarkdownTableRow(lines[consumed]))+ consumed+++ }+ if len(rows) == 0 {+ return nil, 0+ }++ columnCount := 0+ for _, row := range rows {+ columnCount = max(columnCount, len(row))+ }+ naturalWidths := make([]int, columnCount)+ for _, row := range rows {+ for i := range columnCount {+ cell := ""+ if i < len(row) {+ cell = row[i]+ }+ naturalWidths[i] = max(naturalWidths[i], lipglossWidth(cell))+ }+ }+ widths := markdownTableColumnWidths(naturalWidths, width)++ var rendered []string+ for rowIndex, row := range rows {+ wrappedCells := make([][]string, columnCount)+ rowHeight := 1+ for i := range columnCount {+ cell := ""+ if i < len(row) {+ cell = row[i]+ }+ wrappedCells[i] = wrapMarkdownTableCell(cell, widths[i])+ rowHeight = max(rowHeight, len(wrappedCells[i]))+ }+ for lineIndex := range rowHeight {+ cells := make([]string, columnCount)+ for i := range columnCount {+ cellLine := ""+ if lineIndex < len(wrappedCells[i]) {+ cellLine = wrappedCells[i][lineIndex]+ }+ cells[i] = padPlainLine(cellLine, widths[i])+ }+ line := strings.Join(cells, chatTableBorderStyle.Render(" | "))+ if rowIndex == 0 {+ line = chatHeaderStyle.Render(stripANSIForWidth(line))+ }+ rendered = append(rendered, line)+ }+ }+ return rendered, consumed+}++func markdownTableColumnWidths(naturalWidths []int, width int) []int {+ if len(naturalWidths) == 0 {+ return nil+ }+ separatorWidth := max(0, len(naturalWidths)-1) * lipglossWidth(" | ")+ available := max(1, width-separatorWidth)+ widths := make([]int, len(naturalWidths))+ minWidths := make([]int, len(naturalWidths))+ for i, natural := range naturalWidths {+ widths[i] = max(1, natural)+ minWidth := min(widths[i], 12)+ if i == 0 {+ minWidth = min(widths[i], 4)+ }+ minWidths[i] = max(1, minWidth)+ }++ for sumInts(widths) > available {+ index := widestShrinkableColumn(widths, minWidths)+ if index < 0 {+ break+ }+ widths[index]--+ }+ for sumInts(widths) > available {+ index := widestColumn(widths)+ if index < 0 || widths[index] <= 1 {+ break+ }+ widths[index]--+ }+ return widths+}++func widestShrinkableColumn(widths, minWidths []int) int {+ index := -1+ for i, width := range widths {+ if width <= minWidths[i] {+ continue+ }+ if index < 0 || width > widths[index] {+ index = i+ }+ }+ return index+}++func widestColumn(widths []int) int {+ index := -1+ for i, width := range widths {+ if index < 0 || width > widths[index] {+ index = i+ }+ }+ return index+}++func sumInts(values []int) int {+ sum := 0+ for _, value := range values {+ sum += value+ }+ return sum+}++func wrapMarkdownTableCell(cell string, width int) []string {+ width = max(1, width)+ var out []string+ line := strings.TrimSpace(cell)+ for lipglossWidth(line) > width {+ cut := chatDisplayWidthCut(line, width)+ out = append(out, strings.TrimSpace(line[:cut]))+ line = strings.TrimSpace(line[cut:])+ }+ out = append(out, line)+ if len(out) == 0 {+ return []string{""}+ }+ return out+}++func looksLikeMarkdownTableRow(line string) bool {+ line = strings.TrimSpace(line)+ return strings.Contains(line, "|") && strings.Count(line, "|") >= 1+}++func isMarkdownTableSeparator(line string) bool {+ cells := parseMarkdownTableRow(line)+ if len(cells) == 0 {+ return false+ }+ for _, cell := range cells {+ cell = strings.Trim(cell, " :-")+ if cell != "" {+ return false+ }+ }+ return true+}++func parseMarkdownTableRow(line string) []string {+ line = strings.TrimSpace(line)+ line = strings.TrimPrefix(line, "|")+ line = strings.TrimSuffix(line, "|")+ raw := strings.Split(line, "|")+ cells := make([]string, 0, len(raw))+ for _, cell := range raw {+ cells = append(cells, strings.TrimSpace(cell))+ }+ return cells+}++func padPlainLine(line string, width int) string {+ if extra := width - lipglossWidth(line); extra > 0 {+ return line + strings.Repeat(" ", extra)+ }+ return line+}++func stripANSIForWidth(line string) string {+ return stripChatANSI(line)+}++func lipglossWidth(line string) int {+ return lipgloss.Width(line)+}diff --git a/cmd/tui/chat/modals.go b/cmd/tui/chat/modals.gonew file mode 100644index 000000000..2ca0f923a--- /dev/null+++ b/cmd/tui/chat/modals.go@@ -0,0 +1,263 @@+package chat++import (+ "context"+ "fmt"+ "slices"+ "strings"++ tea "github.com/charmbracelet/bubbletea"++ apptui "github.com/ollama/ollama/cmd/tui"+)++type chatModelPicker = apptui.SelectorModel++func (m *chatModel) openModelPicker(filter string) (tea.Model, tea.Cmd) {+ if m.opts.ModelOptions == nil {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "error", content: "Model picker is unavailable.", err: "Model picker is unavailable."}))+ m.status = "error"+ return *m, nil+ }++ ctx := m.ctx+ if ctx == nil {+ ctx = context.Background()+ }+ models, err := m.opts.ModelOptions(ctx)+ if err != nil {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "error", content: fmt.Sprintf("Could not list models: %v", err), err: err.Error()}))+ m.status = "error"+ return *m, nil+ }+ models = normalizeModelOptions(models)+ if len(models) == 0 {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "system", content: "No models available."}))+ m.status = "ready"+ return *m, nil+ }++ items := modelSelectorItems(models, m.opts.Model)+ current := m.opts.Model+ if !m.openModelOnInit {+ items = compactModelSelectorItems(models, m.opts.Model)+ current = ""+ }+ picker := apptui.NewModelSelectorModel("Select model", items, current, filter)+ picker.SetHelpText("↑/↓ navigate • enter select • type search • esc cancel")+ m.modelPicker = &picker+ m.modelPickerModels = models+ m.status = "model"+ return *m, nil+}++func normalizeModelOptions(models []ModelOption) []ModelOption {+ seen := make(map[string]struct{}, len(models))+ out := make([]ModelOption, 0, len(models))+ for _, model := range models {+ model.Name = strings.TrimSpace(model.Name)+ model.Description = strings.TrimSpace(model.Description)+ if model.Name == "" {+ continue+ }+ key := strings.ToLower(model.Name)+ if _, ok := seen[key]; ok {+ continue+ }+ seen[key] = struct{}{}+ out = append(out, model)+ }+ slices.SortStableFunc(out, func(a, b ModelOption) int {+ if a.Recommended == b.Recommended {+ return 0+ }+ if a.Recommended {+ return -1+ }+ return 1+ })+ return out+}++func modelSelectorItems(models []ModelOption, current string) []apptui.SelectItem {+ return modelSelectorItemsWithCurrentPriority(models, current, true)+}++func compactModelSelectorItems(models []ModelOption, current string) []apptui.SelectItem {+ return modelSelectorItemsWithCurrentPriority(models, current, false)+}++func modelSelectorItemsWithCurrentPriority(models []ModelOption, current string, pinCurrent bool) []apptui.SelectItem {+ ordered := slices.Clone(models)+ slices.SortStableFunc(ordered, func(a, b ModelOption) int {+ if cmp := compareModelPickerGroup(modelPickerGroup(a, current, pinCurrent), modelPickerGroup(b, current, pinCurrent)); cmp != 0 {+ return cmp+ }+ return 0+ })++ items := make([]apptui.SelectItem, 0, len(ordered))+ for _, model := range ordered {+ items = append(items, apptui.SelectItem{+ Name: model.Name,+ Description: modelOptionMeta(model),+ Recommended: model.Name == current || !model.Cloud || model.Recommended,+ AvailabilityBadge: model.AvailabilityBadge,+ })+ }+ return items+}++func modelPickerGroup(model ModelOption, current string, pinCurrent bool) int {+ if pinCurrent && model.Name == current {+ return 0+ }+ if model.Recommended {+ return 1+ }+ if model.Name == current {+ return 2+ }+ if !model.Cloud {+ return 3+ }+ return 4+}++func compareModelPickerGroup(a, b int) int {+ switch {+ case a < b:+ return -1+ case a > b:+ return 1+ default:+ return 0+ }+}++func (m chatModel) updateModelPicker(msg tea.KeyMsg) (tea.Model, tea.Cmd) {+ if m.modelPicker == nil {+ return m, nil+ }+ switch msg.Type {+ case tea.KeyCtrlC, tea.KeyEsc:+ m.modelPicker = nil+ m.modelPickerModels = nil+ m.openModelOnInit = false+ m.status = "ready"+ return m, nil+ case tea.KeyEnter:+ return m.selectModel()+ default:+ m.modelPicker.UpdateNavigation(msg)+ }+ return m, nil+}++func (m chatModel) selectModel() (tea.Model, tea.Cmd) {+ if m.modelPicker == nil {+ return m, nil+ }+ selectedItem, ok := m.modelPicker.SelectedItem()+ if !ok {+ return m, nil+ }+ selected, ok := m.modelOptionForSelection(selectedItem.Name)+ if !ok {+ return m, nil+ }++ // Cloud models need auth + plan check before switching. If we already+ // know the badge state from the model list, go directly to the right+ // prompt — no "checking" spinner.+ if selected.Cloud && m.opts.CheckCloudModel != nil {+ switch selected.AvailabilityBadge {+ case "Sign in required":+ return m.startCloudAuthSignIn(selected.Name, selected.RequiredPlan, selected.SignInURL)+ case "Upgrade required":+ return m.startCloudAuthUpgrade(selected.Name, selected.RequiredPlan)+ }+ // Badge is empty — auth is satisfied (confirmed via Whoami when the+ // list was built). Apply directly.+ }++ m.modelPicker = nil+ m.modelPickerModels = nil+ m.openModelOnInit = false+ if err := m.applyModelSelection(selected.Name, true); err != nil {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "error", content: fmt.Sprintf("Could not switch model: %v", err), err: err.Error()}))+ m.status = "error"+ return m, nil+ }+ m.status = "ready"+ return m, tea.Batch(m.startModelPreload(selected.Name), cloudModelPreflightCmd(m.ctx, m.opts, selected.Name, selected.RequiredPlan))+}++func (m chatModel) modelOptionForSelection(name string) (ModelOption, bool) {+ for _, model := range m.modelPickerModels {+ if model.Name == name {+ return model, true+ }+ }+ return ModelOption{}, false+}++func (m *chatModel) applyModelSelection(modelName string, persist bool) error {+ modelName = strings.TrimSpace(modelName)+ if modelName == "" {+ return nil+ }+ m.opts.Model = modelName+ m.opts.ContextWindowTokens = 0+ if m.opts.ToolRegistryForModel != nil {+ m.opts.Tools = m.opts.ToolRegistryForModel(m.ctx, modelName)+ }+ if m.opts.SystemPromptForModel != nil {+ m.opts.SystemPrompt = m.opts.SystemPromptForModel(m.ctx, modelName, m.opts.Tools)+ }+ if m.opts.MultiModalForModel != nil {+ ctx := m.ctx+ if ctx == nil {+ ctx = context.Background()+ }+ m.opts.MultiModal = m.opts.MultiModalForModel(ctx, modelName)+ }+ m.refreshContextWindowTokens(modelName)+ m.contextTokens = m.estimatePromptTokens(m.messages, "")+ m.contextEstimate = true+ if persist && m.opts.OnModelSelected != nil {+ ctx := m.ctx+ if ctx == nil {+ ctx = context.Background()+ }+ return m.opts.OnModelSelected(ctx, modelName)+ }+ return nil+}++func (m *chatModel) startModelPreload(modelName string) tea.Cmd {+ modelName = strings.TrimSpace(modelName)+ if m == nil || modelName == "" || m.opts.PreloadModel == nil {+ return nil+ }+ m.preloadingModel = modelName+ m.spinner = 0+ return tea.Batch(preloadModelCmd(m.ctx, m.opts.PreloadModel, modelName, m.opts.Think), m.scheduleTick())+}++func (m chatModel) renderModelPicker(width int) string {+ return m.modelPicker.RenderContent()+}++func (m chatModel) renderInlineModelPicker(width int) []string {+ rendered := m.modelPicker.RenderCompactContent(maxInlineModelPickerItems)+ lines := strings.Split(strings.TrimRight(rendered, "\n"), "\n")+ for i := range lines {+ lines[i] = truncateRenderedLine(lines[i], width)+ }+ return lines+}++func modelOptionMeta(model ModelOption) string {+ return strings.TrimSpace(model.Description)+}diff --git a/cmd/tui/chat/modals_test.go b/cmd/tui/chat/modals_test.gonew file mode 100644index 000000000..646207044--- /dev/null+++ b/cmd/tui/chat/modals_test.go@@ -0,0 +1,441 @@+package chat++import (+ "context"+ "slices"+ "strings"+ "testing"++ tea "github.com/charmbracelet/bubbletea"++ coreagent "github.com/ollama/ollama/agent"+ "github.com/ollama/ollama/api"+ apptui "github.com/ollama/ollama/cmd/tui"+)++func TestChatModelCommandOpensPicker(t *testing.T) {+ m := chatModel{+ ctx: context.Background(),+ input: []rune("/model"),+ width: 100,+ height: 20,+ opts: Options{+ Model: "llama3.2",+ ContextWindowTokens: 131072,+ ModelOptions: func(context.Context) ([]ModelOption, error) {+ return []ModelOption{+ {Name: "kimi-k2.6:cloud", Description: "cloud coding"},+ {Name: "llama3.2", Description: "local"},+ }, nil+ },+ },+ }++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("model command should not return a command")+ }+ m = updated.(chatModel)+ if m.modelPicker == nil {+ t.Fatal("model picker was not opened")+ }+ view := stripANSI(m.View())+ if !strings.Contains(view, "Select model") ||+ !strings.Contains(view, "Type to filter") ||+ !strings.Contains(view, "kimi-k2.6:cloud") ||+ !strings.Contains(view, "llama3.2") {+ t.Fatalf("model picker view missing content: %q", view)+ }+ if strings.Contains(view, "Search...") {+ t.Fatalf("model picker should render inline without full search box: %q", view)+ }+ if strings.Contains(view, "local") || strings.Contains(view, "cloud coding") {+ t.Fatalf("inline model picker should stay compact without descriptions: %q", view)+ }+ if !strings.Contains(view, "│ █") {+ t.Fatalf("inline model picker should keep input box visible: %q", view)+ }+}++func TestChatModelCommandShowsRecommendedFirstWithoutSections(t *testing.T) {+ m := chatModel{+ ctx: context.Background(),+ input: []rune("/model"),+ width: 100,+ height: 20,+ opts: Options{+ Model: "llama3.2",+ ModelOptions: func(context.Context) ([]ModelOption, error) {+ return []ModelOption{+ {Name: "llama3.2", Description: "selected local"},+ {Name: "gemma4", Description: "local"},+ {Name: "glm-5.2:cloud", Description: "recommended cloud", Recommended: true, Cloud: true},+ {Name: "kimi-k2.7-code:cloud", Description: "another recommended cloud", Recommended: true, Cloud: true},+ }, nil+ },+ },+ }++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("model command should not return a command")+ }+ view := stripANSI(updated.(chatModel).View())+ for _, unwanted := range []string{"Recommended", "More", "recommended cloud", "selected local"} {+ if strings.Contains(view, unwanted) {+ t.Fatalf("compact model picker should be flat and description-free; found %q in %q", unwanted, view)+ }+ }+ firstRecommended := strings.Index(view, "glm-5.2:cloud")+ secondRecommended := strings.Index(view, "kimi-k2.7-code:cloud")+ current := strings.Index(view, "llama3.2")+ local := strings.Index(view, "gemma4")+ if firstRecommended < 0 || secondRecommended < 0 || current < 0 || local < 0 {+ t.Fatalf("compact model picker missing expected models: %q", view)+ }+ if !(firstRecommended < current && secondRecommended < current && current < local) {+ t.Fatalf("compact model picker order should be recommended, current, local: %q", view)+ }+}++func TestChatModelCommandOpensSmallPicker(t *testing.T) {+ m := chatModel{+ ctx: context.Background(),+ input: []rune("/model"),+ width: 100,+ height: 24,+ opts: Options{+ Model: "model-1",+ ModelOptions: func(context.Context) ([]ModelOption, error) {+ return []ModelOption{+ {Name: "model-1"},+ {Name: "model-2"},+ {Name: "model-3"},+ {Name: "model-4"},+ {Name: "model-5"},+ {Name: "model-6"},+ {Name: "model-7"},+ }, nil+ },+ },+ }++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("model command should not return a command")+ }+ m = updated.(chatModel)+ view := stripANSI(m.View())+ for _, want := range []string{"model-1", "model-5", "... and 2 more"} {+ if !strings.Contains(view, want) {+ t.Fatalf("small model picker missing %q: %q", want, view)+ }+ }+ if strings.Contains(view, "model-6") || strings.Contains(view, "model-7") {+ t.Fatalf("small model picker rendered too many items: %q", view)+ }+}++func TestChatModelPickerStaysInlineWhenSmall(t *testing.T) {+ m := chatModel{+ ctx: context.Background(),+ input: []rune("/model"),+ width: 44,+ height: 10,+ opts: Options{+ Model: "llama3.2",+ ModelOptions: func(context.Context) ([]ModelOption, error) {+ return []ModelOption{+ {Name: "kimi-k2.6:cloud", Description: "cloud coding"},+ {Name: "llama3.2", Description: "local"},+ }, nil+ },+ },+ }++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("model command should not return a command")+ }+ m = updated.(chatModel)+ view := stripANSI(m.View())+ if !strings.Contains(view, "Select model") || !strings.Contains(view, "Type to filter") {+ t.Fatalf("small model picker should stay inline: %q", view)+ }+ if strings.Contains(view, "Search...") {+ t.Fatalf("small model picker should not use bespoke full-frame search: %q", view)+ }+}++func TestChatModelPickerShowsRecommendedModelsFirst(t *testing.T) {+ models := normalizeModelOptions([]ModelOption{+ {Name: "llama3.2", Description: "local"},+ {Name: "kimi-k2.6:cloud", Description: "cloud coding", Recommended: true},+ {Name: "qwen3.5:cloud", Description: "cloud reasoning", Recommended: true},+ {Name: "gemma4", Description: "local"},+ })+ got := make([]string, 0, len(models))+ for _, model := range models {+ got = append(got, model.Name)+ }+ want := []string{"kimi-k2.6:cloud", "qwen3.5:cloud", "llama3.2", "gemma4"}+ if !slices.Equal(got, want) {+ t.Fatalf("model order = %#v, want %#v", got, want)+ }+}++func TestChatModelPickerPinsCurrentThenRecommendedModels(t *testing.T) {+ models := normalizeModelOptions([]ModelOption{+ {Name: "llama3.2", Description: "local"},+ {Name: "glm-5.2:cloud", Description: "cloud selected", Recommended: true, Cloud: true},+ {Name: "kimi-k2.7-code:cloud", Description: "cloud coding", Recommended: true, Cloud: true},+ {Name: "gemma4", Description: "local"},+ })++ items := modelSelectorItems(models, "glm-5.2:cloud")+ got := make([]string, 0, len(items))+ for _, item := range items {+ got = append(got, item.Name)+ }+ want := []string{"glm-5.2:cloud", "kimi-k2.7-code:cloud", "llama3.2", "gemma4"}+ if !slices.Equal(got, want) {+ t.Fatalf("selector item order = %#v, want %#v", got, want)+ }+ for _, item := range items[:3] {+ if !item.Recommended {+ t.Fatalf("%q should be pinned in the first picker section", item.Name)+ }+ }+ if items[0].Description != "cloud selected" {+ t.Fatalf("current model description = %q, want plain model description", items[0].Description)+ }+}++func TestInitialModelPickerRendersBeforeChatShell(t *testing.T) {+ models := normalizeModelOptions([]ModelOption{+ {Name: "glm-5.2:cloud", Description: "cloud selected", Recommended: true, Cloud: true},+ {Name: "llama3.2", Description: "local"},+ })+ picker := apptui.NewModelSelectorModel("Select model", modelSelectorItems(models, "glm-5.2:cloud"), "glm-5.2:cloud", "")+ m := chatModel{+ width: 100,+ height: 20,+ openModelOnInit: true,+ modelPicker: &picker,+ entries: []chatEntry{{role: "assistant", content: "old chat content"}},+ }++ view := stripANSI(m.View())+ if !strings.Contains(view, "Select model") || !strings.Contains(view, "llama3.2") {+ t.Fatalf("initial picker view missing model content: %q", view)+ }+ if strings.Contains(view, "old chat content") || strings.Contains(view, "│ █") {+ t.Fatalf("initial picker should render before chat shell: %q", view)+ }+}++func TestChatModelPickerRanksClosestFilteredModelFirst(t *testing.T) {+ models := normalizeModelOptions([]ModelOption{+ {Name: "gemma3:27b", Description: "recommended but longer", Recommended: true},+ {Name: "llama3.2", Description: "mentions gemm in description"},+ {Name: "gemma4:27b", Description: "longer local"},+ {Name: "gemma4", Description: "short local"},+ })+ picker := apptui.NewModelSelectorModel("Select model", modelSelectorItems(models, ""), "", "gemm")++ filtered := picker.FilteredItems()+ got := make([]string, 0, len(filtered))+ for _, model := range filtered {+ got = append(got, model.Name)+ }+ want := []string{"gemma4", "gemma3:27b", "gemma4:27b", "llama3.2"}+ if !slices.Equal(got, want) {+ t.Fatalf("filtered model order = %#v, want %#v", got, want)+ }+}++func TestChatModelPickerFiltersAndSwitchesModel(t *testing.T) {+ var savedModel string+ originalMessages := []api.Message{{Role: "user", Content: "keep me"}}+ m := chatModel{+ ctx: context.Background(),+ chatID: "chat-1",+ input: []rune("/model qwen"),+ width: 100,+ height: 20,+ messages: slices.Clone(originalMessages),+ opts: Options{+ Model: "llama3.2",+ ModelOptions: func(context.Context) ([]ModelOption, error) {+ return []ModelOption{+ {Name: "llama3.2", Description: "local"},+ {Name: "qwen3.5:cloud", Description: "cloud reasoning"},+ }, nil+ },+ ToolRegistryForModel: func(ctx context.Context, model string) *coreagent.Registry {+ if model != "qwen3.5:cloud" {+ t.Fatalf("tool registry model = %q, want qwen3.5:cloud", model)+ }+ registry := &coreagent.Registry{}+ registry.Register(chatTestTool{})+ return registry+ },+ ContextWindowTokensForModel: func(ctx context.Context, model string, fallback int) int {+ if model != "qwen3.5:cloud" {+ t.Fatalf("context model = %q, want qwen3.5:cloud", model)+ }+ if fallback != 0 {+ t.Fatalf("context fallback = %d, want 0 after model switch", fallback)+ }+ return 262144+ },+ SystemPromptForModel: func(ctx context.Context, model string, registry *coreagent.Registry) string {+ if model != "qwen3.5:cloud" {+ t.Fatalf("system prompt model = %q, want qwen3.5:cloud", model)+ }+ if registry == nil {+ t.Fatalf("system prompt registry missing fake tool: %#v", registry)+ }+ if _, ok := registry.Get("fake_tool"); !ok {+ t.Fatalf("system prompt registry missing fake tool: %#v", registry)+ }+ return "system for " + model+ },+ OnModelSelected: func(ctx context.Context, model string) error {+ savedModel = model+ return nil+ },+ },+ }++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("model command should not return a command")+ }+ m = updated.(chatModel)+ if m.modelPicker == nil || m.modelPicker.Filter() != "qwen" {+ t.Fatalf("model picker = %#v, want qwen filter", m.modelPicker)+ }+ if view := stripANSI(m.View()); !strings.Contains(view, "qwen3.5:cloud") || strings.Contains(view, "llama3.2") {+ t.Fatalf("filtered model picker view = %q", view)+ }++ updated, cmd = m.Update(tea.KeyMsg{Type: tea.KeyEnter})+ m = updated.(chatModel)+ if cmd != nil {+ t.Fatal("switching models should not start a command")+ }+ if m.modelPicker != nil {+ t.Fatal("model picker should close after selection")+ }+ if m.status != "ready" || m.notificationLine() != "" {+ t.Fatalf("model switch should not show action status, status=%q notification=%q", m.status, m.notificationLine())+ }+ if m.opts.Model != "qwen3.5:cloud" {+ t.Fatalf("model = %q, want qwen3.5:cloud", m.opts.Model)+ }+ if m.chatID != "chat-1" {+ t.Fatalf("chatID = %q, want chat-1", m.chatID)+ }+ if len(m.messages) != len(originalMessages) || m.messages[0].Content != originalMessages[0].Content {+ t.Fatalf("messages changed on model switch: %#v", m.messages)+ }+ if len(m.entries) != 0 {+ t.Fatalf("model switch should not append transcript entries: %#v", m.entries)+ }+ if savedModel != "qwen3.5:cloud" {+ t.Fatalf("saved model = %q, want qwen3.5:cloud", savedModel)+ }+ if m.opts.Tools == nil {+ t.Fatalf("tools registry was not rebuilt for model: %#v", m.opts.Tools)+ }+ if _, ok := m.opts.Tools.Get("fake_tool"); !ok {+ t.Fatalf("tools registry was not rebuilt for model: %#v", m.opts.Tools)+ }+ if m.opts.ContextWindowTokens != 262144 {+ t.Fatalf("context window = %d, want 262144", m.opts.ContextWindowTokens)+ }+ if m.opts.SystemPrompt != "system for qwen3.5:cloud" {+ t.Fatalf("system prompt = %q", m.opts.SystemPrompt)+ }+}++func TestChatModelSelectionStartsBackgroundPreload(t *testing.T) {+ m := chatModel{+ ctx: context.Background(),+ opts: Options{+ Model: "llama3.2",+ PreloadModel: func(context.Context, string, *api.ThinkValue) (int, error) {+ return 0, nil+ },+ },+ }++ if err := m.applyModelSelection("qwen3", false); err != nil {+ t.Fatal(err)+ }+ cmd := m.startModelPreload("qwen3")+ if cmd == nil {+ t.Fatal("model switch should start background preload when configured")+ }+ if m.preloadingModel != "qwen3" {+ t.Fatalf("preloadingModel = %q, want qwen3", m.preloadingModel)+ }+}++func TestChatModelSwitchNextRunKeepsHistory(t *testing.T) {+ client := &chatCaptureClient{}+ history := []api.Message{+ {Role: "user", Content: "old question"},+ {Role: "assistant", Content: "old answer"},+ }+ m := chatModel{+ ctx: context.Background(),+ chatID: "chat-1",+ messages: slices.Clone(history),+ input: []rune("continue"),+ opts: Options{+ Model: "llama3.2",+ Client: client,+ SystemPromptForModel: func(_ context.Context, model string, _ *coreagent.Registry) string {+ return "system for " + model+ },+ },+ }+ if err := m.applyModelSelection("qwen3", true); err != nil {+ t.Fatal(err)+ }++ updated, cmd := m.handleSubmit()+ m = updated.(chatModel)+ if cmd == nil {+ t.Fatal("next prompt should start a model run")+ }+ done := waitForRunDone(t, m.events)+ if done.err != nil {+ t.Fatal(done.err)+ }++ if len(client.requests) != 1 {+ t.Fatalf("requests = %d, want 1", len(client.requests))+ }+ req := client.requests[0]+ if req.Model != "qwen3" {+ t.Fatalf("request model = %q, want qwen3", req.Model)+ }+ if len(req.Messages) != 4 {+ t.Fatalf("request messages = %#v, want system + 2 history + new user", req.Messages)+ }+ if req.Messages[0].Role != "system" || req.Messages[0].Content != "system for qwen3" {+ t.Fatalf("system message = %#v", req.Messages[0])+ }+ for i, want := range history {+ got := req.Messages[i+1]+ if got.Role != want.Role || got.Content != want.Content {+ t.Fatalf("history message %d = %#v, want %#v", i, got, want)+ }+ }+ if req.Messages[3].Role != "user" || req.Messages[3].Content != "continue" {+ t.Fatalf("new user message = %#v", req.Messages[3])+ }+}diff --git a/cmd/tui/chat/multimodal_test.go b/cmd/tui/chat/multimodal_test.gonew file mode 100644index 000000000..159465ce2--- /dev/null+++ b/cmd/tui/chat/multimodal_test.go@@ -0,0 +1,307 @@+package chat++import (+ "context"+ "net/url"+ "os"+ "path/filepath"+ "strings"+ "testing"++ tea "github.com/charmbracelet/bubbletea"+)++func TestChatStartRunAttachesDroppedImagePath(t *testing.T) {+ fp := writeTestPNG(t)+ m := chatModel{+ ctx: context.Background(),+ opts: Options{+ Model: "test",+ Client: chatTestClient{},+ MultiModal: true,+ },+ }++ updated, cmd := m.startRun("describe " + fp)+ m = updated.(chatModel)++ if cmd == nil {+ t.Fatal("startRun should return a command")+ }+ if len(m.liveMessages) != 1 {+ t.Fatalf("liveMessages = %d, want 1", len(m.liveMessages))+ }+ if got := m.liveMessages[0].Content; got != "describe" {+ t.Fatalf("content = %q, want describe", got)+ }+ if got := len(m.liveMessages[0].Images); got != 1 {+ t.Fatalf("images = %d, want 1", got)+ }+ if len(m.entries) == 0 {+ t.Fatal("missing user transcript entry")+ }+ entry := m.entries[0].content+ if strings.Contains(entry, fp) {+ t.Fatalf("transcript entry should hide local file path: %q", entry)+ }+ if !strings.Contains(entry, "describe") || !strings.Contains(entry, "[attached 1 file]") {+ t.Fatalf("transcript entry = %q, want prompt plus attachment note", entry)+ }+}++func TestChatStartRunAttachesDroppedFileURL(t *testing.T) {+ fp := writeTestPNG(t)+ fileURL := (&url.URL{Scheme: "file", Path: fp}).String()+ m := chatModel{+ ctx: context.Background(),+ opts: Options{+ Model: "test",+ Client: chatTestClient{},+ MultiModal: true,+ },+ }++ updated, _ := m.startRun(fileURL)+ m = updated.(chatModel)++ if got := m.liveMessages[0].Content; got != "" {+ t.Fatalf("content = %q, want empty prompt after extracting file URL", got)+ }+ if got := len(m.liveMessages[0].Images); got != 1 {+ t.Fatalf("images = %d, want 1", got)+ }+ if got := m.entries[0].content; got != "[attached 1 file]" {+ t.Fatalf("transcript entry = %q, want attachment-only note", got)+ }+}++func TestChatPasteImagePathAttachesOnSubmit(t *testing.T) {+ fp := writeTestPNG(t)+ m := chatModel{+ ctx: context.Background(),+ opts: Options{+ Model: "test",+ Client: chatTestClient{},+ MultiModal: true,+ },+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("describe " + fp), Paste: true})+ m = updated.(chatModel)+ if got := string(m.input); got != "describe [Image #0]" {+ t.Fatalf("pasted path input = %q, want placeholder", got)+ }+ if got := m.notificationLine(); got != "" {+ t.Fatalf("notification = %q, want no attachment notification", got)+ }+ if got := string(m.input); strings.Contains(got, fp) {+ t.Fatalf("pasted path should be hidden behind placeholder, input = %q", got)+ }+ if completions := m.slashCompletions(); len(completions) != 0 {+ t.Fatalf("placeholder input should not show slash completions: %#v", completions)+ }++ updated, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})+ m = updated.(chatModel)+ if cmd == nil {+ t.Fatal("submit should start a run")+ }+ if got := m.liveMessages[0].Content; got != "describe [Image #0]" {+ t.Fatalf("content = %q, want prompt with placeholder", got)+ }+ if got := len(m.liveMessages[0].Images); got != 1 {+ t.Fatalf("images = %d, want 1", got)+ }+ if strings.Contains(m.entries[0].content, fp) {+ t.Fatalf("transcript entry should hide pasted file path: %q", m.entries[0].content)+ }+ if !strings.Contains(m.entries[0].content, "[Image #0]") {+ t.Fatalf("transcript entry should show placeholder: %q", m.entries[0].content)+ }+}++func TestChatPasteImagePathAfterSwitchingToMultimodalModel(t *testing.T) {+ fp := writeTestPNG(t)+ m := chatModel{+ ctx: context.Background(),+ input: []rune("/model vision"),+ opts: Options{+ Model: "text",+ ModelOptions: func(context.Context) ([]ModelOption, error) {+ return []ModelOption{+ {Name: "text", Description: "local"},+ {Name: "vision", Description: "local vision"},+ }, nil+ },+ MultiModalForModel: func(_ context.Context, model string) bool {+ return model == "vision"+ },+ },+ }++ updated, cmd := m.handleSubmit()+ if cmd != nil {+ t.Fatal("model picker should not return a command")+ }+ m = updated.(chatModel)++ updated, cmd = m.Update(tea.KeyMsg{Type: tea.KeyEnter})+ if cmd != nil {+ t.Fatal("model switch should not preload without a preload hook")+ }+ m = updated.(chatModel)+ if m.opts.Model != "vision" {+ t.Fatalf("model = %q, want vision", m.opts.Model)+ }+ if !m.opts.MultiModal {+ t.Fatal("switching to a multimodal model should enable image paste handling")+ }++ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("describe " + fp), Paste: true})+ m = updated.(chatModel)+ if got := string(m.input); got != "describe [Image #0]" {+ t.Fatalf("pasted path input = %q, want placeholder", got)+ }+ if strings.Contains(string(m.input), fp) {+ t.Fatalf("pasted path should be hidden behind placeholder, input = %q", string(m.input))+ }+}++func TestChatImagePlaceholdersUseSessionNumbers(t *testing.T) {+ first := writeTestPNG(t)+ second := writeTestPNG(t)+ m := chatModel{+ ctx: context.Background(),+ opts: Options{+ Model: "test",+ Client: chatTestClient{},+ MultiModal: true,+ },+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(first), Paste: true})+ m = updated.(chatModel)+ if got := string(m.input); got != "[Image #0]" {+ t.Fatalf("first placeholder = %q, want [Image #0]", got)+ }++ updated, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})+ m = updated.(chatModel)+ if cmd == nil {+ t.Fatal("submit should start a run")+ }++ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(second), Paste: true})+ m = updated.(chatModel)+ if got := string(m.input); got != "[Image #1]" {+ t.Fatalf("second placeholder = %q, want [Image #1]", got)+ }+}++func TestChatAbsoluteImagePathBypassesSlashCommandParsing(t *testing.T) {+ fp := writeTestPNG(t)+ m := chatModel{+ ctx: context.Background(),+ opts: Options{+ Model: "test",+ Client: chatTestClient{},+ MultiModal: true,+ },+ }++ m.input = []rune(fp)+ m.inputCursor = len(m.input)+ m.inputCursorSet = true+ updated, cmd := m.handleSubmit()+ m = updated.(chatModel)++ if cmd == nil {+ t.Fatal("absolute image path should start a run instead of being parsed as a slash command")+ }+ if got := len(m.liveMessages[0].Images); got != 1 {+ t.Fatalf("images = %d, want 1", got)+ }+ if got := m.entries[0].role; got != "user" {+ t.Fatalf("entry role = %q, want user", got)+ }+}++func TestChatDeletingImagePlaceholderRemovesAttachment(t *testing.T) {+ fp := writeTestPNG(t)+ m := chatModel{+ ctx: context.Background(),+ opts: Options{+ Model: "test",+ Client: chatTestClient{},+ MultiModal: true,+ },+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("describe " + fp), Paste: true})+ m = updated.(chatModel)+ if got := len(m.inputAttachments); got != 1 {+ t.Fatalf("input attachments = %d, want 1", got)+ }++ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyBackspace})+ m = updated.(chatModel)+ if got := string(m.input); got != "describe " {+ t.Fatalf("input after backspace = %q, want image placeholder removed", got)+ }+ if got := len(m.inputAttachments); got != 0 {+ t.Fatalf("input attachments after editing placeholder = %d, want 0", got)+ }++ m.input = []rune("describe")+ m.inputCursor = len(m.input)+ m.inputCursorSet = true+ updated, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})+ m = updated.(chatModel)+ if cmd == nil {+ t.Fatal("submit should start a run")+ }+ if got := len(m.liveMessages[0].Images); got != 0 {+ t.Fatalf("images = %d, want 0 after deleting placeholder", got)+ }+ if got := m.liveMessages[0].Content; got != "describe" {+ t.Fatalf("content = %q, want describe", got)+ }+}++func TestChatWordDeletingImagePlaceholderRemovesAttachment(t *testing.T) {+ fp := writeTestPNG(t)+ m := chatModel{+ ctx: context.Background(),+ opts: Options{+ Model: "test",+ Client: chatTestClient{},+ MultiModal: true,+ },+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("describe " + fp), Paste: true})+ m = updated.(chatModel)+ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeySpace})+ m = updated.(chatModel)+ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyBackspace, Alt: true})+ m = updated.(chatModel)++ if got := string(m.input); got != "describe " {+ t.Fatalf("input after word backspace = %q, want image placeholder removed", got)+ }+ if got := len(m.inputAttachments); got != 0 {+ t.Fatalf("input attachments after word backspace = %d, want 0", got)+ }+}++func writeTestPNG(t *testing.T) string {+ t.Helper()+ dir := t.TempDir()+ fp := filepath.Join(dir, "dragged image.png")+ data := make([]byte, 600)+ copy(data, []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'})+ if err := os.WriteFile(fp, data, 0o600); err != nil {+ t.Fatalf("failed to write test image: %v", err)+ }+ return fp+}diff --git a/cmd/tui/chat/render.go b/cmd/tui/chat/render.gonew file mode 100644index 000000000..d76e77c93--- /dev/null+++ b/cmd/tui/chat/render.go@@ -0,0 +1,2169 @@+package chat++import (+ "context"+ "encoding/json"+ "fmt"+ "regexp"+ "slices"+ "sort"+ "strconv"+ "strings"+ "time"+ "unicode/utf8"++ "github.com/charmbracelet/lipgloss"+ "github.com/mattn/go-runewidth"++ coreagent "github.com/ollama/ollama/agent"+ "github.com/ollama/ollama/api"+)++type chatEntry struct {+ role string+ content string+ label string+ detail string+ status string+ err string+ toolID string+ args map[string]any+ expanded bool+ startedAt time.Time+ finishedAt time.Time+ tools []chatEntry+ metrics *api.Metrics++ version int+ renderKey chatEntryRenderKey+ renderLines []string+}++const (+ chatMessageIndent = " "+ chatUserMessagePrefix = ""+ maxCtrlOToolOutputRunes = 400++ defaultViewWidth = 80+ defaultViewHeight = 24+)++type chatEntryRenderKey struct {+ width int+ version int+}++func (m chatModel) findToolEntry(toolID string) int {+ if toolID == "" {+ return -1+ }+ for i := len(m.entries) - 1; i >= 0; i-- {+ if m.entries[i].role == "tool" && m.entries[i].toolID == toolID {+ return i+ }+ }+ return -1+}++func (m chatModel) findActiveToolEntry(toolID string) int {+ idx := m.findToolEntry(toolID)+ if idx < 0 || !isToolActiveStatus(m.entries[idx].status) {+ return -1+ }+ return idx+}++func (m chatModel) toolStartedAt(toolID string) time.Time {+ idx := m.findToolEntry(toolID)+ if idx < 0 {+ return time.Time{}+ }+ return m.entries[idx].startedAt+}++func entryHasExpandableOutput(entry chatEntry) bool {+ return (entry.role == "tool" && (len(entry.args) > 0 || strings.TrimSpace(entry.content) != "")) ||+ (entry.role == "tool_group" && len(entry.tools) > 0) ||+ (entry.role == "compaction_summary" && strings.TrimSpace(entry.content) != "")+}++func entryHasToolOutputMode(entry chatEntry) bool {+ return (entry.role == "tool" && (isToolActiveStatus(entry.status) || isToolResultStatus(entry.status) || entry.content != "")) ||+ (entry.role == "tool_group" && len(entry.tools) > 0) ||+ (entry.role == "compaction_summary" && strings.TrimSpace(entry.content) != "")+}++func (m *chatModel) applyToolOutputMode() {+ if !m.toolOutputMode {+ return+ }+ for i := range m.entries {+ m.applyToolOutputModeTo(i)+ }+}++func (m *chatModel) applyToolOutputModeTo(index int) {+ if !m.toolOutputMode || index < 0 || index >= len(m.entries) {+ return+ }+ if !entryHasToolOutputMode(m.entries[index]) {+ return+ }+ if m.entries[index].expanded == m.toolOutputOpen {+ return+ }+ m.entries[index].expanded = m.toolOutputOpen+ m.markEntryDirty(index)+}++func (m *chatModel) groupCompletedToolHistory() {+ if m.hasPendingDetectedToolCalls() {+ m.applyToolOutputMode()+ return+ }+ m.entries = groupCompletedToolEntries(m.entries, m.detectedToolCalls...)+ m.applyToolOutputMode()+}++func (m chatModel) hasPendingDetectedToolCalls() bool {+ if len(m.detectedToolCalls) == 0 {+ return false+ }+ results := map[string]struct{}{}+ for _, tool := range flattenToolHistory(m.entries) {+ if tool.toolID == "" || !isToolResultStatus(tool.status) {+ continue+ }+ results[tool.toolID] = struct{}{}+ }+ for _, tool := range m.detectedToolCalls {+ if tool.toolID == "" {+ continue+ }+ if _, ok := results[tool.toolID]; !ok {+ return true+ }+ }+ return false+}++func (m *chatModel) ensureAssistantEntry() int {+ if len(m.entries) > 0 && m.entries[len(m.entries)-1].role == "assistant" {+ return len(m.entries) - 1+ }+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "assistant"}))+ return len(m.entries) - 1+}++func (m chatModel) renderTranscript(width int) string {+ var b strings.Builder+ first := true+ for index, entry := range m.entries {+ prefix, body := m.renderEntry(entry)+ prefixWidth := lipgloss.Width(prefix)+ continuation := ""+ if prefixWidth > 0 {+ continuation = strings.Repeat(" ", prefixWidth)+ }+ lines := m.renderEntryLinesCached(index, entry, body, width-prefixWidth)+ if len(lines) == 0 {+ continue+ }+ if !first {+ b.WriteByte('\n')+ }+ first = false+ for i, line := range lines {+ if i == 0 {+ b.WriteString(prefix)+ b.WriteString(line)+ } else {+ b.WriteString(continuation)+ b.WriteString(line)+ }+ b.WriteByte('\n')+ }+ }+ return b.String()+}++// renderEntryLinesCached renders (and memoizes) the wrapped lines for an entry.+// Despite the value receiver, the cache write below mutates the caller's entries+// in place: m.entries is a slice, so the value-receiver copy shares its backing+// array with the caller. markEntryDirty invalidates a cached entry by bumping+// its version, which entryRenderKey compares against to decide whether to reuse+// or re-render.+func (m chatModel) renderEntryLinesCached(index int, entry chatEntry, body string, width int) []string {+ key := entryRenderKey(entry, width)+ if index >= 0 && index < len(m.entries) {+ cached := m.entries[index]+ if cached.renderKey == key && cached.renderLines != nil {+ return cached.renderLines+ }+ }++ lines := m.renderEntryLines(entry, body, width)+ if index >= 0 && index < len(m.entries) {+ m.entries[index].renderKey = key+ m.entries[index].renderLines = slices.Clone(lines)+ }+ return lines+}++func (m chatModel) transcriptLines(width int) []string {+ transcript := m.renderTranscript(width)+ transcript = strings.TrimRight(transcript, "\n")+ if transcript == "" {+ return nil+ }+ return strings.Split(transcript, "\n")+}++func (m chatModel) visibleTranscriptStartLine(width, available int) int {+ return m.visibleTranscriptStartLineForLines(len(m.transcriptLines(width)), available)+}++func (m chatModel) visibleTranscriptStartLineForLines(total, available int) int {+ if total <= available || available <= 0 {+ return 0+ }+ maxScroll := total - available+ scroll := clamp(m.scroll, 0, maxScroll)+ return maxScroll - scroll+}++func (m chatModel) viewWidth() int {+ width, _ := m.viewSize()+ return width+}++// defaultSize clamps caller-supplied dimensions to the standard fallbacks+// (80x24) when unset. Free functions that receive width/height as arguments+// (rather than reading them off the model) use this directly; methods use+// viewSize, which reads m.width/m.height first.+func defaultSize(width, height int) (int, int) {+ if width <= 0 {+ width = defaultViewWidth+ }+ if height <= 0 {+ height = defaultViewHeight+ }+ return width, height+}++func (m chatModel) viewSize() (int, int) {+ return defaultSize(m.width, m.height)+}++func (m chatModel) transcriptHeight() int {+ width, height := m.viewSize()+ lineCount := len(m.transcriptLines(width))+ baseHeaderHeight := 2+ baseMaxHeight := height - baseHeaderHeight+ baseBottomLines := m.bottomLines(width, baseMaxHeight)+ baseHeight := max(0, baseMaxHeight-len(baseBottomLines)-transcriptInputGap(baseMaxHeight, len(baseBottomLines), lineCount))+ if lineCount <= baseHeight {+ return lineCount+ }+ statusHeaderHeight := 3+ statusMaxHeight := height - statusHeaderHeight+ statusBottomLines := m.bottomLines(width, statusMaxHeight)+ return max(0, statusMaxHeight-len(statusBottomLines)-transcriptInputGap(statusMaxHeight, len(statusBottomLines), lineCount))+}++func (m chatModel) transcriptLayout() (top, height int) {+ width, height := m.viewSize()+ headerHeight := len(m.headerLines())+ bottomLines := m.bottomLines(width, height-headerHeight)+ transcriptLineCount := len(m.transcriptLines(width))+ return headerHeight, max(0, height-headerHeight-len(bottomLines)-transcriptInputGap(height-headerHeight, len(bottomLines), transcriptLineCount))+}++func (m chatModel) maxScroll() int {+ width, _ := m.viewSize()+ return max(0, len(m.transcriptLines(width))-m.transcriptHeight())+}++func (m chatModel) bottomLines(width, maxHeight int) []string {+ var lines []string+ if m.modelPicker != nil {+ lines = append(lines, m.renderInlineModelPicker(width)...)+ } else {+ lines = append(lines, m.completionLines(width)...)+ }++ actionStatusLines := m.renderActionStatusLines(width)+ approvalLines := m.renderApprovalPromptLines(width)+ if maxHeight > 0 {+ maxApprovalLines := max(0, maxHeight-len(lines)-len(actionStatusLines)-3)+ if len(approvalLines) > maxApprovalLines {+ approvalLines = approvalLines[:maxApprovalLines]+ }+ maxActionStatusLines := max(1, maxHeight-len(lines)-len(approvalLines)-3)+ if len(actionStatusLines) > maxActionStatusLines {+ actionStatusLines = actionStatusLines[:maxActionStatusLines]+ }+ }++ lines = append(lines, actionStatusLines...)+ lines = append(lines, approvalLines...)+ modelLines := m.renderModelStatusLines(width)+ fixedLines := len(lines) + 2+ if len(modelLines) > 0 {+ fixedLines += len(modelLines)+ }+ inputBodyLines := maxInputBoxBodyLines+ if maxHeight > 0 {+ inputBodyLines = min(inputBodyLines, max(1, maxHeight-fixedLines))+ }+ inputCursor := m.normalizedInputCursor()+ if m.approvalPrompt != nil || m.cloudAuthPrompt != nil {+ inputCursor = -1+ }+ lines = append(lines, renderInputBoxLines(string(m.input), inputCursor, width, inputBodyLines, m.emptyInputPlaceholder())...)+ if len(modelLines) > 0 {+ lines = append(lines, modelLines...)+ }+ return lines+}++func (m chatModel) renderModelStatusLines(width int) []string {+ if m.modelPicker != nil {+ return nil+ }+ var parts []string+ if model := strings.TrimSpace(m.opts.Model); model != "" {+ parts = append(parts, model)+ }+ if contextStatus := m.contextStatus(); contextStatus != "" {+ parts = append(parts, contextStatus)+ }+ if notice := m.permissionModeNotice(); notice != "" {+ parts = append(parts, notice)+ }+ if len(parts) == 0 {+ return nil+ }+ indent := inputBoxTextIndent()+ lines := wrapChatText(strings.Join(parts, " "), max(20, width-lipgloss.Width(indent)))+ for i := range lines {+ lines[i] = renderFooterPlainLine(indent + lines[i])+ }+ return lines+}++func (m chatModel) renderActionStatusLines(width int) []string {+ if activity := m.activityLine(); activity != "" {+ return []string{chatMetaStyle.Render(inputBoxTextIndent() + activity)}+ }+ if notificationLines := m.renderNotificationLines(width); len(notificationLines) > 0 {+ return notificationLines+ }+ return nil+}++func transcriptInputGap(maxHeight, bottomLineCount, transcriptLineCount int) int {+ const desiredGap = 1+ if transcriptLineCount == 0 {+ return 0+ }+ if maxHeight <= 0 {+ return desiredGap+ }+ available := maxHeight - bottomLineCount+ if available <= 1 {+ return 0+ }+ return min(desiredGap, available-1)+}++func (m *chatModel) scrollBy(lines int) {+ if lines == 0 {+ return+ }+ m.scroll = clamp(m.scroll+lines, 0, m.maxScroll())+}++var chatANSISequencePattern = regexp.MustCompile(`\x1b\[[0-9;:]*[A-Za-z]`)++func stripChatANSI(s string) string {+ return chatANSISequencePattern.ReplaceAllString(s, "")+}++func (m chatModel) normalizedSelectionRange() (chatSelectionPoint, chatSelectionPoint, bool) {+ return normalizedSelectionRangeFor(m.selection)+}++func normalizedSelectionRangeFor(selection chatSelection) (chatSelectionPoint, chatSelectionPoint, bool) {+ if !selection.active {+ return chatSelectionPoint{}, chatSelectionPoint{}, false+ }+ start, end := selection.anchor, selection.cursor+ if start.line > end.line || (start.line == end.line && start.col > end.col) {+ start, end = end, start+ }+ if start.line == end.line && start.col == end.col {+ return chatSelectionPoint{}, chatSelectionPoint{}, false+ }+ return start, end, true+}++func displayColumnToRuneIndex(line string, col int) int {+ if col <= 0 {+ return 0+ }+ width := 0+ for i, r := range []rune(line) {+ next := width + runewidth.RuneWidth(r)+ if col < next {+ return i+ }+ width = next+ }+ return len([]rune(line))+}++func (m chatModel) selectedTranscriptText(width int) string {+ start, end, ok := m.normalizedSelectionRange()+ if !ok {+ return ""+ }+ lines := m.transcriptLines(width)+ if len(lines) == 0 {+ return ""+ }+ start.line = clamp(start.line, 0, len(lines)-1)+ end.line = clamp(end.line, 0, len(lines)-1)+ var selected []string+ for lineIndex := start.line; lineIndex <= end.line; lineIndex++ {+ text := transcriptLineTextForSelection(stripChatANSI(lines[lineIndex]))+ runes := []rune(text)+ startCol, endCol := 0, len(runes)+ if lineIndex == start.line {+ startCol = displayColumnToRuneIndex(text, start.col)+ }+ if lineIndex == end.line {+ endCol = displayColumnToRuneIndex(text, end.col)+ }+ if startCol > endCol {+ startCol, endCol = endCol, startCol+ }+ selected = append(selected, string(runes[startCol:endCol]))+ }+ return strings.TrimRight(strings.Join(selected, "\n"), "\n")+}++func transcriptLineTextForSelection(text string) string {+ firstPrefix := chatMessageIndent + chatUserMessagePrefix+ if strings.HasPrefix(text, firstPrefix) {+ return chatMessageIndent + strings.TrimPrefix(text, firstPrefix)+ }+ continuationPrefix := chatMessageIndent + strings.Repeat(" ", lipgloss.Width(chatUserMessagePrefix))+ if strings.HasPrefix(text, continuationPrefix) {+ return chatMessageIndent + strings.TrimPrefix(text, continuationPrefix)+ }+ return text+}++func (m chatModel) renderEntry(entry chatEntry) (string, string) {+ switch entry.role {+ case "user":+ return "", entry.content+ case "assistant":+ return "", entry.content+ case "thinking":+ return chatMetaStyle.Render("•") + " ", thinkingStatusLine(entry)+ case "slash":+ return chatMetaStyle.Render("•") + " ", entry.content+ case "compaction_summary":+ prefix := toolStatusStyle(entry.status).Render("•") + " "+ return prefix, compactionSummaryStatusLine(entry)+ case "tool":+ prefix := toolStatusStyle(entry.status).Render("•") + " "+ return prefix, toolStatusLine(entry)+ case "tool_group":+ prefix := toolGroupPrefixStyle(entry).Render("•") + " "+ return prefix, toolGroupStatusLine(entry)+ case "error":+ return chatErrorStyle.Render("err ") + " ", entry.content+ case "system":+ return "", entry.content+ default:+ return "", entry.content+ }+}++func (m chatModel) renderEntryLines(entry chatEntry, body string, width int) []string {+ if width < 20 {+ width = 20+ }+ switch entry.role {+ case "assistant":+ innerWidth := max(1, width-lipgloss.Width(chatMessageIndent))+ lines := indentLines(splitRenderedBody(renderMarkdownForView(body, innerWidth)), chatMessageIndent)+ lines = append(lines, indentLines(renderMetricsLines(entry.metrics, innerWidth), chatMessageIndent)...)+ return lines+ case "thinking":+ return renderThinkingLines(entry, width)+ case "system", "slash":+ return splitRenderedBody(renderMarkdownForView(body, width))+ case "user":+ return renderUserMessageLines(body, width)+ case "compaction_summary":+ return renderCompactionSummaryLines(entry, width)+ case "tool":+ if entryHasExpandableOutput(entry) {+ return renderToolResultLines(entry, width)+ }+ if isToolResultStatus(entry.status) {+ return renderToolResultLines(entry, width)+ }+ return wrapChatText(body, width)+ case "tool_group":+ return renderToolGroupLines(entry, width)+ default:+ return wrapChatText(body, width)+ }+}++func renderUserMessageLines(content string, width int) []string {+ if width < 20 {+ width = 20+ }+ firstPrefix := chatMessageIndent + chatUserMessagePrefix+ continuationPrefix := chatMessageIndent + strings.Repeat(" ", lipgloss.Width(chatUserMessagePrefix))+ innerWidth := max(1, width-lipgloss.Width(firstPrefix))+ lines := wrapChatText(content, innerWidth)+ for i, line := range lines {+ prefix := continuationPrefix+ if i == 0 {+ prefix = firstPrefix+ }+ lines[i] = chatUserBlockStyle.Render(padRenderedLine(prefix+line, width))+ }+ return lines+}++func renderMetricsLines(metrics *api.Metrics, width int) []string {+ summary := metricsSummaryLines(metrics)+ if len(summary) == 0 {+ return nil+ }+ var lines []string+ for _, line := range summary {+ for _, wrapped := range wrapChatText(line, width) {+ lines = append(lines, chatMetaStyle.Render(wrapped))+ }+ }+ return lines+}++func metricsSummaryLines(metrics *api.Metrics) []string {+ if metrics == nil || metricsEmpty(*metrics) {+ return nil+ }+ var lines []string+ if metrics.TotalDuration > 0 {+ lines = append(lines, fmt.Sprintf("total duration: %v", metrics.TotalDuration))+ }+ if metrics.LoadDuration > 0 {+ lines = append(lines, fmt.Sprintf("load duration: %v", metrics.LoadDuration))+ }+ if metrics.PromptEvalCount > 0 {+ lines = append(lines, fmt.Sprintf("prompt eval count: %d token(s)", metrics.PromptEvalCount))+ }+ if metrics.PromptEvalDuration > 0 {+ lines = append(lines, fmt.Sprintf("prompt eval duration: %s", metrics.PromptEvalDuration))+ lines = append(lines, fmt.Sprintf("prompt eval rate: %.2f tokens/s", float64(metrics.PromptEvalCount)/metrics.PromptEvalDuration.Seconds()))+ }+ if metrics.EvalCount > 0 {+ lines = append(lines, fmt.Sprintf("eval count: %d token(s)", metrics.EvalCount))+ }+ if metrics.EvalDuration > 0 {+ lines = append(lines, fmt.Sprintf("eval duration: %s", metrics.EvalDuration))+ lines = append(lines, fmt.Sprintf("eval rate: %.2f tokens/s", float64(metrics.EvalCount)/metrics.EvalDuration.Seconds()))+ }+ return lines+}++func metricsEmpty(metrics api.Metrics) bool {+ return metrics.TotalDuration <= 0 &&+ metrics.LoadDuration <= 0 &&+ metrics.PromptEvalCount <= 0 &&+ metrics.PromptEvalDuration <= 0 &&+ metrics.EvalCount <= 0 &&+ metrics.EvalDuration <= 0+}++func historyRoleStyle(role string) lipgloss.Style {+ switch role {+ case "system":+ return chatHistorySystemRoleStyle+ case "user":+ return chatHistoryUserRoleStyle+ case "assistant":+ return chatHistoryAssistantRoleStyle+ case "tool":+ return chatHistoryToolRoleStyle+ default:+ return chatHistoryTitleStyle+ }+}++func renderToolResultLines(entry chatEntry, width int) []string {+ lines := wrapChatText(toolStatusLine(entry), width)+ if !entry.expanded {+ return lines+ }++ detailLines := renderToolCallDetailLines(entry, width)+ if len(detailLines) > 0 {+ lines = append(lines, "")+ lines = append(lines, detailLines...)+ }+ if strings.TrimSpace(entry.content) != "" {+ lines = append(lines, "")+ lines = append(lines, renderToolOutputLines(entry, entry.content, width)...)+ }+ return lines+}++func renderToolGroupLines(entry chatEntry, width int) []string {+ lines := wrapChatText(toolGroupStatusLine(entry), width)+ if !entry.expanded {+ return lines+ }++ for i, tool := range entry.tools {+ if i > 0 {+ lines = append(lines, "")+ }+ lines = append(lines, " "+toolGroupChildStatusLine(tool))+ if detailLines := renderToolCallDetailLines(tool, width-4); len(detailLines) > 0 {+ lines = append(lines, indentLines(detailLines, " ")...)+ }+ if strings.TrimSpace(tool.content) == "" {+ continue+ }+ lines = append(lines, indentLines(renderToolOutputLines(tool, tool.content, width-4), " ")...)+ }+ return lines+}++func renderCompactionSummaryLines(entry chatEntry, width int) []string {+ lines := wrapChatText(compactionSummaryStatusLine(entry), width)+ if !entry.expanded || strings.TrimSpace(entry.content) == "" {+ return lines+ }+ lines = append(lines, "")+ lines = append(lines, indentLines(splitRenderedBody(renderMarkdownForView(entry.content, width-2)), " ")...)+ return lines+}++func compactionSummaryStatusLine(entry chatEntry) string {+ segment := toolStatusStyle(entry.status).Render(toolStatusLabel(entry))+ if segment == "" {+ return "Compacted summary"+ }+ return fmt.Sprintf("Compacted summary %s", segment)+}++func renderThinkingLines(entry chatEntry, width int) []string {+ if !entry.expanded || strings.TrimSpace(entry.content) == "" {+ return nil+ }+ lines := wrapChatText(thinkingStatusLine(entry), width)+ lines = append(lines, "")+ lines = append(lines, indentLines(splitRenderedBody(renderMarkdownForView(entry.content, width-2)), " ")...)+ return lines+}++func thinkingStatusLine(entry chatEntry) string {+ if strings.TrimSpace(entry.label) != "" {+ return entry.label+ }+ return "Thinking"+}++func (m chatModel) thinkingLabel() string {+ return thinkingActivityLabel(m.thinkingTokens)+}++func thinkingActivityLabel(tokens int) string {+ if tokens > 0 {+ return "Thinking ↓ " + formatTokenCount(tokens)+ }+ return "Thinking"+}++func (m *chatModel) syncThinkingEntry() {+ if strings.TrimSpace(m.latestLiveThinking()) == "" {+ return+ }+ idx := -1+ if len(m.entries) > 0 && m.entries[len(m.entries)-1].role == "thinking" && m.entries[len(m.entries)-1].status == "running" {+ idx = len(m.entries) - 1+ }+ if idx < 0 {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "thinking", status: "running"}))+ idx = len(m.entries) - 1+ }+ m.entries[idx].content = m.latestLiveThinking()+ m.entries[idx].label = m.thinkingLabel()+ m.entries[idx].status = "running"+ m.entries[idx].expanded = false+ m.markEntryDirty(idx)+}++func (m chatModel) latestLiveThinking() string {+ for i := len(m.liveMessages) - 1; i >= 0; i-- {+ if m.liveMessages[i].Role == "assistant" && strings.TrimSpace(m.liveMessages[i].Thinking) != "" {+ return m.liveMessages[i].Thinking+ }+ }+ return ""+}++func (m *chatModel) finishThinkingEntry() {+ if len(m.entries) == 0 {+ return+ }+ idx := len(m.entries) - 1+ if m.entries[idx].role != "thinking" || m.entries[idx].status != "running" {+ return+ }+ m.entries[idx].status = "done"+ m.entries[idx].label = m.thinkingLabel()+ m.markEntryDirty(idx)+}++func toolGroupChildStatusLine(entry chatEntry) string {+ label := toolGroupChildStatusLabel(entry)++ segment := renderToolStatusSegment(entry)+ if segment == "" {+ return boldToolInvocationName(label)+ }+ return fmt.Sprintf("%s %s", boldToolInvocationName(label), segment)+}++func toolGroupChildStatusLabel(entry chatEntry) string {+ if strings.TrimSpace(entry.label) != "" {+ return entry.label+ }+ if strings.TrimSpace(entry.detail) != "" {+ return toolInvocationLabel(entry.detail, entry.args)+ }+ return toolEntryStatusLabel(entry)+}++func boldToolInvocationName(label string) string {+ name, rest, ok := strings.Cut(label, "(")+ if !ok || name == "" {+ return chatHeaderStyle.Render(label)+ }+ return chatHeaderStyle.Render(name) + "(" + rest+}++func renderToolOutputLines(entry chatEntry, output string, width int) []string {+ output = stripInternalToolTruncationMarkers(output)+ output = truncateCtrlOToolOutput(output)+ if looksLikeUnifiedDiff(output) {+ return splitRenderedBody(renderDiffForView(output, width))+ }+ if toolOutputUsesMarkdown(entry.detail) {+ return styleLines(splitRenderedBody(renderMarkdownForView(output, width)), chatToolOutputStyle)+ }+ return styleLines(wrapChatText(output, width), chatToolOutputStyle)+}++func styleLines(lines []string, style lipgloss.Style) []string {+ for i := range lines {+ lines[i] = style.Render(lines[i])+ }+ return lines+}++func truncateCtrlOToolOutput(output string) string {+ runes := []rune(output)+ if len(runes) <= maxCtrlOToolOutputRunes {+ return output+ }+ return string(runes[:maxCtrlOToolOutputRunes-3]) + "..."+}++func stripInternalToolTruncationMarkers(output string) string {+ lines := strings.Split(output, "\n")+ filtered := lines[:0]+ for _, line := range lines {+ trimmed := strings.TrimSpace(line)+ if strings.HasPrefix(trimmed, "[tool output truncated: ") && strings.HasSuffix(trimmed, "]") {+ continue+ }+ filtered = append(filtered, line)+ }+ return strings.TrimSpace(strings.Join(filtered, "\n"))+}++func looksLikeUnifiedDiff(output string) bool {+ lines := strings.Split(output, "\n")+ hasOldFile := false+ hasNewFile := false+ hasHunk := false+ for _, line := range lines {+ switch {+ case strings.HasPrefix(line, "diff --git "):+ return true+ case strings.HasPrefix(line, "--- "):+ hasOldFile = true+ case strings.HasPrefix(line, "+++ "):+ hasNewFile = true+ case strings.HasPrefix(line, "@@ "):+ hasHunk = true+ }+ }+ return hasHunk || (hasOldFile && hasNewFile)+}++func renderDiffForView(diff string, width int) string {+ if width < 20 {+ width = 20+ }+ lines := strings.Split(strings.TrimRight(diff, "\n"), "\n")+ rendered := make([]string, 0, len(lines))+ for _, line := range lines {+ style := diffLineStyle(line)+ for _, wrapped := range wrapChatText(line, width) {+ rendered = append(rendered, style.Render(wrapped))+ }+ }+ return strings.Join(rendered, "\n")+}++func diffLineStyle(line string) lipgloss.Style {+ switch {+ case strings.HasPrefix(line, "diff --git "),+ strings.HasPrefix(line, "--- "),+ strings.HasPrefix(line, "+++ "):+ return chatDiffFileStyle+ case strings.HasPrefix(line, "@@ "):+ return chatDiffHunkStyle+ case strings.HasPrefix(line, "+"):+ return chatDiffAddStyle+ case strings.HasPrefix(line, "-"):+ return chatDiffDeleteStyle+ case strings.HasPrefix(line, "index "),+ strings.HasPrefix(line, "new file "),+ strings.HasPrefix(line, "deleted file "),+ strings.HasPrefix(line, "similarity index "),+ strings.HasPrefix(line, "rename from "),+ strings.HasPrefix(line, "rename to "),+ strings.HasPrefix(line, "\\ "):+ return chatDiffMetaStyle+ default:+ return chatToolStyle+ }+}++func isToolActiveStatus(status string) bool {+ return status == "queued" || status == "running" || status == "approval"+}++func isToolResultStatus(status string) bool {+ return status == "done" || status == "error" || status == "denied" || status == "disabled"+}++// renderToolStatusSegment returns the styled status text for a tool entry,+// or "" when the entry has no status word to show (e.g. a completed or failed+// tool, where the colored dot alone conveys the result).+func renderToolStatusSegment(entry chatEntry) string {+ s := toolStatusLabel(entry)+ if s == "" {+ return ""+ }+ return chatMetaStyle.Render(s)+}++func toolStatusLine(entry chatEntry) string {+ label := toolEntryStatusLabel(entry)++ segment := renderToolStatusSegment(entry)+ if segment == "" {+ return label+ }+ return fmt.Sprintf("%s %s", label, segment)+}++func toolEntryStatusLabel(entry chatEntry) string {+ if isShellToolName(entry.detail) {+ switch entry.status {+ case "approval":+ if entry.label != "" {+ return entry.label+ }+ return toolInvocationLabel(entry.detail, entry.args)+ case "denied":+ if entry.label != "" {+ return entry.label + " denied"+ }+ return toolInvocationLabel(entry.detail, entry.args) + " denied"+ case "queued", "running", "done", "error":+ if entry.label != "" {+ return entry.label+ }+ return toolInvocationLabel(entry.detail, entry.args)+ }+ }+ if entry.status == "denied" {+ if entry.label != "" {+ return entry.label + " denied"+ }+ return toolDisplayName(entry.detail) + " denied"+ }+ if entry.label != "" {+ return entry.label+ }+ return toolDisplayName(entry.detail)+}++func toolGroupStatusLine(entry chatEntry) string {+ label := entry.label+ if label == "" || strings.HasPrefix(label, "Tool calls (") {+ label = toolGroupSummary(entry.tools)+ }++ segment := renderToolStatusSegment(entry)+ if segment == "" {+ return label+ }+ return fmt.Sprintf("%s %s", label, segment)+}++func toolGroupSummary(tools []chatEntry) string {+ if len(tools) == 0 {+ return "Used tools"+ }++ type actionCount struct {+ action string+ count int+ }++ var counts []actionCount+ indexes := map[string]int{}+ for _, tool := range tools {+ action := toolActionForEntry(tool)+ if index, ok := indexes[action]; ok {+ counts[index].count+++ continue+ }+ indexes[action] = len(counts)+ counts = append(counts, actionCount{action: action, count: 1})+ }++ phrases := make([]string, 0, len(counts))+ for _, count := range counts {+ phrases = append(phrases, toolActionPhrase(count.action, count.count))+ }+ return joinToolActionPhrases(phrases)+}++func toolActionForEntry(tool chatEntry) string {+ if tool.status == "denied" {+ if isShellToolName(tool.detail) || strings.Contains(strings.ToLower(tool.label), "bash(") || strings.Contains(strings.ToLower(tool.label), "powershell(") {+ return "denied_command"+ }+ return "denied_tool"+ }+ if tool.status == "disabled" {+ if isShellToolName(tool.detail) || strings.Contains(strings.ToLower(tool.label), "bash(") || strings.Contains(strings.ToLower(tool.label), "powershell(") {+ return "disabled_command"+ }+ return "disabled_tool"+ }+ action := toolAction(tool.detail)+ if action == "" {+ action = toolAction(tool.label)+ }+ if action == "" {+ action = "tool"+ }+ return action+}++func toolAction(name string) string {+ name = strings.TrimSpace(strings.ToLower(name))+ switch {+ case isShellToolName(name):+ return "command"+ case strings.Contains(name, "bash") || strings.Contains(name, "powershell"):+ return "command"+ case strings.HasPrefix(name, "edit("):+ return "edit"+ case strings.HasPrefix(name, "read("):+ return "read"+ case strings.HasPrefix(name, "list("):+ return "list"+ case strings.HasPrefix(name, "web search("):+ return "search"+ case strings.HasPrefix(name, "web fetch("):+ return "fetch"+ case strings.HasPrefix(name, "skill("):+ return "skill"+ }+ switch name {+ case "edit":+ return "edit"+ case "read":+ return "read"+ case "list":+ return "list"+ case "web_search":+ return "search"+ case "web_fetch":+ return "fetch"+ case "skill":+ return "skill"+ default:+ return "tool"+ }+}++func toolActionPhrase(action string, count int) string {+ plural := count != 1+ switch action {+ case "denied_command":+ if plural {+ return fmt.Sprintf("Denied %d commands", count)+ }+ return "Denied a command"+ case "denied_tool":+ if plural {+ return fmt.Sprintf("Denied %d tools", count)+ }+ return "Denied a tool"+ case "disabled_command":+ if plural {+ return fmt.Sprintf("Skipped %d commands", count)+ }+ return "Skipped a command"+ case "disabled_tool":+ if plural {+ return fmt.Sprintf("Skipped %d tools", count)+ }+ return "Skipped a tool"+ case "command":+ if plural {+ return fmt.Sprintf("Ran %d commands", count)+ }+ return "Ran 1 command"+ case "edit":+ if plural {+ return fmt.Sprintf("Edited %d files", count)+ }+ return "Edited a file"+ case "read":+ if plural {+ return fmt.Sprintf("Read %d files", count)+ }+ return "Read a file"+ case "list":+ if plural {+ return fmt.Sprintf("Listed files %d times", count)+ }+ return "Listed files"+ case "search":+ if plural {+ return fmt.Sprintf("Searched the web %d times", count)+ }+ return "Searched the web"+ case "fetch":+ if plural {+ return fmt.Sprintf("Fetched %d URLs", count)+ }+ return "Fetched a URL"+ case "skill":+ if plural {+ return fmt.Sprintf("Ran %d skills", count)+ }+ return "Ran a skill"+ default:+ if plural {+ return fmt.Sprintf("Used %d tools", count)+ }+ return "Used a tool"+ }+}++func joinToolActionPhrases(phrases []string) string {+ switch len(phrases) {+ case 0:+ return "Used tools"+ case 1:+ return phrases[0]+ case 2:+ return phrases[0] + " and " + lowerInitial(phrases[1])+ default:+ for i := 1; i < len(phrases); i++ {+ phrases[i] = lowerInitial(phrases[i])+ }+ return strings.Join(phrases[:len(phrases)-1], ", ") + ", and " + phrases[len(phrases)-1]+ }+}++func lowerInitial(s string) string {+ if s == "" {+ return s+ }+ runes := []rune(s)+ runes[0] = []rune(strings.ToLower(string(runes[0])))[0]+ return string(runes)+}++func toolGroupPrefixStyle(entry chatEntry) lipgloss.Style {+ succeeded, failed, denied := toolGroupResultCounts(entry.tools)+ switch {+ case succeeded > 0 && (failed > 0 || denied > 0):+ return chatToolMixedStyle+ case succeeded > 0:+ return chatToolDoneStyle+ case denied > 0 && failed == 0:+ return toolStatusStyle("denied")+ default:+ return toolStatusStyle(entry.status)+ }+}++func toolGroupResultCounts(tools []chatEntry) (succeeded int, failed int, denied int) {+ for _, tool := range tools {+ if tool.status == "denied" || tool.status == "disabled" {+ denied+++ continue+ }+ if tool.err != "" || tool.status == "error" {+ failed+++ continue+ }+ if tool.status == "done" {+ succeeded+++ }+ }+ return succeeded, failed, denied+}++func toolStatusLabel(entry chatEntry) string {+ if entry.status == "approval" {+ return "needs approval"+ }+ if entry.status == "running" || entry.status == "queued" {+ return ""+ }+ return ""+}++func toolStatusStyle(status string) lipgloss.Style {+ switch status {+ case "queued", "running", "approval":+ return chatToolRunningStyle+ case "done":+ return chatToolDoneStyle+ case "error":+ return chatErrorStyle+ case "denied", "disabled":+ return chatToolMixedStyle+ default:+ return chatMetaStyle+ }+}++func toolInvocationLabel(name string, args map[string]any) string {+ displayName := toolDisplayName(name)+ for _, key := range []string{"query", "url", "command", "path", "name"} {+ if value, ok := rawStringArg(args, key); ok {+ if isShellToolName(name) && key == "command" {+ value = truncateRunes(value, 100)+ }+ return fmt.Sprintf("%s(%s)", displayName, strconv.Quote(value))+ }+ }+ if len(args) == 0 {+ return displayName+ }+ return fmt.Sprintf("%s(%s)", displayName, formatDisplayArgs(args))+}++func toolDisplayName(name string) string {+ switch name {+ case "web_search":+ return "Web Search"+ case "web_fetch":+ return "Web Fetch"+ case "bash":+ return "Bash"+ case "powershell":+ return "PowerShell"+ case "read":+ return "Read"+ case "list":+ return "List"+ case "edit":+ return "Edit"+ default:+ if name == "" {+ return "Tool"+ }+ return name+ }+}++func toolOutputUsesMarkdown(name string) bool {+ switch name {+ case "read", "skill", "web_search", "web_fetch":+ return true+ default:+ return false+ }+}++func renderToolCallDetailLines(entry chatEntry, width int) []string {+ if len(entry.args) == 0 {+ return nil+ }+ if isShellToolName(entry.detail) {+ if command, ok := rawStringArg(entry.args, "command"); ok {+ return renderToolCallArgLine(shellPromptPrefix(entry.detail)+command, width)+ }+ }+ switch entry.detail {+ case "web_search":+ if query, ok := rawStringArg(entry.args, "query"); ok {+ return renderToolCallArgLine("query: "+query, width)+ }+ case "web_fetch":+ if targetURL, ok := rawStringArg(entry.args, "url"); ok {+ return renderToolCallArgLine("url: "+targetURL, width)+ }+ }+ return renderToolCallArgs(entry.args, width)+}++func isShellToolName(name string) bool {+ return name == "bash" || name == "powershell"+}++func formatDisplayArgs(args map[string]any) string {+ keys := make([]string, 0, len(args))+ for key := range args {+ keys = append(keys, key)+ }+ sort.Strings(keys)++ parts := make([]string, 0, len(keys))+ for _, key := range keys {+ value := truncateRunes(fmt.Sprintf("%v", args[key]), 100)+ parts = append(parts, fmt.Sprintf("%s=%s", key, strconv.Quote(value)))+ }+ return strings.Join(parts, ", ")+}++func shellPromptPrefix(toolName string) string {+ if toolName == "powershell" {+ return "PS> "+ }+ return "$ "+}++func renderToolCallArgs(args map[string]any, width int) []string {+ keys := make([]string, 0, len(args))+ for key := range args {+ keys = append(keys, key)+ }+ sort.Strings(keys)++ var lines []string+ for _, key := range keys {+ value := toolArgDisplayValue(args[key])+ if strings.Contains(value, "\n") {+ lines = append(lines, chatMetaStyle.Render(key+":"))+ lines = append(lines, indentLines(renderToolCallArgLine(value, max(20, width-2)), " ")...)+ continue+ }+ lines = append(lines, renderToolCallArgLine(key+": "+value, width)...)+ }+ return lines+}++func renderToolCallArgLine(line string, width int) []string {+ wrapped := wrapChatText(line, width)+ for i := range wrapped {+ wrapped[i] = chatMetaStyle.Render(wrapped[i])+ }+ return wrapped+}++func toolArgDisplayValue(value any) string {+ if value == nil {+ return "null"+ }+ if text, ok := value.(string); ok {+ return text+ }+ data, err := json.MarshalIndent(value, "", " ")+ if err == nil {+ return string(data)+ }+ return fmt.Sprint(value)+}++func rawStringArg(args map[string]any, key string) (string, bool) {+ value, ok := args[key].(string)+ if !ok || strings.TrimSpace(value) == "" {+ return "", false+ }+ return value, true+}++func isDeniedToolResult(value string) bool {+ value = strings.ToLower(strings.TrimSpace(value))+ return strings.Contains(value, "tool execution denied") ||+ strings.Contains(value, "tool approval canceled")+}++func isDisabledToolResult(value string) bool {+ return strings.Contains(strings.ToLower(strings.TrimSpace(value)), "tool execution disabled")+}++func truncateRunes(value string, limit int) string {+ runes := []rune(value)+ if len(runes) <= limit {+ return value+ }+ return string(runes[:limit]) + "..."+}++func (m chatModel) notificationLine() string {+ status := strings.TrimSpace(m.status)+ if status == "" || status == "ready" {+ return ""+ }+ if m.running || m.compacting || m.approvalPrompt != nil {+ return ""+ }+ switch status {+ case "running", "compacting", "approval required", "full access enabled", "review mode enabled":+ return ""+ default:+ return status+ }+}++func (m chatModel) renderNotificationLines(width int) []string {+ line := m.notificationLine()+ if line == "" {+ return nil+ }+ indent := inputBoxTextIndent()+ lines := wrapChatText(line, max(20, width-lipgloss.Width(indent)))+ for i, wrapped := range lines {+ lines[i] = chatNotificationStyle.Render(indent + wrapped)+ }+ return lines+}++func inputBoxTextIndent() string {+ return strings.Repeat(" ", inputBoxHorizontalPadding+1)+}++func renderFooterPlainLine(line string) string {+ const fullAccess = "full access"+ if !strings.Contains(line, fullAccess) {+ return chatFooterStyle.Render(line)+ }++ var b strings.Builder+ for {+ before, after, ok := strings.Cut(line, fullAccess)+ if before != "" {+ b.WriteString(chatFooterStyle.Render(before))+ }+ if !ok {+ break+ }+ b.WriteString(chatFullAccessStyle.Render(fullAccess))+ line = after+ }+ return b.String()+}++func (m chatModel) permissionModeNotice() string {+ if notice := strings.TrimSpace(m.permissionNotice); notice != "" {+ return notice+ }+ switch strings.TrimSpace(m.status) {+ case "full access enabled", "review mode enabled":+ return strings.TrimSpace(m.status)+ }+ if m.allowAllToolsEnabled() && m.notificationLine() == "" {+ return "full access enabled"+ }+ return ""+}++func (m *chatModel) refreshContextWindowTokens(modelName string) {+ if m == nil || m.opts.ContextWindowTokensForModel == nil {+ return+ }+ modelName = strings.TrimSpace(modelName)+ if modelName == "" {+ return+ }+ ctx := m.ctx+ if ctx == nil {+ ctx = context.Background()+ }+ tokens := m.opts.ContextWindowTokensForModel(ctx, modelName, m.opts.ContextWindowTokens)+ m.updateContextWindowTokens(tokens)+}++func (m *chatModel) updateContextWindowTokens(tokens int) {+ if tokens <= 0 || tokens == m.opts.ContextWindowTokens {+ return+ }+ m.opts.ContextWindowTokens = tokens+ if compactor, ok := m.opts.Compactor.(*coreagent.SimpleCompactor); ok && compactor != nil {+ compactor.Options.ContextWindowTokens = tokens+ }+}++func (m chatModel) responseModelName(response *api.ChatResponse) string {+ if response != nil {+ if strings.TrimSpace(response.Model) != "" {+ return response.Model+ }+ if strings.TrimSpace(response.RemoteModel) != "" {+ return response.RemoteModel+ }+ }+ return m.opts.Model+}++func (m chatModel) currentWorkingDir() string {+ if strings.TrimSpace(m.workingDir) != "" {+ return m.workingDir+ }+ return m.opts.WorkingDir+}++func (m chatModel) activityLine() string {+ if m.approvalPrompt != nil {+ return ""+ }+ if m.preloadingModel != "" && !m.running && !m.compacting {+ return ""+ }+ if !m.running && !m.compacting && m.preloadingModel == "" && m.approvalPrompt == nil {+ return ""+ }+ label := m.activityLabel()+ if label == "" {+ if m.awaitingToolStart() {+ return statusWithSpinner(m.spinnerFrame(), "Working")+ }+ if m.awaitingModel {+ return statusWithSpinner(m.spinnerFrame(), "Working")+ }+ if !m.waitingForModel() || m.spinner < idleWorkingDelayTicks {+ return ""+ }+ if m.preloadingModel != "" {+ return statusWithSpinner(m.spinnerFrame(), "Working")+ }+ return statusWithSpinner(m.spinnerFrame(), "Working")+ }+ if m.thinking {+ return label+ }+ return statusWithSpinner(m.spinnerFrame(), label)+}++func (m chatModel) activityLabel() string {+ if m.status == "canceling" {+ return "canceling"+ }+ if m.compacting {+ if m.compactingTokens > 0 {+ return "Compacting " + formatTokenCount(m.compactingTokens)+ }+ return "Compacting"+ }+ if m.thinking {+ return thinkingActivityLabel(m.thinkingTokens)+ }+ start := m.currentTurnEntryStart()+ for i := len(m.entries) - 1; i >= start; i-- {+ entry := m.entries[i]+ switch entry.role {+ case "tool":+ if isToolActiveStatus(entry.status) {+ return ""+ }+ case "tool_group":+ if entryHasActiveTool(entry) {+ return ""+ }+ case "assistant":+ if entry.content != "" {+ return ""+ }+ }+ }+ return ""+}++func (m chatModel) waitingForModel() bool {+ if m.preloadingModel != "" && !m.compacting && m.approvalPrompt == nil && m.status != "canceling" {+ return true+ }+ if !m.running || m.compacting || m.approvalPrompt != nil || m.thinking || m.status == "canceling" {+ return false+ }+ if m.awaitingModel {+ return true+ }+ start := m.currentTurnEntryStart()+ for i := len(m.entries) - 1; i >= start; i-- {+ entry := m.entries[i]+ switch entry.role {+ case "tool":+ if isToolActiveStatus(entry.status) {+ return false+ }+ case "tool_group":+ if entryHasActiveTool(entry) {+ return false+ }+ case "assistant":+ return true+ }+ }+ return true+}++func (m chatModel) currentTurnEntryStart() int {+ for i := len(m.entries) - 1; i >= 0; i-- {+ if m.entries[i].role == "user" {+ return i + 1+ }+ }+ return 0+}++func (m *chatModel) applyResponseMetrics(response *api.ChatResponse) {+ if response == nil {+ return+ }+ tokens := 0+ if response.PromptEvalCount > 0 {+ tokens = response.PromptEvalCount+ }+ if response.EvalCount > 0 {+ tokens += response.EvalCount+ }+ if tokens <= 0 {+ return+ }+ if m.running {+ if tokens > m.contextTokens {+ m.contextTokens = tokens+ }+ return+ }+ if tokens > 0 {+ m.contextTokens = tokens+ m.contextEstimate = false+ }+}++func (m chatModel) estimatePromptTokens(messages []api.Message, systemPrompt string) int {+ if strings.TrimSpace(systemPrompt) == "" {+ systemPrompt = m.systemPrompt("")+ }+ var tools api.Tools+ if m.opts.Tools != nil {+ tools = m.opts.Tools.Tools()+ }+ return estimatePromptTokenCount(systemPrompt, messages, tools, m.opts.Format)+}++func estimatePromptTokenCount(systemPrompt string, messages []api.Message, tools api.Tools, format string) int {+ total := approximateTokenCount(systemPrompt)+ for _, msg := range messages {+ total += approximateTokenCount(msg.Role)+ total += approximateTokenCount(msg.Content)+ total += approximateTokenCount(msg.Thinking)+ total += approximateTokenCount(msg.ToolName)+ total += approximateTokenCount(msg.ToolCallID)+ for _, call := range msg.ToolCalls {+ total += approximateTokenCount(call.Function.Name)+ total += approximateTokenCount(call.Function.Arguments.String())+ }+ }+ total += approximateTokenCount(tools.String())+ total += approximateTokenCount(format)+ return total+}++func approximateTokenCount(text string) int {+ n := len([]rune(text))+ if n <= 0 {+ return 0+ }+ return max(1, (n+3)/4)+}++func formatTokenCount(count int) string {+ if count == 1 {+ return "1 token"+ }+ return fmt.Sprintf("%d tokens", count)+}++func (m chatModel) contextStatus() string {+ window := m.displayContextWindowTokens()+ if window <= 0 {+ return ""+ }+ used := max(m.contextTokens, 0)+ percent := 0+ if window > 0 {+ percent = (used*100 + window/2) / window+ }++ prefix := ""+ if m.contextEstimate {+ prefix = "~"+ }++ threshold := coreagent.ResolveCompactionThreshold(m.opts.CompactionThreshold)+ compactAt := int(float64(window)*threshold + 0.999999)+ if compactAt <= 0 || compactAt > window {+ compactAt = window+ }++ if used >= compactAt {+ return fmt.Sprintf("ctx %s%s / %s (%d%% used)", prefix, formatContextTokenCount(used), formatContextTokenCount(window), percent)+ }++ noticeDistance := int(float64(window)*0.1 + 0.999999)+ if noticeDistance < 1 {+ noticeDistance = 1+ }+ if compactAt-used <= noticeDistance {+ return fmt.Sprintf("ctx %s%s / %s (%d%% used)", prefix, formatContextTokenCount(used), formatContextTokenCount(window), percent)+ }++ if percent > 60 {+ return fmt.Sprintf("ctx %s%s / %s (%d%% used)", prefix, formatContextTokenCount(used), formatContextTokenCount(window), percent)+ }++ return ""+}++func (m chatModel) displayContextWindowTokens() int {+ if n := chatIntOption(m.opts.Options, "num_ctx"); n > 0 {+ return n+ }+ return max(0, m.opts.ContextWindowTokens)+}++func chatIntOption(options map[string]any, key string) int {+ if options == nil {+ return 0+ }+ switch v := options[key].(type) {+ case int:+ return max(0, v)+ case int32:+ return max(0, int(v))+ case int64:+ return max(0, int(v))+ case uint:+ return int(v)+ case uint32:+ return int(v)+ case uint64:+ return int(v)+ case float64:+ if v == float64(int(v)) {+ return max(0, int(v))+ }+ case string:+ n, err := strconv.Atoi(strings.TrimSpace(v))+ if err == nil {+ return max(0, n)+ }+ }+ return 0+}++func formatContextTokenCount(value int) string {+ sign := ""+ if value < 0 {+ sign = "-"+ value = -value+ }+ if value >= 950_000 {+ return fmt.Sprintf("%s%dM", sign, int(float64(value)/1_000_000+0.5))+ }+ if value >= 10_240 {+ return fmt.Sprintf("%s%dk", sign, int(float64(value)/1024+0.5))+ }+ return sign + formatInteger(value)+}++func formatInteger(value int) string {+ sign := ""+ if value < 0 {+ sign = "-"+ value = -value+ }+ s := strconv.Itoa(value)+ if len(s) <= 3 {+ return sign + s+ }+ var b strings.Builder+ b.WriteString(sign)+ first := len(s) % 3+ if first == 0 {+ first = 3+ }+ b.WriteString(s[:first])+ for i := first; i < len(s); i += 3 {+ b.WriteByte(',')+ b.WriteString(s[i : i+3])+ }+ return b.String()+}++func (m chatModel) spinnerFrame() string {+ if len(chatSpinnerFrames) == 0 {+ return ""+ }+ return chatSpinnerFrames[m.spinner%len(chatSpinnerFrames)]+}++func statusWithSpinner(frame, label string) string {+ label = strings.TrimSpace(label)+ if label == "" {+ return strings.TrimSpace(frame)+ }+ return label + frame+}++func renderFullFrame(content string, width, height int) string {+ width, height = defaultSize(width, height)+ rendered := lipgloss.NewStyle().MaxWidth(width).Render(content)+ lines := strings.Split(strings.TrimRight(rendered, "\n"), "\n")+ if len(lines) > height {+ lines = lines[:height]+ }+ for len(lines) < height {+ lines = append(lines, "")+ }+ return strings.Join(lines, "\n")+}++func renderFrameLines(lines []string, width, height int) string {+ width, height = defaultSize(width, height)+ if len(lines) > height {+ lines = lines[:height]+ }+ out := make([]string, 0, height)+ for _, line := range lines {+ out = append(out, padRenderedLine(clipRenderedLine(line, width), width))+ }+ for len(out) < height {+ out = append(out, strings.Repeat(" ", width))+ }+ return strings.Join(out, "\n")+}++func truncateRenderedLine(line string, width int) string {+ if width <= 0 || lipgloss.Width(line) <= width {+ return line+ }+ return lipgloss.NewStyle().MaxWidth(width).Render(line)+}++func clipRenderedLine(line string, width int) string {+ if width <= 0 {+ return ""+ }+ line, _, _ = strings.Cut(line, "\n")+ if lipgloss.Width(line) <= width {+ return line+ }+ clipped := lipgloss.NewStyle().MaxWidth(width).Render(line)+ clipped, _, _ = strings.Cut(clipped, "\n")+ return clipped+}++func clamp(value, minValue, maxValue int) int {+ if value < minValue {+ return minValue+ }+ if value > maxValue {+ return maxValue+ }+ return value+}++func newChatEntry(entry chatEntry) chatEntry {+ if entry.version <= 0 {+ entry.version = 1+ }+ return entry+}++func newSlashEntry(content string) chatEntry {+ return newChatEntry(chatEntry{role: "slash", content: content})+}++func (m *chatModel) markEntryDirty(index int) {+ if index < 0 || index >= len(m.entries) {+ return+ }+ entry := &m.entries[index]+ entry.version+++ if entry.version <= 0 {+ entry.version = 1+ }+ entry.renderKey = chatEntryRenderKey{}+ entry.renderLines = nil+}++func entryRenderKey(entry chatEntry, width int) chatEntryRenderKey {+ return chatEntryRenderKey{width: width, version: entry.version}+}++func entriesFromMessages(messages []api.Message) []chatEntry {+ entries := make([]chatEntry, 0, len(messages))+ toolCalls := make(map[string]api.ToolCall)+ for _, msg := range messages {+ switch msg.Role {+ case "user", "system":+ if summary, ok := compactionSummaryContent(msg); ok {+ entries = append(entries, newChatEntry(chatEntry{+ role: "compaction_summary",+ content: summary,+ status: "done",+ }))+ continue+ }+ entries = append(entries, newChatEntry(chatEntry{role: msg.Role, content: msg.Content}))+ case "assistant":+ if strings.TrimSpace(msg.Thinking) != "" {+ entries = append(entries, newChatEntry(chatEntry{+ role: "thinking",+ content: msg.Thinking,+ label: "Thinking",+ status: "done",+ }))+ }+ for _, call := range msg.ToolCalls {+ if call.ID != "" {+ toolCalls[call.ID] = call+ }+ }+ if strings.TrimSpace(msg.Content) != "" {+ entries = append(entries, newChatEntry(chatEntry{role: "assistant", content: msg.Content}))+ }+ case "tool":+ if summary, ok := compactionSummaryContent(msg); ok {+ entries = append(entries, newChatEntry(chatEntry{+ role: "compaction_summary",+ content: summary,+ status: "done",+ }))+ continue+ }+ toolName := msg.ToolName+ var args map[string]any+ if call, ok := toolCalls[msg.ToolCallID]; ok {+ if toolName == "" {+ toolName = call.Function.Name+ }+ args = call.Function.Arguments.ToMap()+ }+ status := "done"+ if isDisabledToolResult(msg.Content) {+ status = "disabled"+ } else if isDeniedToolResult(msg.Content) {+ status = "denied"+ }+ entries = append(entries, newChatEntry(chatEntry{+ role: "tool",+ content: msg.Content,+ label: toolInvocationLabel(toolName, args),+ detail: toolName,+ status: status,+ toolID: msg.ToolCallID,+ args: args,+ }))+ }+ }+ return groupCompletedToolEntries(entries)+}++func compactionSummaryContent(msg api.Message) (string, bool) {+ return coreagent.CompactionSummaryContent(msg)+}++func groupCompletedToolEntries(entries []chatEntry, detected ...chatEntry) []chatEntry {+ grouped := make([]chatEntry, 0, len(entries))+ visibleToolIDs := visibleToolIDs(entries)+ for i := 0; i < len(entries); {+ if !isGroupableToolHistoryEntry(entries[i]) {+ grouped = append(grouped, entries[i])+ i+++ continue+ }++ start := i+ var tools []chatEntry+ for i < len(entries) {+ if isGroupableToolHistoryEntry(entries[i]) {+ tools = append(tools, flattenToolHistory([]chatEntry{entries[i]})...)+ i+++ continue+ }+ if isInvisibleToolGroupingBoundary(entries[i]) && nextGroupableToolHistoryIndex(entries, i+1) >= 0 {+ i+++ continue+ }+ break+ }++ summaryTools := toolSummaryEntries(tools, detected, visibleToolIDs)+ if len(summaryTools) <= 1 {+ grouped = append(grouped, flattenToolHistory(entries[start:i])...)+ continue+ }++ group := chatEntry{+ role: "tool_group",+ label: toolGroupSummary(summaryTools),+ status: aggregateToolStatus(tools),+ expanded: anyToolExpanded(tools),+ startedAt: firstToolStartedAt(tools),+ finishedAt: lastToolFinishedAt(tools),+ tools: tools,+ }+ if group.status == "error" {+ group.err = "one or more tool calls failed"+ }+ grouped = append(grouped, newChatEntry(group))+ }+ return grouped+}++func isInvisibleToolGroupingBoundary(entry chatEntry) bool {+ switch entry.role {+ case "assistant":+ return strings.TrimSpace(entry.content) == "" &&+ strings.TrimSpace(entry.label) == "" &&+ strings.TrimSpace(entry.detail) == "" &&+ entry.metrics == nil+ case "thinking":+ return !entry.expanded+ default:+ return false+ }+}++func nextGroupableToolHistoryIndex(entries []chatEntry, index int) int {+ for index < len(entries) && isInvisibleToolGroupingBoundary(entries[index]) {+ index+++ }+ if index < len(entries) && isGroupableToolHistoryEntry(entries[index]) {+ return index+ }+ return -1+}++func anyToolExpanded(tools []chatEntry) bool {+ for _, tool := range tools {+ if tool.expanded {+ return true+ }+ }+ return false+}++func isGroupableToolHistoryEntry(entry chatEntry) bool {+ return (entry.role == "tool" && isToolResultStatus(entry.status)) ||+ (entry.role == "tool_group" && len(entry.tools) > 0)+}++func visibleToolIDs(entries []chatEntry) map[string]struct{} {+ ids := map[string]struct{}{}+ for _, tool := range flattenToolHistory(entries) {+ if tool.toolID != "" {+ ids[tool.toolID] = struct{}{}+ }+ }+ return ids+}++func toolSummaryEntries(tools []chatEntry, detected []chatEntry, visible map[string]struct{}) []chatEntry {+ if len(detected) == 0 {+ return tools+ }+ seen := make(map[string]struct{}, len(visible)+len(tools))+ for id := range visible {+ seen[id] = struct{}{}+ }+ summary := slices.Clone(tools)+ for _, tool := range detected {+ if tool.toolID != "" {+ if _, ok := seen[tool.toolID]; ok {+ continue+ }+ seen[tool.toolID] = struct{}{}+ }+ summary = append(summary, tool)+ }+ return summary+}++func entryHasActiveTool(entry chatEntry) bool {+ switch entry.role {+ case "tool":+ return isToolActiveStatus(entry.status)+ case "tool_group":+ for _, tool := range entry.tools {+ if isToolActiveStatus(tool.status) {+ return true+ }+ }+ }+ return false+}++func flattenToolHistory(entries []chatEntry) []chatEntry {+ var tools []chatEntry+ for _, entry := range entries {+ switch entry.role {+ case "tool":+ tools = append(tools, entry)+ case "tool_group":+ tools = append(tools, entry.tools...)+ }+ }+ return tools+}++func aggregateToolStatus(tools []chatEntry) string {+ denied := false+ active := false+ for _, tool := range tools {+ if tool.err != "" || tool.status == "error" {+ return "error"+ }+ if tool.status == "denied" {+ denied = true+ }+ if isToolActiveStatus(tool.status) {+ active = true+ }+ }+ if denied {+ return "denied"+ }+ if active {+ return "running"+ }+ return "done"+}++func firstToolStartedAt(tools []chatEntry) time.Time {+ for _, tool := range tools {+ if !tool.startedAt.IsZero() {+ return tool.startedAt+ }+ }+ return time.Time{}+}++func lastToolFinishedAt(tools []chatEntry) time.Time {+ for i := len(tools) - 1; i >= 0; i-- {+ if !tools[i].finishedAt.IsZero() {+ return tools[i].finishedAt+ }+ }+ return time.Time{}+}++func indentLines(lines []string, prefix string) []string {+ if len(lines) == 0 {+ return nil+ }+ out := make([]string, len(lines))+ for i, line := range lines {+ if line == "" {+ out[i] = prefix+ } else {+ out[i] = prefix + line+ }+ }+ return out+}++func wrapChatText(text string, width int) []string {+ if width < 20 {+ width = 20+ }+ var out []string+ for _, rawLine := range strings.Split(text, "\n") {+ line := strings.TrimRight(rawLine, "\r")+ for runewidth.StringWidth(line) > width {+ cut := chatDisplayWidthCut(line, width)+ out = append(out, strings.TrimSpace(line[:cut]))+ line = strings.TrimSpace(line[cut:])+ }+ out = append(out, line)+ }+ if len(out) == 0 {+ return []string{""}+ }+ return out+}++func chatDisplayWidthCut(line string, width int) int {+ hardCut := 0+ currentWidth := 0+ spaceCut := 0+ spaceWidth := 0+ for i := 0; i < len(line); {+ r, size := utf8.DecodeRuneInString(line[i:])+ nextWidth := currentWidth + runewidth.RuneWidth(r)+ if nextWidth > width {+ break+ }+ currentWidth = nextWidth+ hardCut = i + size+ if (r == ' ' || r == '\t') && currentWidth > width/2 {+ spaceCut = i+ spaceWidth = currentWidth+ }+ i += size+ }+ if spaceCut > 0 && spaceWidth > 0 {+ return spaceCut+ }+ if hardCut > 0 {+ return hardCut+ }+ _, size := utf8.DecodeRuneInString(line)+ return size+}diff --git a/cmd/tui/chat/render_test.go b/cmd/tui/chat/render_test.gonew file mode 100644index 000000000..5dc558593--- /dev/null+++ b/cmd/tui/chat/render_test.go@@ -0,0 +1,1964 @@+package chat++import (+ "context"+ "fmt"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ tea "github.com/charmbracelet/bubbletea"+ "github.com/charmbracelet/lipgloss"++ coreagent "github.com/ollama/ollama/agent"+ "github.com/ollama/ollama/api"+)++func TestChatAssistantEntryHasNoLabel(t *testing.T) {+ m := chatModel{}++ prefix, _ := m.renderEntry(chatEntry{role: "assistant", content: "hello"})++ if strings.Contains(prefix, "Ollama:") {+ t.Fatalf("prefix should not include Ollama label: %q", prefix)+ }+ if prefix != "" {+ t.Fatalf("prefix = %q, want empty", prefix)+ }+}++func TestChatViewRendersEmptyPromptHint(t *testing.T) {+ m := chatModel{+ chatID: "chat-a",+ width: 80,+ height: 12,+ }++ view := stripANSI(m.View())+ lines := strings.Split(view, "\n")+ hintLine := lineIndexContaining(lines, "what changed on this branch?")+ if hintLine < 0 {+ t.Fatalf("empty chat view missing prompt hint: %q", view)+ }+ if strings.Contains(view, "Start a conversation. Use /help for commands.") {+ t.Fatalf("empty chat view should use rotating prompt hint: %q", view)+ }+}++func TestChatUserEntryHasNoLabel(t *testing.T) {+ m := chatModel{entries: []chatEntry{{role: "user", content: "hello"}}}++ prefix, body := m.renderEntry(m.entries[0])++ if prefix != "" {+ t.Fatalf("prefix = %q, want empty", prefix)+ }+ if body != "hello" {+ t.Fatalf("body = %q, want hello", body)+ }++ transcript := stripANSI(m.renderTranscript(80))+ if !strings.Contains(transcript, " hello") {+ t.Fatalf("user transcript should render as user block: %q", transcript)+ }+}++func TestChatSystemEntryHasNoLabel(t *testing.T) {+ m := chatModel{entries: []chatEntry{{role: "system", content: "Available tools"}}}++ prefix, body := m.renderEntry(m.entries[0])++ if prefix != "" {+ t.Fatalf("prefix = %q, want empty", prefix)+ }+ if body != "Available tools" {+ t.Fatalf("body = %q, want Available tools", body)+ }+ if transcript := stripANSI(m.renderTranscript(80)); strings.Contains(transcript, "sys ") {+ t.Fatalf("system transcript should not render sys prefix: %q", transcript)+ }+}++func TestChatMixedToolGroupUsesMixedPrefix(t *testing.T) {+ m := chatModel{}+ entry := newChatEntry(chatEntry{+ role: "tool_group",+ label: "Tool calls (2)",+ status: "error",+ tools: []chatEntry{+ newChatEntry(chatEntry{role: "tool", status: "done"}),+ newChatEntry(chatEntry{role: "tool", status: "error", err: "failed"}),+ },+ })++ prefix, body := m.renderEntry(entry)++ if prefix != chatToolMixedStyle.Render("•")+" " {+ t.Fatalf("prefix = %q, want mixed-styled bullet", prefix)+ }+ body = stripANSI(body)+ if strings.Contains(body, "failed") || strings.Contains(body, "succeeded") || strings.Contains(body, "done") {+ t.Fatalf("body = %q, should not show status words for mixed group", body)+ }+}++func TestChatToolStatusLineDoesNotUseDisclosureGlyph(t *testing.T) {+ startedAt := time.Date(2026, 6, 22, 13, 0, 0, 0, time.UTC)+ entry := newChatEntry(chatEntry{+ role: "tool",+ label: `Web Search("who is parth sareen")`,+ status: "done",+ content: "hidden result",+ startedAt: startedAt,+ finishedAt: startedAt.Add(812 * time.Millisecond),+ })++ line := stripANSI(toolStatusLine(entry))+ if strings.Contains(line, "▸") || strings.Contains(line, "▾") {+ t.Fatalf("tool status line should not include disclosure glyph: %q", line)+ }+ if line != `Web Search("who is parth sareen")` {+ t.Fatalf("tool status line = %q, want label only", line)+ }+ for _, word := range []string{"done", "in 812ms", "812ms"} {+ if strings.Contains(line, word) {+ t.Fatalf("tool status line should not include %q: %q", word, line)+ }+ }+}++func TestChatCompletedToolStatusLineUsesResultStyle(t *testing.T) {+ entry := newChatEntry(chatEntry{+ role: "tool",+ detail: "bash",+ label: `Bash("pwd")`,+ status: "done",+ })++ if line := toolStatusLine(entry); line != `Bash("pwd")` {+ t.Fatalf("tool status line = %q, want command label", line)+ }+ prefix, _ := (chatModel{}).renderEntry(entry)+ if prefix != chatToolDoneStyle.Render("•")+" " {+ t.Fatalf("tool prefix = %q, want done-styled marker", prefix)+ }+}++func TestChatToolStatusMarkerUsesStateColors(t *testing.T) {+ if got, want := chatToolRunningStyle.GetForeground(), lipgloss.Color(chatAnsiYellow); got != want {+ t.Fatalf("running tool foreground = %v, want %v", got, want)+ }+ if got, want := chatToolDoneStyle.GetForeground(), lipgloss.Color(chatAnsiGreen); got != want {+ t.Fatalf("done tool foreground = %v, want %v", got, want)+ }++ running := newChatEntry(chatEntry{+ role: "tool",+ detail: "bash",+ label: `Bash("pwd")`,+ status: "running",+ })+ if line := toolStatusLine(running); line != `Bash("pwd")` {+ t.Fatalf("running tool status line = %q, want command label", line)+ }+ prefix, _ := (chatModel{}).renderEntry(running)+ if prefix != chatToolRunningStyle.Render("•")+" " {+ t.Fatalf("running tool prefix = %q, want running-styled marker", prefix)+ }++ child := newChatEntry(chatEntry{+ role: "tool",+ detail: "bash",+ label: `Bash("pwd")`,+ status: "done",+ })+ if line := toolGroupChildStatusLine(child); line != boldToolInvocationName(`Bash("pwd")`) {+ t.Fatalf("tool group child line = %q, want neutral invocation", line)+ }+}++func TestChatViewRendersInputBox(t *testing.T) {+ m := chatModel{+ input: []rune("hello"),+ width: 40,+ height: 12,+ }++ view := stripANSI(m.View())+ if !strings.Contains(view, inputBoxTopBorderLine(40)) || !strings.Contains(view, inputBoxBottomBorderLine(40)) {+ t.Fatalf("prompt input should render box borders: %q", view)+ }+ if !strings.Contains(view, "│ hello") {+ t.Fatalf("view missing prompt input row: %q", view)+ }+}++func TestChatViewRendersSentUserPromptWithoutPrefix(t *testing.T) {+ m := chatModel{+ width: 40,+ height: 12,+ entries: []chatEntry{+ {role: "user", content: "hello"},+ },+ }++ view := stripANSI(m.View())+ if !strings.Contains(view, "hello") {+ t.Fatalf("submitted user message should render: %q", view)+ }+ if strings.Contains(view, "> hello") {+ t.Fatalf("submitted user message should not include prompt prefix: %q", view)+ }+ if strings.Contains(view, "│ >") {+ t.Fatalf("active input should not include prompt prefix: %q", view)+ }+}++func TestChatFlowViewStartsAtInputWhenEmpty(t *testing.T) {+ m := chatModel{+ input: []rune("hello"),+ width: 40,+ }++ lines := strings.Split(stripANSI(m.View()), "\n")+ if len(lines) == 0 || !strings.Contains(lines[0], inputBoxTopBorderLine(40)) {+ t.Fatalf("empty flow view should start at input box:\n%s", strings.Join(lines, "\n"))+ }+}++func TestFlowTranscriptChangedPrefixStartDetectsToolGrouping(t *testing.T) {+ firstArgs := map[string]any{"command": "pwd"}+ secondArgs := map[string]any{"command": "ls"}+ beforeModel := chatModel{+ width: 120,+ entries: []chatEntry{+ {+ role: "tool",+ label: `Bash("pwd")`,+ detail: "bash",+ status: "done",+ toolID: "call-1",+ args: firstArgs,+ },+ },+ }+ before := beforeModel.transcriptLines(120)++ afterModel := beforeModel+ afterModel.entries = groupCompletedToolEntries([]chatEntry{+ beforeModel.entries[0],+ {+ role: "tool",+ label: `Bash("ls")`,+ detail: "bash",+ status: "done",+ toolID: "call-2",+ args: secondArgs,+ },+ })++ after := afterModel.transcriptLines(120)+ if start := flowTranscriptChangedPrefixStart(before, after, len(before)); start != 0 {+ t.Fatalf("changed prefix start = %d, want 0; before=%q after=%q", start, before, after)+ }+ sequence := flowTranscriptRewriteSequence(len(before), after)+ if !strings.HasPrefix(sequence, "\x1b[1A\r\x1b[J") {+ t.Fatalf("rewrite sequence = %q, want cursor-up clear-below prefix", sequence)+ }+ if !strings.Contains(sequence, "Ran 2 commands") {+ t.Fatalf("grouping should invalidate already printed tool row; before=%q after=%q", before, afterModel.transcriptLines(120))+ }+}++func TestFlowTranscriptChangedPrefixStartIgnoresAppendedLines(t *testing.T) {+ beforeModel := chatModel{+ width: 120,+ entries: []chatEntry{+ {role: "assistant", content: "hello"},+ },+ }+ before := beforeModel.transcriptLines(120)+ afterModel := beforeModel+ afterModel.entries = append(afterModel.entries, chatEntry{role: "assistant", content: "world"})++ if start := flowTranscriptChangedPrefixStart(before, afterModel.transcriptLines(120), len(before)); start >= 0 {+ t.Fatalf("appended transcript lines should not invalidate already printed prefix")+ }+}++func TestChatViewRendersCursorWithEmptyPlaceholder(t *testing.T) {+ m := chatModel{+ chatID: "placeholder-chat",+ width: 80,+ height: 12,+ }++ view := stripANSI(m.View())+ if !strings.Contains(view, "summarize this file and suggest edits") {+ t.Fatalf("empty placeholder should show hint: %q", view)+ }+}++func TestChatViewRendersModelUnderInputBox(t *testing.T) {+ m := chatModel{+ input: []rune("hello"),+ width: 48,+ height: 12,+ opts: Options{+ Model: "kimi-k2.7-code:cloud",+ },+ }++ lines := strings.Split(stripANSI(m.View()), "\n")+ inputLine := lineIndexContaining(lines, "│ hello")+ modelLine := lineIndexContaining(lines, "kimi-k2.7-code:cloud")+ if inputLine < 0 || modelLine < 0 {+ t.Fatalf("view missing input or model line:\n%s", strings.Join(lines, "\n"))+ }+ if modelLine != inputLine+2 {+ t.Fatalf("model line should sit directly under input: input=%d model=%d\n%s", inputLine, modelLine, strings.Join(lines, "\n"))+ }+ if strings.Contains(lines[modelLine], "model ") {+ t.Fatalf("model line should not include a label:\n%s", strings.Join(lines, "\n"))+ }+}++func TestChatViewExpandsInputBoxForLongPrompt(t *testing.T) {+ m := chatModel{+ input: []rune(strings.Repeat("long prompt ", 8)),+ width: 32,+ height: 14,+ }++ view := stripANSI(m.View())+ if got := inputPromptLineCount(t, view); got < 2 {+ t.Fatalf("input body lines = %d, want wrapped prompt:\n%s", got, view)+ }+ if !strings.Contains(view, "█") {+ t.Fatalf("view missing cursor: %q", view)+ }+}++func TestChatViewCapsTallInputBox(t *testing.T) {+ m := chatModel{+ input: []rune(strings.Repeat("pasted text ", 80)),+ width: 32,+ height: 12,+ }++ view := stripANSI(m.View())+ if got := inputPromptLineCount(t, view); got > maxInputBoxBodyLines {+ t.Fatalf("input body lines = %d, want <= %d:\n%s", got, maxInputBoxBodyLines, view)+ }+ if strings.Contains(view, "... ... ") {+ t.Fatalf("truncated pasted prompt should not duplicate omission markers:\n%s", view)+ }+}++func TestChatViewWrapsNotificationWhenNarrow(t *testing.T) {+ m := chatModel{+ input: []rune("hello"),+ width: 28,+ height: 14,+ status: "cache will break by turning system prompt off",+ approvalState: testApprovalState(true, nil),+ opts: Options{+ ContextWindowTokens: 262144,+ },+ contextTokens: 12345,+ contextEstimate: true,+ }++ view := stripANSI(m.View())+ for _, want := range []string{+ "cache will break by",+ "system prompt off",+ } {+ if !strings.Contains(view, want) {+ t.Fatalf("wrapped notification missing %q:\n%s", want, view)+ }+ }+ for _, hidden := range []string{"enter", "send", "/model", "full", "access"} {+ if strings.Contains(view, hidden) {+ t.Fatalf("view should not render footer chrome %q:\n%s", hidden, view)+ }+ }+ if strings.Contains(view, "ctx") {+ t.Fatalf("view should hide distant context pressure:\n%s", view)+ }+ if strings.Contains(view, "ctrl+g") {+ t.Fatalf("view should not include ctrl+g hint:\n%s", view)+ }+ for _, line := range strings.Split(view, "\n") {+ if len([]rune(line)) > 28 {+ t.Fatalf("line width = %d, want <= 28: %q\n%s", len([]rune(line)), line, view)+ }+ }+}++func TestPromptTokenTextDoesNotUseCompactionFallback(t *testing.T) {+ m := chatModel{}+ if got := m.promptTokenText(702); got != "702 tokens" {+ t.Fatalf("promptTokenText without model context = %q, want bare token count", got)+ }++ m.opts.ContextWindowTokens = 262144+ if got := m.promptTokenText(702); got != "702 / 256k tokens" {+ t.Fatalf("promptTokenText with model context = %q", got)+ }++ m.opts.Options = map[string]any{"num_ctx": 131072}+ if got := m.promptTokenText(702); got != "702 / 128k tokens" {+ t.Fatalf("promptTokenText with num_ctx = %q", got)+ }++ m.opts.Options = map[string]any{"num_ctx": 1000000}+ if got := m.promptTokenText(702); got != "702 / 1M tokens" {+ t.Fatalf("promptTokenText with large num_ctx = %q", got)+ }++ m.opts.Options = map[string]any{"num_ctx": 99999}+ if got := m.promptTokenText(702); got != "702 / 99999 tokens" {+ t.Fatalf("promptTokenText below compact threshold = %q", got)+ }+}++func TestPreloadDoneUpdatesContextWindowTokens(t *testing.T) {+ compactor := &coreagent.SimpleCompactor{}+ m := chatModel{+ preloadingModel: "ornith",+ opts: Options{+ ContextWindowTokens: 32768,+ Compactor: compactor,+ },+ }++ next, _ := m.Update(chatModelPreloadDoneMsg{model: "ornith", contextWindowTokens: 262144})+ got := next.(chatModel)+ if got.opts.ContextWindowTokens != 262144 {+ t.Fatalf("context window = %d, want 262144", got.opts.ContextWindowTokens)+ }+ if compactor.Options.ContextWindowTokens != 262144 {+ t.Fatalf("compactor context window = %d, want 262144", compactor.Options.ContextWindowTokens)+ }+}++func TestChatViewRendersNotificationAboveInput(t *testing.T) {+ m := chatModel{+ input: []rune("hello"),+ width: 40,+ height: 12,+ status: "copied latest output",+ }++ view := stripANSI(m.View())+ lines := strings.Split(view, "\n")+ borderLine := lineIndexContaining(lines, inputBoxTopBorderLine(40))+ if borderLine < 0 {+ t.Fatalf("view missing input box:\n%s", view)+ }+ if borderLine < 1 || !strings.Contains(lines[borderLine-1], "copied latest output") {+ t.Fatalf("notification should sit directly above input box:\n%s", view)+ }+}++func TestChatNotificationsUseSecondaryStyle(t *testing.T) {+ if !chatNotificationStyle.GetFaint() {+ t.Fatal("notification style should use secondary/faint styling")+ }+}++func TestChatSubmittedPromptUsesThemeSecondaryGrey(t *testing.T) {+ if got, want := chatUserBlockStyle.GetForeground(), lipgloss.TerminalColor(lipgloss.AdaptiveColor{Light: "#777777", Dark: "#8a8a8a"}); got != want {+ t.Fatalf("submitted prompt foreground = %v, want %v", got, want)+ }+ if chatUserBlockStyle.GetFaint() {+ t.Fatal("submitted prompt should use secondary grey, not faint styling")+ }+}++func TestChatToolOutputUsesDistinctSecondaryGrey(t *testing.T) {+ if got, want := chatToolOutputStyle.GetForeground(), lipgloss.TerminalColor(lipgloss.AdaptiveColor{Light: "#666666", Dark: "#a0a0a0"}); got != want {+ t.Fatalf("tool output foreground = %v, want %v", got, want)+ }+}++func TestChatInlineCodeDoesNotLookSelected(t *testing.T) {+ if chatInlineCodeStyle.GetReverse() {+ t.Fatal("inline code should not use reverse-video styling")+ }+ if !chatInlineCodeStyle.GetBold() {+ t.Fatal("inline code should still have lightweight emphasis")+ }+}++func inputPromptLineCount(t *testing.T, view string) int {+ t.Helper()+ count := 0+ inInputBox := false+ for _, line := range strings.Split(view, "\n") {+ trimmed := strings.TrimSpace(line)+ if strings.HasPrefix(trimmed, "╭") {+ inInputBox = true+ continue+ }+ if strings.HasPrefix(trimmed, "╰") {+ inInputBox = false+ continue+ }+ if inInputBox && strings.Contains(trimmed, "│") {+ count+++ }+ }+ if count == 0 {+ t.Fatalf("input prompt lines not found:\n%s", view)+ }+ return count+}++func TestChatViewKeepsInputBoxWhileRunning(t *testing.T) {+ m := chatModel{+ input: []rune("next"),+ running: true,+ thinking: true,+ thinkingTokens: 42,+ width: 40,+ height: 12,+ }++ view := stripANSI(m.View())+ if !strings.Contains(view, "│ next") {+ t.Fatalf("running view should keep input row: %q", view)+ }+ if strings.Contains(view, "↑/↓ scroll") || strings.Contains(view, "/new chat") || strings.Contains(view, "/clear reset") {+ t.Fatalf("footer should not include scroll/new/clear hints: %q", view)+ }+ lines := strings.Split(view, "\n")+ borderLine := lineIndexContaining(lines, inputBoxTopBorderLine(40))+ if borderLine < 0 {+ t.Fatalf("view missing input box: %q", view)+ }+ if borderLine < 1 || !strings.Contains(lines[borderLine-1], "Thinking ↓ 42 tokens") {+ t.Fatalf("thinking line should sit directly above input box:\n%s", view)+ }+ if strings.Contains(lines[borderLine-1], "...") {+ t.Fatalf("thinking line should not show spinner dots:\n%s", view)+ }+}++func TestChatToolFinishedUpdatesLiveWorkingDirOnly(t *testing.T) {+ root := t.TempDir()+ subdir := filepath.Join(root, "sub")+ if err := os.Mkdir(subdir, 0o755); err != nil {+ t.Fatal(err)+ }+ m := chatModel{+ width: 140,+ height: 12,+ opts: Options{+ RootDir: root,+ WorkingDir: root,+ },+ workingDir: root,+ }++ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolFinished,+ ToolCallID: "call-1",+ ToolName: "bash",+ WorkingDir: subdir,+ })++ if m.workingDir != subdir {+ t.Fatalf("workingDir = %q, want %q", m.workingDir, subdir)+ }+ if m.opts.WorkingDir != root {+ t.Fatalf("opts.WorkingDir mutated to %q, want %q", m.opts.WorkingDir, root)+ }+}++func TestChatBoundedFramePinsInputAfterResize(t *testing.T) {+ m := chatModel{+ input: []rune("next"),+ width: 60,+ height: 14,+ }+ for i := range 20 {+ m.entries = append(m.entries, chatEntry{role: "assistant", content: fmt.Sprintf("line %02d", i)})+ }+ inputLine := renderedInputLine(m.View())+ if inputLine < m.height-4 {+ t.Fatalf("bounded frame should pin input near bottom, input line=%d height=%d\n%s", inputLine, m.height, stripANSI(m.View()))+ }+}++func TestChatViewSeparatesActionStatusFromTranscript(t *testing.T) {+ m := chatModel{+ input: []rune("next"),+ width: 72,+ height: 14,+ running: true,+ thinking: true,+ entries: []chatEntry{+ {role: "assistant", content: "Working through it."},+ },+ }++ lines := strings.Split(stripANSI(m.View()), "\n")+ assistantLine := lineIndexContaining(lines, "Working through it.")+ activityLine := lineIndexContaining(lines, "Thinking")+ if assistantLine < 0 || activityLine < 0 {+ t.Fatalf("view missing assistant/activity lines:\n%s", strings.Join(lines, "\n"))+ }+ if gap := activityLine - assistantLine - 1; gap < 1 {+ t.Fatalf("gap between transcript and action status = %d, want at least 1:\n%s", gap, strings.Join(lines, "\n"))+ }+}++func TestChatViewDoesNotReserveIdleActionSpacerAfterResponse(t *testing.T) {+ m := chatModel{+ input: []rune("next"),+ width: 72,+ height: 12,+ entries: []chatEntry{+ {role: "user", content: "hi"},+ {role: "assistant", content: "Hello."},+ },+ }++ lines := strings.Split(stripANSI(m.View()), "\n")+ assistantLine := lineIndexContaining(lines, "Hello.")+ inputLine := lineIndexContaining(lines, "│ next")+ if assistantLine < 0 || inputLine < 0 {+ t.Fatalf("view missing assistant/input lines:\n%s", strings.Join(lines, "\n"))+ }+ if gap := inputLine - assistantLine - 1; gap < 2 {+ t.Fatalf("gap between finished response and input body = %d, want at least 2:\n%s", gap, strings.Join(lines, "\n"))+ }+}++func TestChatViewHidesEmptyHintWhileTyping(t *testing.T) {+ m := chatModel{+ input: []rune("next"),+ width: 72,+ height: 12,+ }++ lines := strings.Split(stripANSI(m.View()), "\n")+ hintLine := lineIndexContaining(lines, "Try:")+ inputLine := lineIndexContaining(lines, "│ next")+ if hintLine >= 0 {+ t.Fatalf("view should not show empty hint while typing:\n%s", strings.Join(lines, "\n"))+ }+ if inputLine < 0 {+ t.Fatalf("view missing input line:\n%s", strings.Join(lines, "\n"))+ }+}++func renderedInputLine(view string) int {+ for i, line := range strings.Split(stripANSI(view), "\n") {+ if strings.Contains(line, "│ next") {+ return i+ }+ }+ return -1+}++func lineIndexContaining(lines []string, needle string) int {+ for i, line := range lines {+ if strings.Contains(line, needle) {+ return i+ }+ }+ return -1+}++func TestChatScrollsTranscript(t *testing.T) {+ m := chatModel{+ width: 80,+ height: 10,+ }+ for range 12 {+ m.entries = append(m.entries, chatEntry{role: "user", content: "line"})+ }++ if m.maxScroll() == 0 {+ t.Fatal("test setup should produce scrollable transcript")+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyPgUp})+ m = updated.(chatModel)+ if m.scroll == 0 {+ t.Fatal("page up should scroll transcript")+ }++ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyPgDown})+ m = updated.(chatModel)+ if m.scroll != 0 {+ t.Fatalf("scroll = %d, want 0", m.scroll)+ }++ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyCtrlHome})+ m = updated.(chatModel)+ if m.scroll != m.maxScroll() {+ t.Fatalf("scroll = %d, want max %d", m.scroll, m.maxScroll())+ }++ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyCtrlEnd})+ m = updated.(chatModel)+ if m.scroll != 0 {+ t.Fatalf("scroll = %d, want 0", m.scroll)+ }+}++func TestChatStreamingAssistantOutputHoldsLiveMarkdown(t *testing.T) {+ m := chatModel{+ width: 80,+ height: 12,+ running: true,+ events: make(chan tea.Msg),+ }++ updated, _ := m.Update(chatAgentMsg{event: coreagent.Event{Type: coreagent.EventMessageDelta, Content: "generated line 00"}})+ m = updated.(chatModel)+ if !strings.Contains(stripANSI(m.View()), "generated line 00") {+ t.Fatalf("live output should be visible in flow view:\n%s", stripANSI(m.View()))+ }++ updated, _ = m.Update(chatAgentMsg{event: coreagent.Event{Type: coreagent.EventMessageDelta, Content: "\n\ngenerated line 01"}})+ m = updated.(chatModel)+ view := stripANSI(m.View())+ if !strings.Contains(view, "generated line 00") {+ t.Fatalf("live assistant output should remain visible while streaming:\n%s", view)+ }+ if !strings.Contains(view, "generated line 01") {+ t.Fatalf("latest generated line should remain visible:\n%s", view)+ }+}++func TestChatMouseWheelScrollsTranscriptWhileRunning(t *testing.T) {+ m := chatModel{+ width: 80,+ height: 10,+ running: true,+ input: []rune("current draft"),+ promptHistory: []string{"previous one", "previous two"},+ }+ for range 12 {+ m.entries = append(m.entries, chatEntry{role: "user", content: "line"})+ }+ if m.maxScroll() == 0 {+ t.Fatal("test setup should produce scrollable transcript")+ }++ updated, _ := m.Update(tea.MouseMsg{Type: tea.MouseWheelUp})+ m = updated.(chatModel)+ if m.scroll == 0 {+ t.Fatal("mouse wheel up should scroll transcript while running")+ }+ if got := string(m.input); got != "current draft" {+ t.Fatalf("mouse wheel should not navigate prompt history, input = %q", got)+ }++ updated, _ = m.Update(tea.MouseMsg{Type: tea.MouseWheelDown})+ m = updated.(chatModel)+ if m.scroll != 0 {+ t.Fatalf("mouse wheel down should return to bottom, got scroll %d", m.scroll)+ }+ if got := string(m.input); got != "current draft" {+ t.Fatalf("mouse wheel should leave draft alone, input = %q", got)+ }+}++func TestChatWindowsMouseWheelScrollsTranscript(t *testing.T) {+ oldGOOS := chatRuntimeGOOS+ chatRuntimeGOOS = "windows"+ defer func() {+ chatRuntimeGOOS = oldGOOS+ }()++ m := chatModel{+ width: 80,+ height: 8,+ }+ for i := range 20 {+ m.entries = append(m.entries, chatEntry{role: "user", content: fmt.Sprintf("line-%02d", i)})+ }++ updated, _ := m.Update(tea.MouseMsg{Type: tea.MouseWheelUp})+ m = updated.(chatModel)+ if m.scroll == 0 {+ t.Fatal("windows mouse wheel up should scroll transcript")+ }++ updated, _ = m.Update(tea.MouseMsg{Type: tea.MouseWheelDown})+ m = updated.(chatModel)+ if m.scroll != 0 {+ t.Fatalf("windows mouse wheel down should return to bottom, got scroll %d", m.scroll)+ }+}++func TestChatMouseDragSelectsTranscriptWithoutAutoCopy(t *testing.T) {+ oldGOOS := chatRuntimeGOOS+ chatRuntimeGOOS = "darwin"+ defer func() {+ chatRuntimeGOOS = oldGOOS+ }()++ m := chatModel{+ width: 80,+ height: 10,+ entries: []chatEntry{+ {role: "user", content: "alpha beta"},+ },+ }+ top, _ := m.transcriptLayout()++ updated, _ := m.Update(tea.MouseMsg{Type: tea.MouseLeft, Button: tea.MouseButtonLeft, Action: tea.MouseActionPress, X: 2, Y: top})+ m = updated.(chatModel)+ updated, _ = m.Update(tea.MouseMsg{Type: tea.MouseLeft, Button: tea.MouseButtonLeft, Action: tea.MouseActionMotion, X: 7, Y: top})+ m = updated.(chatModel)+ if got := m.selectedTranscriptText(80); got != "alpha" {+ t.Fatalf("selected text = %q, want alpha", got)+ }+ if !m.selection.active {+ t.Fatal("selection should stay active during drag")+ }+ if !m.selection.dragging {+ t.Fatal("selection should track drag before release")+ }++ updated, cmd := m.Update(tea.MouseMsg{Type: tea.MouseRelease, Action: tea.MouseActionRelease, X: 7, Y: top})+ m = updated.(chatModel)+ if cmd != nil {+ t.Fatal("mouse release should not auto-copy selected text")+ }+ if !m.selection.active {+ t.Fatal("selection should stay visible on release")+ }+ if m.selection.dragging {+ t.Fatal("selection should stop tracking drag on release")+ }+ if got := m.selectedTranscriptText(80); got != "alpha" {+ t.Fatalf("selected text after release = %q, want alpha", got)+ }+}++func TestChatWindowsMouseDragCopiesAndClearsTranscriptSelection(t *testing.T) {+ oldGOOS := chatRuntimeGOOS+ chatRuntimeGOOS = "windows"+ defer func() {+ chatRuntimeGOOS = oldGOOS+ }()++ var copied string+ oldClipboard := writeClipboard+ writeClipboard = func(_ context.Context, text string) error {+ copied = text+ return nil+ }+ defer func() {+ writeClipboard = oldClipboard+ }()++ m := chatModel{+ width: 80,+ height: 10,+ entries: []chatEntry{+ {role: "user", content: "alpha beta"},+ },+ }+ top, _ := m.transcriptLayout()++ updated, _ := m.Update(tea.MouseMsg{Type: tea.MouseLeft, Button: tea.MouseButtonLeft, Action: tea.MouseActionPress, X: 2, Y: top})+ m = updated.(chatModel)+ updated, _ = m.Update(tea.MouseMsg{Type: tea.MouseLeft, Button: tea.MouseButtonLeft, Action: tea.MouseActionMotion, X: 7, Y: top})+ m = updated.(chatModel)+ if got := m.selectedTranscriptText(80); got != "alpha" {+ t.Fatalf("selected text = %q, want alpha", got)+ }++ updated, cmd := m.Update(tea.MouseMsg{Type: tea.MouseRelease, Action: tea.MouseActionRelease, X: 7, Y: top})+ m = updated.(chatModel)+ if cmd == nil {+ t.Fatal("mouse release should copy selected text on windows")+ }+ if msg := cmd(); msg != nil {+ t.Fatalf("clipboard command message = %#v, want nil", msg)+ }+ if copied != "alpha" {+ t.Fatalf("copied text = %q, want alpha", copied)+ }+ if m.selection.active {+ t.Fatal("windows selection should clear after copy")+ }+ if m.status != "copied" {+ t.Fatalf("status = %q, want copied", m.status)+ }+}++func TestChatMouseDragSelectionUsesDisplayColumns(t *testing.T) {+ m := chatModel{+ width: 80,+ height: 10,+ entries: []chatEntry{+ {role: "user", content: "a界b"},+ },+ }+ top, _ := m.transcriptLayout()+ contentX := 2++ updated, _ := m.Update(tea.MouseMsg{Type: tea.MouseLeft, Button: tea.MouseButtonLeft, Action: tea.MouseActionPress, X: contentX, Y: top})+ m = updated.(chatModel)+ updated, _ = m.Update(tea.MouseMsg{Type: tea.MouseLeft, Button: tea.MouseButtonLeft, Action: tea.MouseActionMotion, X: contentX + 3, Y: top})+ m = updated.(chatModel)++ if got := m.selectedTranscriptText(80); got != "a界" {+ t.Fatalf("selected text = %q, want a界", got)+ }+}++func TestChatBoundedViewDoesNotRenderScrollHeader(t *testing.T) {+ m := chatModel{+ width: 80,+ height: 6,+ }+ for i := range 12 {+ m.entries = append(m.entries, chatEntry{role: "user", content: fmt.Sprintf("line-%02d", i)})+ }+ m.scroll = m.maxScroll()+ top, _ := m.transcriptLayout()+ lines := strings.Split(stripANSI(m.View()), "\n")+ if top != 0 {+ t.Fatalf("transcript top = %d, want no status header", top)+ }+ if strings.Contains(lines[0], "more") {+ t.Fatalf("view should not render scroll status header: %q", lines[0])+ }+ if strings.TrimSpace(lines[top]) == "" {+ t.Fatalf("transcript should start at layout top %d, line=%q view=%q", top, lines[top], strings.Join(lines, "\n"))+ }+}++func TestChatMouseDragSelectionUsesScrolledTranscriptCoordinates(t *testing.T) {+ oldGOOS := chatRuntimeGOOS+ chatRuntimeGOOS = "darwin"+ defer func() {+ chatRuntimeGOOS = oldGOOS+ }()++ m := chatModel{+ width: 80,+ height: 8,+ }+ for i := range 10 {+ m.entries = append(m.entries, chatEntry{role: "user", content: fmt.Sprintf("line-%02d", i)})+ }+ m.scroll = m.maxScroll()+ top, _ := m.transcriptLayout()++ updated, _ := m.Update(tea.MouseMsg{Type: tea.MouseLeft, Button: tea.MouseButtonLeft, Action: tea.MouseActionPress, X: 2, Y: top})+ m = updated.(chatModel)+ updated, _ = m.Update(tea.MouseMsg{Type: tea.MouseMotion, Button: tea.MouseButtonLeft, Action: tea.MouseActionMotion, X: 9, Y: top})+ m = updated.(chatModel)+ if got := m.selectedTranscriptText(80); got != "line-00" {+ t.Fatalf("selected text = %q, want line-00", got)+ }+ updated, cmd := m.Update(tea.MouseMsg{Type: tea.MouseRelease, Action: tea.MouseActionRelease, X: 9, Y: top})+ m = updated.(chatModel)+ if cmd != nil {+ t.Fatal("mouse release should not auto-copy selected text")+ }+ if !m.selection.active {+ t.Fatal("selection should stay visible on release")+ }+ if m.selection.dragging {+ t.Fatal("selection should stop tracking drag on release")+ }+}++func TestChatArrowKeysNavigatePromptHistoryWhenTranscriptScrollable(t *testing.T) {+ m := chatModel{+ input: []rune("current draft"),+ promptHistory: []string{"old prompt"},+ width: 80,+ height: 10,+ running: true,+ }+ for range 12 {+ m.entries = append(m.entries, chatEntry{role: "user", content: "line"})+ }+ if m.maxScroll() == 0 {+ t.Fatal("test setup should produce scrollable transcript")+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyUp})+ m = updated.(chatModel)+ if m.scroll != 0 {+ t.Fatalf("key up should not scroll transcript, got %d", m.scroll)+ }+ if got := string(m.input); got != "old prompt" {+ t.Fatalf("key up should recall prompt history, got %q", got)+ }++ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyDown})+ m = updated.(chatModel)+ if m.scroll != 0 {+ t.Fatalf("key down should not scroll transcript, got %d", m.scroll)+ }+ if got := string(m.input); got != "current draft" {+ t.Fatalf("key down should restore draft, got %q", got)+ }+}++func TestEntriesFromMessagesSkipsToolCallOnlyAssistant(t *testing.T) {+ args := api.NewToolCallFunctionArguments()+ args.Set("command", "pwd")+ messages := []api.Message{+ {Role: "user", Content: "pwd"},+ {+ Role: "assistant",+ ToolCalls: []api.ToolCall{{+ ID: "call-1",+ Function: api.ToolCallFunction{+ Name: "bash",+ Arguments: args,+ },+ }},+ },+ {Role: "tool", ToolName: "bash", ToolCallID: "call-1", Content: "/tmp/project\n"},+ {Role: "assistant", Content: "The current directory is /tmp/project."},+ }++ entries := entriesFromMessages(messages)+ if len(entries) != 3 {+ t.Fatalf("entries = %d, want user/tool/assistant: %#v", len(entries), entries)+ }+ if entries[1].role != "tool" || entries[1].label != "Bash(\"pwd\")" {+ t.Fatalf("tool entry = %#v", entries[1])+ }+ if line := stripANSI(toolStatusLine(entries[1])); line != `Bash("pwd")` {+ t.Fatalf("tool status line = %q, want command label", line)+ }++ transcript := stripANSI((chatModel{entries: entries}).renderTranscript(120))+ if strings.Contains(transcript, "• \n") || strings.Contains(transcript, "•\n") {+ t.Fatalf("transcript has blank assistant bullet: %q", transcript)+ }+}++func TestEntriesFromMessagesRendersDeniedCommandAsDenied(t *testing.T) {+ args := api.NewToolCallFunctionArguments()+ args.Set("command", "pwd")+ messages := []api.Message{+ {+ Role: "assistant",+ ToolCalls: []api.ToolCall{{+ ID: "call-1",+ Function: api.ToolCallFunction{+ Name: "bash",+ Arguments: args,+ },+ }},+ },+ {Role: "tool", ToolName: "bash", ToolCallID: "call-1", Content: "Tool execution denied."},+ }++ entries := entriesFromMessages(messages)+ if len(entries) != 1 {+ t.Fatalf("entries = %d, want one tool entry: %#v", len(entries), entries)+ }+ if entries[0].status != "denied" {+ t.Fatalf("tool status = %q, want denied: %#v", entries[0].status, entries[0])+ }+ if line := stripANSI(toolStatusLine(entries[0])); line != `Bash("pwd") denied` {+ t.Fatalf("tool status line = %q, want denied command label", line)+ }+}++func TestEntriesFromMessagesRendersDisabledToolAsSkipped(t *testing.T) {+ args := api.NewToolCallFunctionArguments()+ args.Set("command", "pwd")+ messages := []api.Message{+ {+ Role: "assistant",+ ToolCalls: []api.ToolCall{{+ ID: "call-1",+ Function: api.ToolCallFunction{+ Name: "bash",+ Arguments: args,+ },+ }},+ },+ {Role: "tool", ToolName: "bash", ToolCallID: "call-1", Content: "Tool execution disabled."},+ }++ entries := entriesFromMessages(messages)+ if len(entries) != 1 {+ t.Fatalf("entries = %d, want one tool entry: %#v", len(entries), entries)+ }+ if entries[0].status != "disabled" {+ t.Fatalf("tool status = %q, want disabled: %#v", entries[0].status, entries[0])+ }+ if action := toolActionForEntry(entries[0]); action != "disabled_command" {+ t.Fatalf("tool action = %q, want disabled_command", action)+ }+ if phrase := toolActionPhrase(toolActionForEntry(entries[0]), 1); phrase != "Skipped a command" {+ t.Fatalf("tool action phrase = %q, want skipped command", phrase)+ }+}++func TestEntriesFromMessagesRendersCompactionSummaryCollapsed(t *testing.T) {+ entries := entriesFromMessages([]api.Message{+ {Role: "assistant", ToolCalls: []api.ToolCall{{+ ID: coreagent.CompactionToolCallID,+ Function: api.ToolCallFunction{+ Name: coreagent.CompactionToolName,+ },+ }}},+ {Role: "tool", ToolName: coreagent.CompactionToolName, ToolCallID: coreagent.CompactionToolCallID, Content: coreagent.CompactionSummaryMessagePrefix + "- old work\n- decisions"},+ {Role: "user", Content: "recent request"},+ })+ if len(entries) != 2 {+ t.Fatalf("entries = %d, want summary plus user: %#v", len(entries), entries)+ }+ if entries[0].role != "compaction_summary" || entries[0].content != "- old work\n- decisions" {+ t.Fatalf("summary entry = %#v", entries[0])+ }++ m := chatModel{entries: entries}+ transcript := stripANSI(m.renderTranscript(100))+ if !strings.Contains(transcript, "Compacted summary") {+ t.Fatalf("collapsed summary row missing: %q", transcript)+ }+ if strings.Contains(transcript, "Compacted summary done") {+ t.Fatalf("summary row should not include done word: %q", transcript)+ }+ if strings.Contains(transcript, "old work") {+ t.Fatalf("summary body should be collapsed: %q", transcript)+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)+ view := stripANSI(m.renderTranscript(100))+ if !strings.Contains(view, "old work") || !strings.Contains(view, "decisions") {+ t.Fatalf("inline summary body missing: %q", view)+ }+}++func TestEntriesFromMessagesHidesAutomaticCompactionInstruction(t *testing.T) {+ entries := entriesFromMessages([]api.Message{+ {+ Role: "tool",+ ToolName: coreagent.CompactionToolName,+ ToolCallID: coreagent.CompactionToolCallID,+ Content: coreagent.CompactionSummaryMessagePrefix + "old work summary\n\n" + coreagent.CompactionContinueInstruction,+ },+ })+ if len(entries) != 1 || entries[0].role != "compaction_summary" || entries[0].content != "old work summary" {+ t.Fatalf("entries = %#v", entries)+ }+}++func TestEntriesFromMessagesRecognizesLegacySystemCompactionSummary(t *testing.T) {+ entries := entriesFromMessages([]api.Message{+ {Role: "system", Content: "Conversation summary:\nlegacy summary"},+ })+ if len(entries) != 1 || entries[0].role != "compaction_summary" || entries[0].content != "legacy summary" {+ t.Fatalf("entries = %#v", entries)+ }+}++func TestEntriesFromMessagesGroupsMultiToolHistoryInMiddle(t *testing.T) {+ readArgs := api.NewToolCallFunctionArguments()+ readArgs.Set("path", "feedback")+ listArgs := api.NewToolCallFunctionArguments()+ listArgs.Set("path", ".")+ messages := []api.Message{+ {Role: "user", Content: "read feedback file"},+ {+ Role: "assistant",+ ToolCalls: []api.ToolCall{+ {+ ID: "call-read",+ Function: api.ToolCallFunction{+ Name: "read",+ Arguments: readArgs,+ },+ },+ {+ ID: "call-list",+ Function: api.ToolCallFunction{+ Name: "list",+ Arguments: listArgs,+ },+ },+ },+ },+ {Role: "tool", ToolName: "read", ToolCallID: "call-read", Content: "Error: no such file"},+ {Role: "tool", ToolName: "list", ToolCallID: "call-list", Content: "feedback.md\n"},+ {Role: "assistant", Content: "There is a feedback.md file."},+ }++ entries := entriesFromMessages(messages)+ if len(entries) != 3 {+ t.Fatalf("entries = %d, want user/tool-group/assistant: %#v", len(entries), entries)+ }+ if entries[1].role != "tool_group" || len(entries[1].tools) != 2 {+ t.Fatalf("middle entry should be grouped tool history: %#v", entries[1])+ }+ if entries[1].tools[0].label != "Read(\"feedback\")" || entries[1].tools[1].label != "List(\".\")" {+ t.Fatalf("group labels = %#v", entries[1].tools)+ }+}++func TestChatToolCallDetectedDoesNotRenderQueuedRows(t *testing.T) {+ args := api.NewToolCallFunctionArguments()+ args.Set("command", "pwd")+ m := chatModel{}++ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolCallDetected,+ ToolCalls: []api.ToolCall{{+ ID: "call-1",+ Function: api.ToolCallFunction{+ Name: "bash",+ Arguments: args,+ },+ }},+ })++ if len(m.entries) != 0 {+ t.Fatalf("queued tool call should not create history entries: %#v", m.entries)+ }++ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolStarted,+ ToolCallID: "call-1",+ ToolName: "bash",+ Args: args.ToMap(),+ })+ if len(m.entries) != 1 {+ t.Fatalf("started tool should create one visible entry, got %d", len(m.entries))+ }+ if got := m.activityLabel(); got != "" {+ t.Fatalf("activityLabel = %q, want no transient tool label", got)+ }+ if line := strings.TrimSpace(stripANSI(m.activityLine())); line != "" {+ t.Fatalf("activityLine = %q, want no transient tool action line", line)+ }+}++func TestChatToolOutputIsHiddenUntilExpanded(t *testing.T) {+ fullOutput := strings.Repeat("x", maxCtrlOToolOutputRunes+25) + "tail-marker"+ m := chatModel{}+ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolFinished,+ ToolName: "bash",+ Content: fullOutput,+ })++ if len(m.entries) != 1 {+ t.Fatalf("entries = %d, want 1", len(m.entries))+ }+ if m.entries[0].content != fullOutput {+ t.Fatal("tool entry should keep full content before rendering")+ }++ transcript := m.renderTranscript(100)+ body := stripANSI(transcript)+ if strings.Contains(body, "tail-marker") || strings.Contains(body, strings.Repeat("x", 20)) {+ t.Fatalf("collapsed tool output should be hidden: %q", body)+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)++ if !m.toolOutputMode || !m.toolOutputOpen || !m.entries[0].expanded {+ t.Fatalf("ctrl+o should expand tool output inline: %#v", m.entries[0])+ }+ body = stripANSI(m.renderTranscript(100))+ if strings.Contains(body, "tail-marker") {+ t.Fatalf("expanded transcript should cap tool output: %q", body)+ }+ if !strings.Contains(body, "...") {+ t.Fatalf("expanded transcript should show capped output ellipsis: %q", body)+ }+ if got := strings.Count(body, "x"); got != maxCtrlOToolOutputRunes-3 {+ t.Fatalf("expanded transcript x count = %d, want %d:\n%s", got, maxCtrlOToolOutputRunes-3, body)+ }++ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)+ body = stripANSI(m.renderTranscript(100))+ if m.toolOutputOpen || m.entries[0].expanded || strings.Contains(body, strings.Repeat("x", 20)) {+ t.Fatalf("second ctrl+o should collapse tool output: %q", body)+ }+}++func TestChatCompletedToolsGroupWhenNextStepStarts(t *testing.T) {+ firstArgs := map[string]any{"command": "pwd"}+ secondArgs := map[string]any{"command": "ls"}+ thirdArgs := map[string]any{"command": "date"}+ m := chatModel{}++ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-1", ToolName: "bash", Args: firstArgs})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, ToolCallID: "call-1", ToolName: "bash", Args: firstArgs, Content: "one"})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-2", ToolName: "bash", Args: secondArgs})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, ToolCallID: "call-2", ToolName: "bash", Args: secondArgs, Content: "two"})+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-3", ToolName: "bash", Args: thirdArgs})++ if len(m.entries) != 2 {+ t.Fatalf("entries = %d, want grouped history plus active tool: %#v", len(m.entries), m.entries)+ }+ if m.entries[0].role != "tool_group" || len(m.entries[0].tools) != 2 {+ t.Fatalf("first entry should be grouped tool history: %#v", m.entries[0])+ }+ if line := stripANSI(toolGroupStatusLine(m.entries[0])); line != "Ran 2 commands" {+ t.Fatalf("grouped command line = %q", line)+ }+ if m.entries[1].status != "running" || m.entries[1].label != "Bash(\"date\")" {+ t.Fatalf("second entry should be active tool: %#v", m.entries[1])+ }+ if line := stripANSI(toolStatusLine(m.entries[1])); line != `Bash("date")` {+ t.Fatalf("running command line = %q", line)+ }+}++func TestChatCompletedToolsGroupAcrossEmptyAssistantEntries(t *testing.T) {+ entries := groupCompletedToolEntries([]chatEntry{+ newChatEntry(chatEntry{role: "tool", detail: "bash", label: `Bash("ls")`, status: "done", content: "listed"}),+ newChatEntry(chatEntry{role: "assistant"}),+ newChatEntry(chatEntry{role: "tool", detail: "read", label: `Read("agent")`, status: "error", err: "is directory", content: "is directory"}),+ newChatEntry(chatEntry{role: "assistant", content: " "}),+ newChatEntry(chatEntry{role: "tool", detail: "read", label: `Read("AGENTS.md")`, status: "done", content: "instructions"}),+ newChatEntry(chatEntry{role: "assistant", content: "The files were listed."}),+ })++ if len(entries) != 2 {+ t.Fatalf("entries = %d, want grouped tools plus assistant: %#v", len(entries), entries)+ }+ if entries[0].role != "tool_group" || len(entries[0].tools) != 3 {+ t.Fatalf("first entry should group tools across empty assistant entries: %#v", entries[0])+ }+ if line := stripANSI(toolGroupStatusLine(entries[0])); line != "Ran 1 command and read 2 files" {+ t.Fatalf("grouped tool line = %q", line)+ }+ if entries[1].role != "assistant" || entries[1].content != "The files were listed." {+ t.Fatalf("second entry should keep real assistant content: %#v", entries[1])+ }+}++func TestChatCompletedToolsGroupAcrossCollapsedThinking(t *testing.T) {+ entries := groupCompletedToolEntries([]chatEntry{+ newChatEntry(chatEntry{role: "tool", detail: "bash", label: `Bash("pwd")`, status: "done", content: "one"}),+ newChatEntry(chatEntry{role: "thinking", label: "Thinking", content: "choose next tool", status: "done"}),+ newChatEntry(chatEntry{role: "tool", detail: "bash", label: `Bash("ls")`, status: "done", content: "two"}),+ newChatEntry(chatEntry{role: "assistant"}),+ newChatEntry(chatEntry{role: "tool", detail: "read", label: `Read("AGENTS.md")`, status: "done", content: "instructions"}),+ })++ if len(entries) != 1 {+ t.Fatalf("entries = %d, want one grouped tool entry: %#v", len(entries), entries)+ }+ if entries[0].role != "tool_group" || len(entries[0].tools) != 3 {+ t.Fatalf("tools should group across collapsed thinking: %#v", entries[0])+ }+ if line := stripANSI(toolGroupStatusLine(entries[0])); line != "Ran 2 commands and read a file" {+ t.Fatalf("grouped tool line = %q", line)+ }+}++func TestChatCtrlOTogglesInlineToolOutput(t *testing.T) {+ m := chatModel{+ width: 100,+ height: 20,+ entries: []chatEntry{+ {role: "tool", detail: "bash", label: "Bash(\"pwd\")", status: "done", content: "one"},+ {role: "assistant", content: "between"},+ {role: "tool", detail: "read", label: "Read(\"file\")", status: "error", err: "nope", content: "two"},+ },+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)+ for _, index := range []int{0, 2} {+ if !m.entries[index].expanded {+ t.Fatalf("tool entry %d should be expanded inline", index)+ }+ }+ view := stripANSI(m.renderTranscript(100))+ if strings.Contains(view, "Tool details") {+ t.Fatalf("ctrl+o should keep tool output inline: %q", view)+ }+ if !strings.Contains(view, "one") || !strings.Contains(view, "two") {+ t.Fatalf("view missing inline expanded tool output: %q", view)+ }+ if !strings.Contains(view, "between") {+ t.Fatalf("inline tool output should keep surrounding chat visible: %q", view)+ }++ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)+ for _, index := range []int{0, 2} {+ if m.entries[index].expanded {+ t.Fatalf("tool entry %d should remain collapsed", index)+ }+ }+}++func TestChatCtrlOTogglesInlineOutput(t *testing.T) {+ m := chatModel{+ width: 100,+ height: 24,+ entries: []chatEntry{+ {role: "user", content: "who is parth sareen"},+ {role: "tool", detail: "web_search", label: "Web Search(\"who is Parth Sareen\")", status: "done", content: "Search results"},+ {role: "assistant", content: "Based on public search results, Parth Sareen works on AI tooling."},+ },+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)+ if !m.toolOutputOpen || !m.entries[1].expanded {+ t.Fatalf("tool output should be expanded inline: %#v", m.entries[1])+ }++ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)+ if m.toolOutputOpen || m.entries[1].expanded {+ t.Fatalf("tool output should be collapsed inline: %#v", m.entries[1])+ }+}++func TestChatCtrlODoesNotExpandThinking(t *testing.T) {+ m := chatModel{+ entries: []chatEntry{+ newChatEntry(chatEntry{role: "thinking", label: "Thinking", status: "done", content: "private reasoning"}),+ },+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)+ if m.entries[0].expanded {+ t.Fatalf("ctrl+o should not expand thinking entries: %#v", m.entries[0])+ }+ if view := stripANSI(m.renderTranscript(100)); strings.Contains(view, "private reasoning") {+ t.Fatalf("ctrl+o should not render thinking content:\n%s", view)+ }++ m.liveMessages = []api.Message{{Role: "assistant", Thinking: "live private reasoning"}}+ m.syncThinkingEntry()+ if m.entries[1].expanded {+ t.Fatalf("live thinking should not inherit ctrl+o expansion: %#v", m.entries[1])+ }+ if view := stripANSI(m.renderTranscript(100)); strings.Contains(view, "live private reasoning") {+ t.Fatalf("ctrl+o should not render live thinking content:\n%s", view)+ }+}++func TestChatCtrlOCollapseKeepsInputPromptVisible(t *testing.T) {+ m := chatModel{+ width: 80,+ height: 8,+ opts: Options{Model: "gemma4"},+ entries: []chatEntry{+ {role: "user", content: "inspect this"},+ {role: "tool", detail: "bash", label: "Bash(\"pwd\")", status: "done", content: strings.Repeat("output\n", 20)},+ {role: "assistant", content: "Done."},+ },+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)+ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)++ view := stripANSI(m.View())+ if !strings.Contains(view, "│ █") {+ t.Fatalf("input prompt disappeared after collapsing tool output:\n%s", view)+ }+}++func TestChatCtrlOShowsRunningToolOutputInline(t *testing.T) {+ args := map[string]any{"command": "pwd"}+ m := chatModel{+ width: 100,+ height: 20,+ running: true,+ opts: Options{Model: "test-model"},+ }+ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolStarted,+ ToolCallID: "call-1",+ ToolName: "bash",+ Args: args,+ })++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)+ if !m.entries[0].expanded {+ t.Fatalf("ctrl+o should expand the running tool inline")+ }+ view := stripANSI(m.View())+ if !strings.Contains(view, `Bash("pwd")`) || !strings.Contains(view, "$ pwd") {+ t.Fatalf("expanded transcript missing running tool details:\n%s", view)+ }++ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolFinished,+ ToolCallID: "call-1",+ ToolName: "bash",+ Args: args,+ Content: "/tmp/project\n",+ })++ view = stripANSI(m.View())+ if !strings.Contains(view, "/tmp/project") {+ t.Fatalf("finished tool output should be visible inline: %q", view)+ }+ if !strings.Contains(view, "│ █") {+ t.Fatalf("input prompt disappeared while tool output is expanded:\n%s", view)+ }+ if !strings.Contains(view, "test-model") {+ t.Fatalf("footer/model line disappeared while tool output is expanded:\n%s", view)+ }++ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)+ view = stripANSI(m.View())+ if !strings.Contains(view, "│ █") {+ t.Fatalf("input prompt disappeared after collapsing tool output:\n%s", view)+ }+ if !strings.Contains(view, "test-model") {+ t.Fatalf("footer/model line disappeared after collapsing tool output:\n%s", view)+ }+}++func TestChatLongCommandLabelTruncatesAndCtrlOShowsFullCommand(t *testing.T) {+ command := strings.Repeat("x", 120)+ m := chatModel{+ width: 180,+ height: 20,+ }+ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolStarted,+ ToolCallID: "call-1",+ ToolName: "bash",+ Args: map[string]any{"command": command},+ })++ wantLabel := `Bash("` + strings.Repeat("x", 100) + `...")`+ if m.entries[0].label != wantLabel {+ t.Fatalf("label = %q, want %q", m.entries[0].label, wantLabel)+ }+ if strings.Contains(m.entries[0].label, strings.Repeat("x", 101)) {+ t.Fatalf("collapsed label should truncate command: %q", m.entries[0].label)+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)+ view := stripANSI(m.renderTranscript(180))+ if !strings.Contains(view, "$ "+command) {+ t.Fatalf("expanded ctrl+o view should show full command:\n%s", view)+ }+}++func TestChatCtrlOInlineOutputSurvivesToolGrouping(t *testing.T) {+ firstArgs := map[string]any{"command": "pwd"}+ secondArgs := map[string]any{"command": "ls"}+ m := chatModel{+ width: 100,+ height: 24,+ entries: []chatEntry{+ newChatEntry(chatEntry{role: "tool", detail: "bash", label: "Bash(\"pwd\")", status: "done", content: "one", args: firstArgs}),+ newChatEntry(chatEntry{role: "tool", detail: "bash", label: "Bash(\"ls\")", status: "done", content: "two", args: secondArgs}),+ },+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)+ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolStarted,+ ToolCallID: "call-3",+ ToolName: "bash",+ Args: map[string]any{"command": "date"},+ })++ if len(m.entries) != 2 {+ t.Fatalf("entries = %d, want tool group plus active tool: %#v", len(m.entries), m.entries)+ }+ if m.entries[0].role != "tool_group" || !m.entries[0].expanded {+ t.Fatalf("grouped tool history should stay expanded inline: %#v", m.entries[0])+ }+ if line := stripANSI(toolGroupStatusLine(m.entries[0])); line != "Ran 2 commands" {+ t.Fatalf("grouped command line = %q", line)+ }++ view := stripANSI(m.renderTranscript(100))+ for _, want := range []string{`Bash("pwd")`, `Bash("ls")`, `Bash("date")`, "one", "two"} {+ if !strings.Contains(view, want) {+ t.Fatalf("grouped tool output missing %q:\n%s", want, view)+ }+ }+ if strings.Contains(view, " Ran 1 command") {+ t.Fatalf("expanded grouped children should show concrete invocations, not generic summaries:\n%s", view)+ }+}++func TestChatExpandedToolGroupRendersIndentedToolBlocks(t *testing.T) {+ startedAt := time.Date(2026, 6, 11, 12, 0, 0, 0, time.UTC)+ m := chatModel{+ entries: []chatEntry{+ newChatEntry(chatEntry{+ role: "tool_group",+ label: "Tool calls (2)",+ status: "done",+ expanded: true,+ tools: []chatEntry{+ newChatEntry(chatEntry{+ role: "tool",+ detail: "web_search",+ label: "Web Search(\"Parth Sareen\")",+ status: "done",+ content: "Search results for: Parth Sareen",+ startedAt: startedAt,+ finishedAt: startedAt.Add(823 * time.Millisecond),+ }),+ newChatEntry(chatEntry{+ role: "tool",+ detail: "read",+ label: "Read(\"feedback.md\")",+ status: "done",+ content: "Looks good.",+ startedAt: startedAt.Add(time.Second),+ finishedAt: startedAt.Add(3 * time.Second),+ }),+ },+ }),+ },+ }++ transcript := stripANSI(m.renderTranscript(120))+ expected := strings.Join([]string{+ " Web Search(\"Parth Sareen\")",+ " Search results for: Parth Sareen",+ " ",+ " Read(\"feedback.md\")",+ " Looks good.",+ }, "\n")+ if !strings.Contains(transcript, expected) {+ t.Fatalf("expanded tool group did not render expected block spacing:\n%s", transcript)+ }+}++func TestChatExpandedToolGroupCapsChildOutput(t *testing.T) {+ longOutput := strings.Repeat("y", maxCtrlOToolOutputRunes+25) + "group-tail-marker"+ m := chatModel{+ entries: []chatEntry{+ newChatEntry(chatEntry{+ role: "tool_group",+ status: "done",+ expanded: true,+ tools: []chatEntry{+ newChatEntry(chatEntry{+ role: "tool",+ detail: "read",+ label: "Read(\"big.log\")",+ status: "done",+ content: longOutput,+ }),+ },+ }),+ },+ }++ transcript := stripANSI(m.renderTranscript(120))+ if strings.Contains(transcript, "group-tail-marker") {+ t.Fatalf("expanded grouped tool output should be capped:\n%s", transcript)+ }+ if !strings.Contains(transcript, "...") {+ t.Fatalf("expanded grouped tool output should show capped output ellipsis:\n%s", transcript)+ }+ if got := strings.Count(transcript, "y"); got != maxCtrlOToolOutputRunes-3 {+ t.Fatalf("expanded grouped tool output y count = %d, want %d:\n%s", got, maxCtrlOToolOutputRunes-3, transcript)+ }+ if got := m.entries[0].tools[0].content; got != longOutput {+ t.Fatal("ctrl+o rendering should not mutate grouped tool content")+ }+}++func TestChatToolGroupStatusOmitsResultCounts(t *testing.T) {+ startedAt := time.Date(2026, 6, 15, 17, 0, 0, 0, time.UTC)+ entry := newChatEntry(chatEntry{+ role: "tool_group",+ label: "Tool calls (3)",+ status: "error",+ startedAt: startedAt,+ finishedAt: startedAt.Add(3 * time.Second),+ tools: []chatEntry{+ newChatEntry(chatEntry{role: "tool", status: "done"}),+ newChatEntry(chatEntry{role: "tool", status: "done"}),+ newChatEntry(chatEntry{role: "tool", status: "error", err: "failed"}),+ },+ })++ line := stripANSI(toolGroupStatusLine(entry))+ for _, word := range []string{"succeeded", "failed", "done", "in 3s", "3s"} {+ if strings.Contains(line, word) {+ t.Fatalf("group status = %q, should not show status word or elapsed %q", line, word)+ }+ }+ if line != "Used 3 tools" {+ t.Fatalf("group status = %q, want action summary", line)+ }+}++func TestChatToolGroupStatusShowsAllSuccessCount(t *testing.T) {+ entry := newChatEntry(chatEntry{+ role: "tool_group",+ label: "Tool calls (2)",+ status: "done",+ tools: []chatEntry{+ newChatEntry(chatEntry{role: "tool", status: "done"}),+ newChatEntry(chatEntry{role: "tool", status: "done"}),+ },+ })++ line := stripANSI(toolGroupStatusLine(entry))+ if strings.Contains(line, "succeeded") || strings.Contains(line, "done") {+ t.Fatalf("group status = %q, should not show success count or done", line)+ }+ if line != "Used 2 tools" {+ t.Fatalf("group status = %q, want action summary", line)+ }+}++func TestChatToolGroupStatusRecomputesCachedLabel(t *testing.T) {+ entries := groupCompletedToolEntries([]chatEntry{+ newChatEntry(chatEntry{+ role: "tool_group",+ label: "Ran 1 command",+ status: "done",+ tools: []chatEntry{+ newChatEntry(chatEntry{role: "tool", detail: "bash", label: `Bash("pwd")`, status: "done"}),+ },+ }),+ newChatEntry(chatEntry{+ role: "tool",+ detail: "bash",+ label: `Bash("ls")`,+ status: "done",+ }),+ })++ if len(entries) != 1 || entries[0].role != "tool_group" {+ t.Fatalf("entries = %#v, want regrouped tool group", entries)+ }+ if line := stripANSI(toolGroupStatusLine(entries[0])); line != "Ran 2 commands" {+ t.Fatalf("group status = %q, want recomputed action summary", line)+ }+}++func TestChatToolGroupStatusKeepsHiddenDetectedCount(t *testing.T) {+ args := map[string]any{"command": "ls"}+ entry := newChatEntry(chatEntry{+ role: "tool_group",+ label: "Ran 2 commands",+ status: "done",+ tools: []chatEntry{+ newChatEntry(chatEntry{role: "tool", detail: "bash", label: `Bash("pwd")`, status: "done"}),+ },+ })+ entry.tools[0].args = map[string]any{"command": "pwd"}+ detected := []chatEntry{+ newChatEntry(chatEntry{role: "tool", detail: "bash", label: `Bash("ls")`, status: "queued", args: args}),+ }++ grouped := groupCompletedToolEntries([]chatEntry{entry}, detected...)+ if len(grouped) != 1 || grouped[0].role != "tool_group" || len(grouped[0].tools) != 1 {+ t.Fatalf("grouped entries = %#v, want visible finished child only", grouped)+ }+ if line := stripANSI(toolGroupStatusLine(grouped[0])); line != "Ran 2 commands" {+ t.Fatalf("group status = %q, want hidden detected command counted", line)+ }+}++func TestChatToolOutputRendersUnifiedDiff(t *testing.T) {+ diff := strings.Join([]string{+ "diff --git a/file.go b/file.go",+ "index 1111111..2222222 100644",+ "--- a/file.go",+ "+++ b/file.go",+ "@@ -1,3 +1,3 @@",+ " package main",+ "-var old = true",+ "+var newer = true",+ }, "\n")+ m := chatModel{+ entries: []chatEntry{{+ role: "tool",+ detail: "bash",+ label: "Bash(\"git diff\")",+ status: "done",+ content: diff,+ }},+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)+ rendered := m.renderTranscript(100)+ body := stripANSI(rendered)+ if !strings.Contains(body, "diff --git a/file.go b/file.go") ||+ !strings.Contains(body, "-var old = true") ||+ !strings.Contains(body, "+var newer = true") {+ t.Fatalf("rendered diff missing expected lines: %q", body)+ }+ if !looksLikeUnifiedDiff(diff) {+ t.Fatal("diff output should be detected as a unified diff")+ }+}++func TestChatToolCallRendersPrettyInvocationAndResult(t *testing.T) {+ args := api.NewToolCallFunctionArguments()+ args.Set("query", "Parth Sareen Ollama software engineer")++ m := chatModel{width: 100, height: 30}+ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolCallDetected,+ ToolCalls: []api.ToolCall{{+ ID: "call-1",+ Function: api.ToolCallFunction{+ Name: "web_search",+ Arguments: args,+ },+ }},+ })+ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolStarted,+ ToolCallID: "call-1",+ ToolName: "web_search",+ Args: args.ToMap(),+ })+ m.applyAgentEvent(coreagent.Event{+ Type: coreagent.EventToolFinished,+ ToolCallID: "call-1",+ ToolName: "web_search",+ Args: args.ToMap(),+ Content: "**Search results for:** Parth Sareen\n\n1. Parth Sareen\n URL: https://parthsareen.com\n",+ })++ transcript := stripANSI(m.renderTranscript(100))+ if !strings.Contains(transcript, "Web Search(\"Parth Sareen Ollama software engineer\")") {+ t.Fatalf("transcript missing invocation: %q", transcript)+ }+ for _, word := range []string{"done", "in 6s", "6s"} {+ if strings.Contains(transcript, word) {+ t.Fatalf("transcript should not include status word/elapsed %q: %q", word, transcript)+ }+ }+ if strings.Contains(transcript, "https://parthsareen.com") || strings.Contains(transcript, "Search results for:") {+ t.Fatalf("tool output should be collapsed by default: %q", transcript)+ }+ if strings.Contains(transcript, "web_search") {+ t.Fatalf("transcript should use display name instead of raw tool name: %q", transcript)+ }+ if m.entries[0].status != "done" {+ t.Fatalf("tool status = %q, want done", m.entries[0].status)+ }++ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})+ m = updated.(chatModel)+ view := stripANSI(m.renderTranscript(100))+ if !strings.Contains(view, "**Search results for:**") || !strings.Contains(view, "https://parthsareen.com") {+ t.Fatalf("inline web output missing content: %q", view)+ }+}++func TestChatToolOutputHidesInternalTruncationMarker(t *testing.T) {+ entry := chatEntry{+ role: "tool",+ detail: "bash",+ status: "done",+ expanded: true,+ content: "head\n\n[tool output truncated: showing first ~10 tokens and last ~10 tokens; omitted ~25 tokens. Use a narrower command, line range, or search query if more detail is needed.]\n\ntail",+ }++ rendered := stripANSI(strings.Join(renderToolResultLines(entry, 80), "\n"))+ if strings.Contains(rendered, "tool output truncated") || strings.Contains(rendered, "omitted ~25 tokens") {+ t.Fatalf("internal truncation marker should be hidden from tool output: %q", rendered)+ }+ if !strings.Contains(rendered, "head") || !strings.Contains(rendered, "tail") {+ t.Fatalf("tool output should keep visible content: %q", rendered)+ }+}++func TestChatRenderTranscriptCachesEntryLinesUntilDirty(t *testing.T) {+ m := chatModel{+ entries: []chatEntry{+ newChatEntry(chatEntry{role: "assistant", content: "**hello**"}),+ },+ }++ _ = m.renderTranscript(80)+ if len(m.entries[0].renderLines) == 0 {+ t.Fatal("rendered entry lines should be cached")+ }++ m.entries[0].renderLines = []string{"cached line"}+ if got := stripANSI(m.renderTranscript(80)); !strings.Contains(got, "cached line") {+ t.Fatalf("render should reuse cached lines for unchanged entry: %q", got)+ }++ m.entries[0].content = "**changed**"+ m.markEntryDirty(0)+ if got := stripANSI(m.renderTranscript(80)); strings.Contains(got, "cached line") || !strings.Contains(got, "changed") {+ t.Fatalf("dirty entry should re-render instead of using stale cache: %q", got)+ }+}++func TestWrapChatTextSplitsLongLines(t *testing.T) {+ lines := wrapChatText("alpha beta gamma delta", 12)+ if len(lines) < 2 {+ t.Fatalf("lines = %#v, want split text", lines)+ }+ if strings.Contains(lines[0], "delta") {+ t.Fatalf("first line was not wrapped: %#v", lines)+ }+}++func TestWrapChatTextUsesDisplayWidth(t *testing.T) {+ lines := wrapChatText(strings.Repeat("界", 20), 20)+ if len(lines) < 2 {+ t.Fatalf("lines = %#v, want full-width text split", lines)+ }+ for _, line := range lines {+ if got := lipgloss.Width(line); got > 20 {+ t.Fatalf("line %q width = %d, want <= 20", line, got)+ }+ }+}++func TestRenderMarkdownTableWrapsLongCells(t *testing.T) {+ markdown := strings.Join([]string{+ "| # | Item | Why it matters |",+ "|---|---|---|",+ "| **C** | **Bash filesystem/network confinement** | Biggest asymmetry: file tools are sandboxed via `os.Root`, bash is not and this text should survive until tail-token. |",+ }, "\n")++ rendered := renderMarkdownForView(markdown, 72)+ plain := stripANSI(rendered)+ if !strings.Contains(plain, "tail-token") {+ t.Fatalf("long table cell was truncated:\n%s", plain)+ }+ if strings.Contains(plain, "tail-toke...") {+ t.Fatalf("long table cell should wrap, not ellipsize:\n%s", plain)+ }+ for _, line := range strings.Split(rendered, "\n") {+ if got := lipgloss.Width(line); got > 72 {+ t.Fatalf("rendered table line width = %d, want <= 72: %q\n%s", got, stripANSI(line), plain)+ }+ }+}diff --git a/cmd/tui/chat/test_helpers_test.go b/cmd/tui/chat/test_helpers_test.gonew file mode 100644index 000000000..4f7535a2a--- /dev/null+++ b/cmd/tui/chat/test_helpers_test.go@@ -0,0 +1,87 @@+package chat++import (+ "context"+ "regexp"+ "testing"+ "time"++ tea "github.com/charmbracelet/bubbletea"++ coreagent "github.com/ollama/ollama/agent"+ "github.com/ollama/ollama/api"+)++type chatTestTool struct{}++type chatTestClient struct{}++type chatCaptureClient struct {+ requests []*api.ChatRequest+}++func (chatTestClient) Chat(ctx context.Context, req *api.ChatRequest, fn api.ChatResponseFunc) error {+ if err := ctx.Err(); err != nil {+ return err+ }+ return fn(api.ChatResponse{+ Message: api.Message{Role: "assistant", Content: "ok"},+ Done: true,+ })+}++func (c *chatCaptureClient) Chat(ctx context.Context, req *api.ChatRequest, fn api.ChatResponseFunc) error {+ if err := ctx.Err(); err != nil {+ return err+ }+ c.requests = append(c.requests, req)+ return fn(api.ChatResponse{+ Message: api.Message{Role: "assistant", Content: "ok"},+ Done: true,+ })+}++func (chatTestTool) Name() string {+ return "fake_tool"+}++func (chatTestTool) Description() string {+ return "does test work"+}++func (chatTestTool) Schema() api.ToolFunction {+ return api.ToolFunction{+ Name: "fake_tool",+ Description: "does test work",+ Parameters: api.ToolFunctionParameters{+ Type: "object",+ },+ }+}++func (chatTestTool) Execute(context.Context, coreagent.ToolContext, map[string]any) (coreagent.ToolResult, error) {+ return coreagent.ToolResult{Content: "ok"}, nil+}++func waitForRunDone(t *testing.T, events <-chan tea.Msg) chatRunDoneMsg {+ t.Helper()+ timeout := time.After(2 * time.Second)+ for {+ select {+ case msg, ok := <-events:+ if !ok {+ t.Fatal("events closed before run done")+ }+ if done, ok := msg.(chatRunDoneMsg); ok {+ return done+ }+ case <-timeout:+ t.Fatal("timed out waiting for run done")+ }+ }+}++func stripANSI(s string) string {+ re := regexp.MustCompile(`\x1b\[[0-9;:]*[A-Za-z]`)+ return re.ReplaceAllString(s, "")+}diff --git a/cmd/tui/chat/theme.go b/cmd/tui/chat/theme.gonew file mode 100644index 000000000..5426c3f29--- /dev/null+++ b/cmd/tui/chat/theme.go@@ -0,0 +1,126 @@+package chat++import "github.com/charmbracelet/lipgloss"++const (+ chatAnsiRed = "1"+ chatAnsiGreen = "2"+ chatAnsiYellow = "3"+ chatAnsiBlue = "4"+ chatAnsiCyan = "6"+ chatAnsiBrightBlack = "8"+)++var (+ chatHeaderStyle = lipgloss.NewStyle().+ Bold(true)++ chatMetaStyle = lipgloss.NewStyle().+ Faint(true)++ chatFooterStyle = lipgloss.NewStyle().+ Faint(true)++ chatInputBorderStyle = lipgloss.NewStyle().+ Faint(true)++ chatInputPlaceholderStyle = lipgloss.NewStyle().+ Foreground(lipgloss.Color("8"))++ chatCursorStyle = lipgloss.NewStyle().+ Reverse(true)++ chatBlankCursorStyle = lipgloss.NewStyle().+ Faint(true)++ chatNotificationStyle = chatMetaStyle++ chatUserStyle = lipgloss.NewStyle()++ chatUserBlockStyle = lipgloss.NewStyle().+ Foreground(lipgloss.AdaptiveColor{Light: "#777777", Dark: "#8a8a8a"})++ chatToolStyle = lipgloss.NewStyle()++ chatInlineCodeStyle = lipgloss.NewStyle().+ Bold(true)++ chatCodeBlockStyle = lipgloss.NewStyle()++ chatTableBorderStyle = lipgloss.NewStyle().+ Faint(true)++ chatToolRunningStyle = lipgloss.NewStyle().+ Foreground(lipgloss.Color(chatAnsiYellow))++ chatToolDoneStyle = lipgloss.NewStyle().+ Foreground(lipgloss.Color(chatAnsiGreen))++ // chatToolMixedStyle marks a tool group with both succeeded and failed+ // calls (partial success). Amber/orange is distinct from green (success),+ // red (failure), and yellow (running).+ chatToolMixedStyle = lipgloss.NewStyle().+ Foreground(lipgloss.Color("208"))++ chatToolOutputStyle = lipgloss.NewStyle().+ Foreground(lipgloss.AdaptiveColor{Light: "#666666", Dark: "#a0a0a0"})++ chatDiffMetaStyle = lipgloss.NewStyle().+ Faint(true)++ chatDiffFileStyle = lipgloss.NewStyle().+ Bold(true).+ Foreground(lipgloss.Color(chatAnsiCyan))++ chatDiffHunkStyle = lipgloss.NewStyle().+ Foreground(lipgloss.Color(chatAnsiBlue))++ chatDiffAddStyle = lipgloss.NewStyle().+ Foreground(lipgloss.Color(chatAnsiGreen))++ chatDiffDeleteStyle = lipgloss.NewStyle().+ Foreground(lipgloss.Color(chatAnsiRed))++ chatErrorStyle = lipgloss.NewStyle().+ Foreground(lipgloss.Color(chatAnsiRed))++ chatFullAccessStyle = lipgloss.NewStyle().+ Foreground(lipgloss.AdaptiveColor{Light: "#9f5f5f", Dark: "#b87373"})++ chatCommandNameStyle = lipgloss.NewStyle()++ chatPickerTextStyle = lipgloss.NewStyle()++ chatPickerTitleStyle = lipgloss.NewStyle().+ Bold(true)++ chatPickerSelectedStyle = lipgloss.NewStyle().+ Bold(true)++ chatPickerMetaStyle = lipgloss.NewStyle().+ Faint(true)++ chatHistoryTitleStyle = lipgloss.NewStyle().+ Bold(true)++ chatHistorySystemRoleStyle = lipgloss.NewStyle().+ Bold(true).+ Faint(true)++ chatHistoryUserRoleStyle = lipgloss.NewStyle().+ Bold(true).+ Foreground(lipgloss.Color(chatAnsiBlue))++ chatHistoryAssistantRoleStyle = lipgloss.NewStyle().+ Bold(true).+ Foreground(lipgloss.Color(chatAnsiYellow))++ chatHistoryToolRoleStyle = lipgloss.NewStyle().+ Bold(true).+ Foreground(lipgloss.Color(chatAnsiGreen))++ chatHistoryLabelStyle = lipgloss.NewStyle().+ Faint(true)++ chatHistoryTextStyle = lipgloss.NewStyle()+)diff --git a/cmd/tui/chat/think.go b/cmd/tui/chat/think.gonew file mode 100644index 000000000..074bfa683--- /dev/null+++ b/cmd/tui/chat/think.go@@ -0,0 +1,166 @@+package chat++import (+ "fmt"+ "strings"++ tea "github.com/charmbracelet/bubbletea"++ "github.com/ollama/ollama/api"+)++type chatThinkOption struct {+ value string+ label string+ description string+}++type chatThinkPicker struct {+ options []chatThinkOption+ cursor int+}++var chatThinkOptions = []chatThinkOption{+ {value: "auto", label: "auto", description: "use the model default"},+ {value: "on", label: "on", description: "enable thinking"},+ {value: "off", label: "off", description: "disable thinking"},+ {value: "low", label: "low", description: "use low thinking effort"},+ {value: "medium", label: "medium", description: "use medium thinking effort"},+ {value: "high", label: "high", description: "use high thinking effort"},+ {value: "max", label: "max", description: "use maximum thinking effort"},+}++func (m *chatModel) openThinkPicker() (tea.Model, tea.Cmd) {+ m.thinkPicker = newChatThinkPicker(m.opts.Think)+ m.status = "think"+ return *m, nil+}++func newChatThinkPicker(current *api.ThinkValue) *chatThinkPicker {+ picker := &chatThinkPicker{options: append([]chatThinkOption(nil), chatThinkOptions...)}+ currentValue := thinkValueLabel(current)+ for i, option := range picker.options {+ if option.value == currentValue {+ picker.cursor = i+ break+ }+ }+ return picker+}++func (m chatModel) updateThinkPicker(msg tea.KeyMsg) (tea.Model, tea.Cmd) {+ switch msg.Type {+ case tea.KeyCtrlC, tea.KeyEsc:+ m.thinkPicker = nil+ m.status = "ready"+ case tea.KeyEnter:+ return m.selectThinkOption()+ case tea.KeyUp:+ m.thinkPicker.move(-1)+ case tea.KeyDown:+ m.thinkPicker.move(1)+ }+ return m, nil+}++func (p *chatThinkPicker) move(delta int) {+ if p == nil || len(p.options) == 0 || delta == 0 {+ return+ }+ p.cursor = clamp(p.cursor+delta, 0, len(p.options)-1)+}++func (p *chatThinkPicker) selected() (chatThinkOption, bool) {+ if p == nil || len(p.options) == 0 {+ return chatThinkOption{}, false+ }+ return p.options[clamp(p.cursor, 0, len(p.options)-1)], true+}++func (m chatModel) selectThinkOption() (tea.Model, tea.Cmd) {+ option, ok := m.thinkPicker.selected()+ if !ok {+ return m, nil+ }+ m.thinkPicker = nil+ return m.applyThinkValue(option.value)+}++func (m *chatModel) handleThinkCommand(value string) (tea.Model, tea.Cmd) {+ return m.applyThinkValue(value)+}++func (m *chatModel) applyThinkValue(value string) (tea.Model, tea.Cmd) {+ think, label, err := parseThinkValue(value)+ if err != nil {+ m.entries = append(m.entries, newChatEntry(chatEntry{role: "error", content: err.Error(), err: err.Error()}))+ m.status = "error"+ return *m, nil+ }+ m.opts.Think = think+ m.status = "think " + label+ return *m, nil+}++func parseThinkValue(value string) (*api.ThinkValue, string, error) {+ switch strings.ToLower(strings.TrimSpace(value)) {+ case "", "auto", "default", "unset":+ return nil, "auto", nil+ case "on", "true", "think", "thinking":+ return &api.ThinkValue{Value: true}, "on", nil+ case "off", "false", "nothink", "no-think":+ return &api.ThinkValue{Value: false}, "off", nil+ case "low", "medium", "high", "max":+ value = strings.ToLower(strings.TrimSpace(value))+ return &api.ThinkValue{Value: value}, value, nil+ default:+ return nil, "", fmt.Errorf("Usage: /think [auto|on|off|low|medium|high|max]")+ }+}++func thinkValueLabel(value *api.ThinkValue) string {+ if value == nil || value.Value == nil {+ return "auto"+ }+ switch v := value.Value.(type) {+ case bool:+ if v {+ return "on"+ }+ return "off"+ case string:+ return strings.ToLower(v)+ default:+ return "auto"+ }+}++func (m chatModel) renderThinkPicker(width int) string {+ picker := m.thinkPicker+ if picker == nil {+ return ""+ }++ var b strings.Builder+ b.WriteString(chatPickerTitleStyle.Render("Thinking mode"))+ b.WriteString("\n\n")+ for i, option := range picker.options {+ selected := i == picker.cursor+ if selected {+ b.WriteString(chatPickerSelectedStyle.Render("› " + option.label))+ } else {+ b.WriteString(" ")+ b.WriteString(chatPickerTextStyle.Render(option.label))+ }+ b.WriteByte('\n')+ b.WriteString(chatPickerMetaStyle.Render(" " + option.description))+ b.WriteByte('\n')+ if i < len(picker.options)-1 {+ b.WriteByte('\n')+ }+ }++ b.WriteString("\n")+ b.WriteString(chatPickerMetaStyle.Render("↑/↓ navigate • enter select • esc cancel"))+ return b.String()+}diff --git a/cmd/tui/confirm.go b/cmd/tui/confirm.goindex a0060539a..a483375ab 100644--- a/cmd/tui/confirm.go+++ b/cmd/tui/confirm.go@@ -39,7 +39,7 @@ func (m confirmModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {wasSet := m.width > 0m.width = msg.Widthif wasSet {- return m, tea.EnterAltScreen+ return m, tea.ClearScreen}return m, nildiff --git a/cmd/tui/selector.go b/cmd/tui/selector.goindex c53fe16d5..68e133de1 100644--- a/cmd/tui/selector.go+++ b/cmd/tui/selector.go@@ -2,6 +2,7 @@ package tuiimport ("fmt"+ "sort""strings"tea "github.com/charmbracelet/bubbletea"@@ -63,6 +64,8 @@ type SelectItem struct {AvailabilityBadge string}+type SelectorModel = selectorModel+type selectorItemsUpdatedMsg struct {items []SelectItem}@@ -121,6 +124,7 @@ type selectorModel struct {cancelled boolhelpText stringwidth int+ rankFiltered bool}func selectorModelWithCurrent(title string, items []SelectItem, current string) selectorModel {@@ -133,6 +137,21 @@ func selectorModelWithCurrent(title string, items []SelectItem, current string)return m}+func NewSelectorModel(title string, items []SelectItem, current string) SelectorModel {+ return selectorModelWithCurrent(title, items, current)+}++func NewModelSelectorModel(title string, items []SelectItem, current, filter string) SelectorModel {+ m := selectorModelWithCurrent(title, items, current)+ m.filter = strings.TrimSpace(filter)+ m.rankFiltered = true+ if m.filter != "" {+ m.cursor = 0+ m.scrollOffset = 0+ }+ return m+}+func currentItemName(items []SelectItem, cursor int) string {if cursor < 0 || cursor >= len(items) {return ""@@ -140,15 +159,22 @@ func currentItemName(items []SelectItem, cursor int) string {return items[cursor].Name}+func indexOfItemName(items []SelectItem, name string) int {+ for i, item := range items {+ if item.Name == name {+ return i+ }+ }+ return -1+}+func cursorForItemName(items []SelectItem, name string, fallback int) int {if len(items) == 0 {return 0}if name != "" {- for i, item := range items {- if item.Name == name {- return i- }+ if i := indexOfItemName(items, name); i >= 0 {+ return i}}if fallback < 0 {@@ -167,10 +193,19 @@ func (m selectorModel) filteredItems() []SelectItem {filterLower := strings.ToLower(m.filter)var result []SelectItemfor _, item := range m.items {+ if m.rankFiltered {+ if selectItemMatchScore(item, filterLower).ok {+ result = append(result, item)+ }+ continue+ }if strings.Contains(strings.ToLower(item.Name), filterLower) {result = append(result, item)}}+ if m.rankFiltered {+ sortSelectItemsForFilter(result, filterLower)+ }return result}@@ -241,6 +276,54 @@ func (m *selectorModel) updateNavigation(msg tea.KeyMsg) {}}+func (m *selectorModel) UpdateNavigation(msg tea.KeyMsg) {+ m.updateNavigation(msg)+}++func (m *selectorModel) Move(delta int) {+ if delta == 0 {+ return+ }+ filtered := m.filteredItems()+ if len(filtered) == 0 {+ m.cursor = 0+ m.scrollOffset = 0+ return+ }+ m.cursor += delta+ if m.cursor < 0 {+ m.cursor = 0+ }+ if m.cursor >= len(filtered) {+ m.cursor = len(filtered) - 1+ }+ m.updateScroll(m.otherStart())+}++func (m *selectorModel) SetHelpText(help string) {+ m.helpText = help+}++func (m selectorModel) Filter() string {+ return m.filter+}++func (m selectorModel) FilteredItems() []SelectItem {+ return append([]SelectItem(nil), m.filteredItems()...)+}++func (m selectorModel) SelectedItem() (SelectItem, bool) {+ filtered := m.filteredItems()+ if len(filtered) == 0 || m.cursor < 0 || m.cursor >= len(filtered) {+ return SelectItem{}, false+ }+ return filtered[m.cursor], true+}++func (m selectorModel) RenderContent() string {+ return m.renderContent()+}+// updateScroll adjusts scrollOffset based on cursor position.// When not filtering, scrollOffset is relative to the "More" (non-recommended) section.// When filtering, it's relative to the full filtered list.@@ -281,7 +364,7 @@ func (m selectorModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {wasSet := m.width > 0m.width = msg.Widthif wasSet {- return m, tea.EnterAltScreen+ return m, tea.ClearScreen}return m, nil@@ -338,6 +421,16 @@ func (m selectorModel) renderItem(s *strings.Builder, item SelectItem, idx int)}}+func (m selectorModel) renderCompactItem(s *strings.Builder, item SelectItem, idx int) {+ if idx == m.cursor {+ s.WriteString(selectorSelectedItemStyle.Render("▸ " + item.Name))+ s.WriteString(cursorItemSuffix(item))+ } else {+ s.WriteString(selectorItemStyle.Render(item.Name))+ }+ s.WriteString("\n")+}+// renderContent renders the selector content (title, items, help text) without// checking the cancelled/selected state. This is used by both View() (standalone mode)// and by the TUI modal which embeds a selectorModel.@@ -431,6 +524,57 @@ func (m selectorModel) renderContent() string {return s.String()}+func (m selectorModel) RenderCompactContent(maxItems int) string {+ var s strings.Builder++ s.WriteString(selectorTitleStyle.Render(m.title))+ s.WriteString(" ")+ if m.filter == "" {+ s.WriteString(selectorFilterStyle.Render("Type to filter..."))+ } else {+ s.WriteString(selectorInputStyle.Render(m.filter))+ }+ s.WriteString("\n")++ filtered := m.filteredItems()+ if len(filtered) == 0 {+ s.WriteString(selectorItemStyle.Render(selectorDescStyle.Render("(no matches)")))+ s.WriteString("\n")+ } else {+ maxItems = max(1, maxItems)+ start := 0+ if len(filtered) > maxItems {+ start = m.cursor - maxItems/2+ if start < 0 {+ start = 0+ }+ if maxStart := len(filtered) - maxItems; start > maxStart {+ start = maxStart+ }+ }+ end := min(len(filtered), start+maxItems)+ if start > 0 {+ s.WriteString(selectorMoreStyle.Render(fmt.Sprintf("... %d more above", start)))+ s.WriteString("\n")+ }+ for idx := start; idx < end; idx++ {+ m.renderCompactItem(&s, filtered[idx], idx)+ }+ if remaining := len(filtered) - end; remaining > 0 {+ s.WriteString(selectorMoreStyle.Render(fmt.Sprintf("... and %d more", remaining)))+ s.WriteString("\n")+ }+ }++ help := "↑/↓ navigate • enter select • esc cancel"+ if m.helpText != "" {+ help = m.helpText+ }+ s.WriteString(selectorHelpStyle.Render(help))++ return s.String()+}+func (m selectorModel) View() string {if m.cancelled || m.selected != "" {return ""@@ -443,6 +587,99 @@ func (m selectorModel) View() string {return s}+type selectItemScore struct {+ ok bool+ rank int+ index int+ lengthDelta int+ recommended int+ name string+}++func sortSelectItemsForFilter(items []SelectItem, filter string) {+ filter = strings.ToLower(strings.TrimSpace(filter))+ sort.SliceStable(items, func(i, j int) bool {+ return compareSelectItemsForFilter(items[i], items[j], filter) < 0+ })+}++func compareSelectItemsForFilter(a, b SelectItem, filter string) int {+ aScore := selectItemMatchScore(a, filter)+ bScore := selectItemMatchScore(b, filter)+ for _, cmp := range []int{+ compareSelectorInt(aScore.rank, bScore.rank),+ compareSelectorInt(aScore.index, bScore.index),+ compareSelectorInt(aScore.lengthDelta, bScore.lengthDelta),+ compareSelectorInt(aScore.recommended, bScore.recommended),+ strings.Compare(aScore.name, bScore.name),+ } {+ if cmp != 0 {+ return cmp+ }+ }+ return 0+}++func selectItemMatchScore(item SelectItem, filter string) selectItemScore {+ filter = strings.ToLower(strings.TrimSpace(filter))+ name := strings.ToLower(strings.TrimSpace(item.Name))+ description := strings.ToLower(strings.TrimSpace(item.Description))+ score := selectItemScore{+ rank: 4,+ index: 1 << 20,+ lengthDelta: 1 << 20,+ name: name,+ }+ if item.Recommended {+ score.recommended = -1+ }+ if filter == "" {+ score.ok = true+ return score+ }+ nameRunes := len([]rune(name))+ filterRunes := len([]rune(filter))+ if name == filter {+ score.ok = true+ score.rank = 0+ score.index = 0+ score.lengthDelta = 0+ return score+ }+ if strings.HasPrefix(name, filter) {+ score.ok = true+ score.rank = 1+ score.index = 0+ score.lengthDelta = max(0, nameRunes-filterRunes)+ return score+ }+ if index := strings.Index(name, filter); index >= 0 {+ score.ok = true+ score.rank = 2+ score.index = len([]rune(name[:index]))+ score.lengthDelta = max(0, nameRunes-filterRunes)+ return score+ }+ if index := strings.Index(description, filter); index >= 0 {+ score.ok = true+ score.rank = 3+ score.index = len([]rune(description[:index]))+ score.lengthDelta = max(0, nameRunes-filterRunes)+ }+ return score+}++func compareSelectorInt(a, b int) int {+ switch {+ case a < b:+ return -1+ case a > b:+ return 1+ default:+ return 0+ }+}+// cursorForCurrent returns the item index matching current, or 0 if not found.func cursorForCurrent(items []SelectItem, current string) int {if current == "" {@@ -451,10 +688,8 @@ func cursorForCurrent(items []SelectItem, current string) int {// Prefer exact name matches before tag-prefix fallback so "qwen3.5" does not// incorrectly select "qwen3.5:cloud" (and vice versa) based on list order.- for i, item := range items {- if item.Name == current {- return i- }+ if i := indexOfItemName(items, current); i >= 0 {+ return i}for i, item := range items {@@ -700,7 +935,7 @@ func (m multiSelectorModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {wasSet := m.width > 0m.width = msg.Widthif wasSet {- return m, tea.EnterAltScreen+ return m, tea.ClearScreen}return m, nildiff --git a/cmd/tui/signin.go b/cmd/tui/signin.goindex c45326ebd..f8a512fb4 100644--- a/cmd/tui/signin.go+++ b/cmd/tui/signin.go@@ -60,7 +60,7 @@ func (m signInModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {wasSet := m.width > 0m.width = msg.Widthif wasSet {- return m, tea.EnterAltScreen+ return m, tea.ClearScreen}return m, nil@@ -115,7 +115,7 @@ func (m upgradeModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {wasSet := m.width > 0m.width = msg.Widthif wasSet {- return m, tea.EnterAltScreen+ return m, tea.ClearScreen}return m, nildiff --git a/cmd/tui/tui.go b/cmd/tui/tui.goindex 6f051e4c0..cbc701fa1 100644--- a/cmd/tui/tui.go+++ b/cmd/tui/tui.go@@ -48,8 +48,8 @@ type menuItem struct {const pinnedIntegrationCount = 4var runModelMenuItem = menuItem{- title: "Chat with a model",- description: "Start an interactive chat with a model",+ title: "Chat, Code, & Work",+ description: "Chat with models, code, search the web, and do work",isRunModel: true,}diff --git a/cmd/tui/tui_test.go b/cmd/tui/tui_test.goindex 91b3abd90..3298cbbe0 100644--- a/cmd/tui/tui_test.go+++ b/cmd/tui/tui_test.go@@ -140,7 +140,14 @@ func TestMenuRendersPinnedItemsAndMore(t *testing.T) {}view := menu.View()- for _, want := range []string{"Chat with a model", "Launch Claude Code", "Launch Hermes Agent", "Launch OpenClaw", "More..."} {+ for _, want := range []string{+ "Chat, Code, & Work",+ "Chat with models, code, search the web, and do work",+ "Launch Claude Code",+ "Launch Hermes Agent",+ "Launch OpenClaw",+ "More...",+ } {if !strings.Contains(view, want) {t.Fatalf("expected menu view to contain %q\n%s", want, view)}