blob: e6e5b4e54c702aadc7e5cc9c784be5a2c3fe8b4a [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001package termui
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "os/exec"
12 "os/signal"
13 "strings"
14 "sync"
15 "syscall"
16 "text/template"
17 "time"
18
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +000019 "github.com/dustin/go-humanize"
Earl Lee2e463fb2025-04-17 11:22:22 -070020 "github.com/fatih/color"
21 "golang.org/x/term"
22 "sketch.dev/loop"
23)
24
25var (
26 // toolUseTemplTxt defines how tool invocations appear in the terminal UI.
27 // Keep this template in sync with the tools defined in claudetool package
28 // and registered in loop/agent.go.
29 // Add formatting for new tools as they are created.
30 // TODO: should this be part of tool definition to make it harder to forget to set up?
31 toolUseTemplTxt = `{{if .msg.ToolError}}šŸ™ˆ {{end -}}
32{{if eq .msg.ToolName "think" -}}
33 🧠 {{.input.thoughts -}}
34{{else if eq .msg.ToolName "keyword_search" -}}
35 šŸ” {{ .input.query}}: {{.input.keywords -}}
36{{else if eq .msg.ToolName "bash" -}}
Philip Zeyligerb60f0f22025-04-23 18:19:32 +000037 šŸ–„ļø{{if .input.background}}šŸ”„{{end}} {{ .input.command -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070038{{else if eq .msg.ToolName "patch" -}}
39 āŒØļø {{.input.path -}}
40{{else if eq .msg.ToolName "done" -}}
41{{/* nothing to show here, the agent will write more in its next message */}}
42{{else if eq .msg.ToolName "title" -}}
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000043šŸ·ļø {{.input.title}}
44🌱 git branch: sketch/{{.input.branch_name}}
Earl Lee2e463fb2025-04-17 11:22:22 -070045{{else if eq .msg.ToolName "str_replace_editor" -}}
46 āœļø {{.input.file_path -}}
47{{else if eq .msg.ToolName "codereview" -}}
48 šŸ› Running automated code review, may be slow
49{{else -}}
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000050 šŸ› ļø {{ .msg.ToolName}}: {{.msg.ToolInput -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070051{{end -}}
52`
53 toolUseTmpl = template.Must(template.New("tool_use").Parse(toolUseTemplTxt))
54)
55
56type termUI struct {
57 stdin *os.File
58 stdout *os.File
59 stderr *os.File
60
61 agent loop.CodingAgent
62 httpURL string
63
64 trm *term.Terminal
65
66 // the chatMsgCh channel is for "conversation" messages, like responses to user input
67 // from the LLM, or output from executing slash-commands issued by the user.
68 chatMsgCh chan chatMessage
69
70 // the log channel is for secondary messages, like logging, errors, and debug information
71 // from local and remove subproceses.
72 termLogCh chan string
73
74 // protects following
75 mu sync.Mutex
76 oldState *term.State
77 // Tracks branches that were pushed during the session
78 pushedBranches map[string]struct{}
79}
80
81type chatMessage struct {
82 idx int
83 sender string
84 content string
85 thinking bool
86}
87
88func New(agent loop.CodingAgent, httpURL string) *termUI {
89 return &termUI{
90 agent: agent,
91 stdin: os.Stdin,
92 stdout: os.Stdout,
93 stderr: os.Stderr,
94 httpURL: httpURL,
95 chatMsgCh: make(chan chatMessage, 1),
96 termLogCh: make(chan string, 1),
97 pushedBranches: make(map[string]struct{}),
98 }
99}
100
101func (ui *termUI) Run(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700102 fmt.Println(`🌐 ` + ui.httpURL + `/`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700103 fmt.Println(`šŸ’¬ type 'help' for help`)
104 fmt.Println()
105
106 // Start up the main terminal UI:
107 if err := ui.initializeTerminalUI(ctx); err != nil {
108 return err
109 }
110 go ui.receiveMessagesLoop(ctx)
111 if err := ui.inputLoop(ctx); err != nil {
112 return err
113 }
114 return nil
115}
116
117func (ui *termUI) LogToolUse(resp loop.AgentMessage) {
118 inputData := map[string]any{}
119 if err := json.Unmarshal([]byte(resp.ToolInput), &inputData); err != nil {
120 ui.AppendSystemMessage("error: %v", err)
121 return
122 }
123 buf := bytes.Buffer{}
124 if err := toolUseTmpl.Execute(&buf, map[string]any{"msg": resp, "input": inputData, "output": resp.ToolResult}); err != nil {
125 ui.AppendSystemMessage("error: %v", err)
126 return
127 }
128 ui.AppendSystemMessage("%s\n", buf.String())
129}
130
131func (ui *termUI) receiveMessagesLoop(ctx context.Context) {
132 bold := color.New(color.Bold).SprintFunc()
133 for {
134 select {
135 case <-ctx.Done():
136 return
137 default:
138 }
139 resp := ui.agent.WaitForMessage(ctx)
140 // Typically a user message will start the thinking and a (top-level
141 // conversation) end of turn will stop it.
142 thinking := !(resp.EndOfTurn && resp.ParentConversationID == nil)
143
144 switch resp.Type {
145 case loop.AgentMessageType:
Josh Bleecher Snyder2978ab22025-04-30 10:29:32 -0700146 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "šŸ•“ļø ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700147 case loop.ToolUseMessageType:
148 ui.LogToolUse(resp)
149 case loop.ErrorMessageType:
150 ui.AppendSystemMessage("āŒ %s", resp.Content)
151 case loop.BudgetMessageType:
152 ui.AppendSystemMessage("šŸ’° %s", resp.Content)
153 case loop.AutoMessageType:
154 ui.AppendSystemMessage("🧐 %s", resp.Content)
155 case loop.UserMessageType:
Josh Bleecher Snyderc2d26102025-04-30 06:19:43 -0700156 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "🦸", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700157 case loop.CommitMessageType:
158 // Display each commit in the terminal
159 for _, commit := range resp.Commits {
160 if commit.PushedBranch != "" {
Sean McCullough43664f62025-04-20 16:13:03 -0700161 ui.AppendSystemMessage("šŸ”„ new commit: [%s] %s\npushed to: %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch))
Earl Lee2e463fb2025-04-17 11:22:22 -0700162
163 // Track the pushed branch in our map
164 ui.mu.Lock()
165 ui.pushedBranches[commit.PushedBranch] = struct{}{}
166 ui.mu.Unlock()
167 } else {
168 ui.AppendSystemMessage("šŸ”„ new commit: [%s] %s", commit.Hash[:8], commit.Subject)
169 }
170 }
171 default:
172 ui.AppendSystemMessage("āŒ Unexpected Message Type %s %v", resp.Type, resp)
173 }
174 }
175}
176
177func (ui *termUI) inputLoop(ctx context.Context) error {
178 for {
179 line, err := ui.trm.ReadLine()
180 if errors.Is(err, io.EOF) {
181 ui.AppendSystemMessage("\n")
182 line = "exit"
183 } else if err != nil {
184 return err
185 }
186
187 line = strings.TrimSpace(line)
188
189 switch line {
190 case "?", "help":
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700191 ui.AppendSystemMessage(`General use:
192Use chat to ask sketch to tackle a task or answer a question about this repo.
193
194Special commands:
195- help, ? : Show this help message
196- budget : Show original budget
197- usage, cost : Show current token usage and cost
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000198- browser, open, b : Open current conversation in browser
Earl Lee2e463fb2025-04-17 11:22:22 -0700199- stop, cancel, abort : Cancel the current operation
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700200- exit, quit, q : Exit sketch
201- ! <command> : Execute a shell command (e.g. !ls -la)`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700202 case "budget":
203 originalBudget := ui.agent.OriginalBudget()
204 ui.AppendSystemMessage("šŸ’° Budget summary:")
205 if originalBudget.MaxResponses > 0 {
206 ui.AppendSystemMessage("- Max responses: %d", originalBudget.MaxResponses)
207 }
208 if originalBudget.MaxWallTime > 0 {
209 ui.AppendSystemMessage("- Max wall time: %v", originalBudget.MaxWallTime)
210 }
211 ui.AppendSystemMessage("- Max total cost: %0.2f", originalBudget.MaxDollars)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000212 case "browser", "open", "b":
213 if ui.httpURL != "" {
214 ui.AppendSystemMessage("🌐 Opening %s in browser", ui.httpURL)
215 go ui.agent.OpenBrowser(ui.httpURL)
216 } else {
217 ui.AppendSystemMessage("āŒ No web URL available for this session")
218 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700219 case "usage", "cost":
220 totalUsage := ui.agent.TotalUsage()
221 ui.AppendSystemMessage("šŸ’° Current usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000222 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
223 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700224 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
225 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
226 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
227 case "bye", "exit", "q", "quit":
228 ui.trm.SetPrompt("")
229 // Display final usage stats
230 totalUsage := ui.agent.TotalUsage()
231 ui.AppendSystemMessage("šŸ’° Final usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000232 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
233 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700234 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
235 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
236 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
237
238 // Display pushed branches
239 ui.mu.Lock()
240 if len(ui.pushedBranches) > 0 {
241 // Convert map keys to a slice for display
242 branches := make([]string, 0, len(ui.pushedBranches))
243 for branch := range ui.pushedBranches {
244 branches = append(branches, branch)
245 }
246
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000247 initialCommitRef := getGitRefName(ui.agent.InitialCommit())
Earl Lee2e463fb2025-04-17 11:22:22 -0700248 if len(branches) == 1 {
249 ui.AppendSystemMessage("\nšŸ”„ Branch pushed during session: %s", branches[0])
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000250 ui.AppendSystemMessage("šŸ’ To add those changes to your branch: git cherry-pick %s..%s", initialCommitRef, branches[0])
Earl Lee2e463fb2025-04-17 11:22:22 -0700251 } else {
252 ui.AppendSystemMessage("\nšŸ”„ Branches pushed during session:")
253 for _, branch := range branches {
254 ui.AppendSystemMessage("- %s", branch)
255 }
256 ui.AppendSystemMessage("\nšŸ’ To add all those changes to your branch:")
257 for _, branch := range branches {
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000258 ui.AppendSystemMessage("git cherry-pick %s..%s", initialCommitRef, branch)
Earl Lee2e463fb2025-04-17 11:22:22 -0700259 }
260 }
261 }
262 ui.mu.Unlock()
263
264 ui.AppendSystemMessage("\nšŸ‘‹ Goodbye!")
265 return nil
266 case "stop", "cancel", "abort":
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000267 ui.agent.CancelTurn(fmt.Errorf("user canceled the operation"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700268 case "panic":
269 panic("user forced a panic")
270 default:
271 if line == "" {
272 continue
273 }
274 if strings.HasPrefix(line, "!") {
275 // Execute as shell command
276 line = line[1:] // remove the '!' prefix
277 sendToLLM := strings.HasPrefix(line, "!")
278 if sendToLLM {
279 line = line[1:] // remove the second '!'
280 }
281
282 // Create a cmd and run it
283 // TODO: ui.trm contains a mutex inside its write call.
284 // It is potentially safe to attach ui.trm directly to this
285 // cmd object's Stdout/Stderr and stream the output.
286 // That would make a big difference for, e.g. wget.
287 cmd := exec.Command("bash", "-c", line)
288 out, err := cmd.CombinedOutput()
289 ui.AppendSystemMessage("%s", out)
290 if err != nil {
291 ui.AppendSystemMessage("āŒ Command error: %v", err)
292 }
293 if sendToLLM {
294 // Send the command and its output to the agent
295 message := fmt.Sprintf("I ran the command: `%s`\nOutput:\n```\n%s```", line, out)
296 if err != nil {
297 message += fmt.Sprintf("\n\nError: %v", err)
298 }
299 ui.agent.UserMessage(ctx, message)
300 }
301 continue
302 }
303
304 // Send it to the LLM
305 // chatMsg := chatMessage{sender: "you", content: line}
306 // ui.sendChatMessage(chatMsg)
307 ui.agent.UserMessage(ctx, line)
308 }
309 }
310}
311
312func (ui *termUI) updatePrompt(thinking bool) {
313 var t string
314
315 if thinking {
316 // Emoji don't seem to work here? Messes up my terminal.
317 t = "*"
318 }
Josh Bleecher Snyder23b6a2d2025-04-30 04:07:52 +0000319 p := fmt.Sprintf("%s ($%0.2f/%0.2f)%s> ",
320 ui.httpURL, ui.agent.TotalUsage().TotalCostUSD, ui.agent.OriginalBudget().MaxDollars, t)
Earl Lee2e463fb2025-04-17 11:22:22 -0700321 ui.trm.SetPrompt(p)
322}
323
324func (ui *termUI) initializeTerminalUI(ctx context.Context) error {
325 ui.mu.Lock()
326 defer ui.mu.Unlock()
327
328 if !term.IsTerminal(int(ui.stdin.Fd())) {
329 return fmt.Errorf("this command requires terminal I/O")
330 }
331
332 oldState, err := term.MakeRaw(int(ui.stdin.Fd()))
333 if err != nil {
334 return err
335 }
336 ui.oldState = oldState
337 ui.trm = term.NewTerminal(ui.stdin, "")
338 width, height, err := term.GetSize(int(ui.stdin.Fd()))
339 if err != nil {
340 return fmt.Errorf("Error getting terminal size: %v\n", err)
341 }
342 ui.trm.SetSize(width, height)
343 // Handle terminal resizes...
344 sig := make(chan os.Signal, 1)
345 signal.Notify(sig, syscall.SIGWINCH)
346 go func() {
347 for {
348 <-sig
349 newWidth, newHeight, err := term.GetSize(int(ui.stdin.Fd()))
350 if err != nil {
351 continue
352 }
353 if newWidth != width || newHeight != height {
354 width, height = newWidth, newHeight
355 ui.trm.SetSize(width, height)
356 }
357 }
358 }()
359
360 ui.updatePrompt(false)
361
362 // This is the only place where we should call fe.trm.Write:
363 go func() {
364 for {
365 select {
366 case <-ctx.Done():
367 return
368 case msg := <-ui.chatMsgCh:
369 // Sometimes claude doesn't say anything when it runs tools.
370 // No need to output anything in that case.
371 if strings.TrimSpace(msg.content) == "" {
372 break
373 }
Josh Bleecher Snyder2978ab22025-04-30 10:29:32 -0700374 s := fmt.Sprintf("%s %s\n", msg.sender, msg.content)
Earl Lee2e463fb2025-04-17 11:22:22 -0700375 // Update prompt before writing, because otherwise it doesn't redraw the prompt.
376 ui.updatePrompt(msg.thinking)
377 ui.trm.Write([]byte(s))
378 case logLine := <-ui.termLogCh:
379 b := []byte(logLine + "\n")
380 ui.trm.Write(b)
381 }
382 }
383 }()
384
385 return nil
386}
387
388func (ui *termUI) RestoreOldState() error {
389 ui.mu.Lock()
390 defer ui.mu.Unlock()
391 return term.Restore(int(ui.stdin.Fd()), ui.oldState)
392}
393
394// AppendChatMessage is for showing responses the user's request, conversational dialog etc
395func (ui *termUI) AppendChatMessage(msg chatMessage) {
396 ui.chatMsgCh <- msg
397}
398
399// AppendSystemMessage is for debug information, errors and such that are not part of the "conversation" per se,
400// but still need to be shown to the user.
401func (ui *termUI) AppendSystemMessage(fmtString string, args ...any) {
402 ui.termLogCh <- fmt.Sprintf(fmtString, args...)
403}
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000404
405// getGitRefName returns a readable git ref for sha, falling back to the original sha on error.
406func getGitRefName(sha string) string {
407 // branch or tag name
408 cmd := exec.Command("git", "rev-parse", "--abbrev-ref", sha)
409 branchName, err := cmd.Output()
410 if err == nil {
411 branchStr := strings.TrimSpace(string(branchName))
412 // If we got a branch name that's not HEAD, use it
413 if branchStr != "" && branchStr != "HEAD" {
414 return branchStr
415 }
416 }
417
418 // short SHA
419 cmd = exec.Command("git", "rev-parse", "--short", sha)
420 shortSha, err := cmd.Output()
421 if err == nil {
422 shortStr := strings.TrimSpace(string(shortSha))
423 if shortStr != "" {
424 return shortStr
425 }
426 }
427
428 return sha
429}