blob: 1ffe6555f977e912ad1b5417ca341b4ee8658e51 [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?
Josh Bleecher Snyderc3c20232025-05-07 05:46:04 -070031 toolUseTemplTxt = `{{if .msg.ToolError}}ć€°ļø {{end -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070032{{if eq .msg.ToolName "think" -}}
33 🧠 {{.input.thoughts -}}
34{{else if eq .msg.ToolName "keyword_search" -}}
Josh Bleecher Snyder453a62f2025-05-01 10:14:33 -070035 šŸ” {{ .input.query}}: {{.input.search_terms -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070036{{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}}
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +000044{{else if eq .msg.ToolName "precommit" -}}
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000045🌱 git branch: sketch/{{.input.branch_name}}
Earl Lee2e463fb2025-04-17 11:22:22 -070046{{else if eq .msg.ToolName "str_replace_editor" -}}
47 āœļø {{.input.file_path -}}
48{{else if eq .msg.ToolName "codereview" -}}
49 šŸ› Running automated code review, may be slow
Sean McCullough485afc62025-04-28 14:28:39 -070050{{else if eq .msg.ToolName "multiplechoice" -}}
51 šŸ“ {{.input.question}}
52{{ range .input.responseOptions -}}
53 - {{ .caption}}: {{.responseText}}
54{{end -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070055{{else -}}
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000056 šŸ› ļø {{ .msg.ToolName}}: {{.msg.ToolInput -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070057{{end -}}
58`
59 toolUseTmpl = template.Must(template.New("tool_use").Parse(toolUseTemplTxt))
60)
61
David Crawshaw93fec602025-05-05 08:40:06 -070062type TermUI struct {
Earl Lee2e463fb2025-04-17 11:22:22 -070063 stdin *os.File
64 stdout *os.File
65 stderr *os.File
66
67 agent loop.CodingAgent
68 httpURL string
69
70 trm *term.Terminal
71
72 // the chatMsgCh channel is for "conversation" messages, like responses to user input
73 // from the LLM, or output from executing slash-commands issued by the user.
74 chatMsgCh chan chatMessage
75
76 // the log channel is for secondary messages, like logging, errors, and debug information
77 // from local and remove subproceses.
78 termLogCh chan string
79
80 // protects following
81 mu sync.Mutex
82 oldState *term.State
83 // Tracks branches that were pushed during the session
84 pushedBranches map[string]struct{}
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +000085
86 // Pending message count, for graceful shutdown
87 messageWaitGroup sync.WaitGroup
Earl Lee2e463fb2025-04-17 11:22:22 -070088}
89
90type chatMessage struct {
91 idx int
92 sender string
93 content string
94 thinking bool
95}
96
David Crawshaw93fec602025-05-05 08:40:06 -070097func New(agent loop.CodingAgent, httpURL string) *TermUI {
98 return &TermUI{
Earl Lee2e463fb2025-04-17 11:22:22 -070099 agent: agent,
100 stdin: os.Stdin,
101 stdout: os.Stdout,
102 stderr: os.Stderr,
103 httpURL: httpURL,
104 chatMsgCh: make(chan chatMessage, 1),
105 termLogCh: make(chan string, 1),
106 pushedBranches: make(map[string]struct{}),
107 }
108}
109
David Crawshaw93fec602025-05-05 08:40:06 -0700110func (ui *TermUI) Run(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700111 fmt.Println(`🌐 ` + ui.httpURL + `/`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700112 fmt.Println(`šŸ’¬ type 'help' for help`)
113 fmt.Println()
114
115 // Start up the main terminal UI:
116 if err := ui.initializeTerminalUI(ctx); err != nil {
117 return err
118 }
119 go ui.receiveMessagesLoop(ctx)
120 if err := ui.inputLoop(ctx); err != nil {
121 return err
122 }
123 return nil
124}
125
David Crawshaw93fec602025-05-05 08:40:06 -0700126func (ui *TermUI) LogToolUse(resp *loop.AgentMessage) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700127 inputData := map[string]any{}
128 if err := json.Unmarshal([]byte(resp.ToolInput), &inputData); err != nil {
129 ui.AppendSystemMessage("error: %v", err)
130 return
131 }
132 buf := bytes.Buffer{}
133 if err := toolUseTmpl.Execute(&buf, map[string]any{"msg": resp, "input": inputData, "output": resp.ToolResult}); err != nil {
134 ui.AppendSystemMessage("error: %v", err)
135 return
136 }
137 ui.AppendSystemMessage("%s\n", buf.String())
138}
139
David Crawshaw93fec602025-05-05 08:40:06 -0700140func (ui *TermUI) receiveMessagesLoop(ctx context.Context) {
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700141 it := ui.agent.NewIterator(ctx, 0)
Earl Lee2e463fb2025-04-17 11:22:22 -0700142 bold := color.New(color.Bold).SprintFunc()
143 for {
144 select {
145 case <-ctx.Done():
146 return
147 default:
148 }
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700149 resp := it.Next()
150 if resp == nil {
151 return
152 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700153 // Typically a user message will start the thinking and a (top-level
154 // conversation) end of turn will stop it.
155 thinking := !(resp.EndOfTurn && resp.ParentConversationID == nil)
156
157 switch resp.Type {
158 case loop.AgentMessageType:
Josh Bleecher Snyder2978ab22025-04-30 10:29:32 -0700159 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "šŸ•“ļø ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700160 case loop.ToolUseMessageType:
161 ui.LogToolUse(resp)
162 case loop.ErrorMessageType:
163 ui.AppendSystemMessage("āŒ %s", resp.Content)
164 case loop.BudgetMessageType:
165 ui.AppendSystemMessage("šŸ’° %s", resp.Content)
166 case loop.AutoMessageType:
167 ui.AppendSystemMessage("🧐 %s", resp.Content)
168 case loop.UserMessageType:
Josh Bleecher Snyderc2d26102025-04-30 06:19:43 -0700169 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "🦸", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700170 case loop.CommitMessageType:
171 // Display each commit in the terminal
172 for _, commit := range resp.Commits {
173 if commit.PushedBranch != "" {
Sean McCullough43664f62025-04-20 16:13:03 -0700174 ui.AppendSystemMessage("šŸ”„ new commit: [%s] %s\npushed to: %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch))
Earl Lee2e463fb2025-04-17 11:22:22 -0700175
176 // Track the pushed branch in our map
177 ui.mu.Lock()
178 ui.pushedBranches[commit.PushedBranch] = struct{}{}
179 ui.mu.Unlock()
180 } else {
181 ui.AppendSystemMessage("šŸ”„ new commit: [%s] %s", commit.Hash[:8], commit.Subject)
182 }
183 }
184 default:
185 ui.AppendSystemMessage("āŒ Unexpected Message Type %s %v", resp.Type, resp)
186 }
187 }
188}
189
David Crawshaw93fec602025-05-05 08:40:06 -0700190func (ui *TermUI) inputLoop(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700191 for {
192 line, err := ui.trm.ReadLine()
193 if errors.Is(err, io.EOF) {
194 ui.AppendSystemMessage("\n")
195 line = "exit"
196 } else if err != nil {
197 return err
198 }
199
200 line = strings.TrimSpace(line)
201
202 switch line {
203 case "?", "help":
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700204 ui.AppendSystemMessage(`General use:
205Use chat to ask sketch to tackle a task or answer a question about this repo.
206
207Special commands:
208- help, ? : Show this help message
209- budget : Show original budget
210- usage, cost : Show current token usage and cost
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000211- browser, open, b : Open current conversation in browser
Earl Lee2e463fb2025-04-17 11:22:22 -0700212- stop, cancel, abort : Cancel the current operation
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700213- exit, quit, q : Exit sketch
214- ! <command> : Execute a shell command (e.g. !ls -la)`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700215 case "budget":
216 originalBudget := ui.agent.OriginalBudget()
217 ui.AppendSystemMessage("šŸ’° Budget summary:")
218 if originalBudget.MaxResponses > 0 {
219 ui.AppendSystemMessage("- Max responses: %d", originalBudget.MaxResponses)
220 }
221 if originalBudget.MaxWallTime > 0 {
222 ui.AppendSystemMessage("- Max wall time: %v", originalBudget.MaxWallTime)
223 }
224 ui.AppendSystemMessage("- Max total cost: %0.2f", originalBudget.MaxDollars)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000225 case "browser", "open", "b":
226 if ui.httpURL != "" {
227 ui.AppendSystemMessage("🌐 Opening %s in browser", ui.httpURL)
228 go ui.agent.OpenBrowser(ui.httpURL)
229 } else {
230 ui.AppendSystemMessage("āŒ No web URL available for this session")
231 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700232 case "usage", "cost":
233 totalUsage := ui.agent.TotalUsage()
234 ui.AppendSystemMessage("šŸ’° Current usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000235 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
236 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700237 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
238 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
239 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
240 case "bye", "exit", "q", "quit":
241 ui.trm.SetPrompt("")
242 // Display final usage stats
243 totalUsage := ui.agent.TotalUsage()
244 ui.AppendSystemMessage("šŸ’° Final usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000245 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
246 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700247 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
248 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
249 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
250
251 // Display pushed branches
252 ui.mu.Lock()
253 if len(ui.pushedBranches) > 0 {
254 // Convert map keys to a slice for display
255 branches := make([]string, 0, len(ui.pushedBranches))
256 for branch := range ui.pushedBranches {
257 branches = append(branches, branch)
258 }
259
Josh Bleecher Snyder8fdf7532025-05-06 00:56:12 +0000260 initialCommitRef := getShortSHA(ui.agent.InitialCommit())
Earl Lee2e463fb2025-04-17 11:22:22 -0700261 if len(branches) == 1 {
262 ui.AppendSystemMessage("\nšŸ”„ Branch pushed during session: %s", branches[0])
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000263 ui.AppendSystemMessage("šŸ’ To add those changes to your branch: git cherry-pick %s..%s", initialCommitRef, branches[0])
Earl Lee2e463fb2025-04-17 11:22:22 -0700264 } else {
265 ui.AppendSystemMessage("\nšŸ”„ Branches pushed during session:")
266 for _, branch := range branches {
267 ui.AppendSystemMessage("- %s", branch)
268 }
269 ui.AppendSystemMessage("\nšŸ’ To add all those changes to your branch:")
270 for _, branch := range branches {
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000271 ui.AppendSystemMessage("git cherry-pick %s..%s", initialCommitRef, branch)
Earl Lee2e463fb2025-04-17 11:22:22 -0700272 }
273 }
274 }
275 ui.mu.Unlock()
276
277 ui.AppendSystemMessage("\nšŸ‘‹ Goodbye!")
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000278 // Wait for all pending messages to be processed before exiting
279 ui.messageWaitGroup.Wait()
Earl Lee2e463fb2025-04-17 11:22:22 -0700280 return nil
281 case "stop", "cancel", "abort":
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000282 ui.agent.CancelTurn(fmt.Errorf("user canceled the operation"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700283 case "panic":
284 panic("user forced a panic")
285 default:
286 if line == "" {
287 continue
288 }
289 if strings.HasPrefix(line, "!") {
290 // Execute as shell command
291 line = line[1:] // remove the '!' prefix
292 sendToLLM := strings.HasPrefix(line, "!")
293 if sendToLLM {
294 line = line[1:] // remove the second '!'
295 }
296
297 // Create a cmd and run it
298 // TODO: ui.trm contains a mutex inside its write call.
299 // It is potentially safe to attach ui.trm directly to this
300 // cmd object's Stdout/Stderr and stream the output.
301 // That would make a big difference for, e.g. wget.
302 cmd := exec.Command("bash", "-c", line)
303 out, err := cmd.CombinedOutput()
304 ui.AppendSystemMessage("%s", out)
305 if err != nil {
306 ui.AppendSystemMessage("āŒ Command error: %v", err)
307 }
308 if sendToLLM {
309 // Send the command and its output to the agent
310 message := fmt.Sprintf("I ran the command: `%s`\nOutput:\n```\n%s```", line, out)
311 if err != nil {
312 message += fmt.Sprintf("\n\nError: %v", err)
313 }
314 ui.agent.UserMessage(ctx, message)
315 }
316 continue
317 }
318
319 // Send it to the LLM
320 // chatMsg := chatMessage{sender: "you", content: line}
321 // ui.sendChatMessage(chatMsg)
322 ui.agent.UserMessage(ctx, line)
323 }
324 }
325}
326
David Crawshaw93fec602025-05-05 08:40:06 -0700327func (ui *TermUI) updatePrompt(thinking bool) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700328 var t string
329
330 if thinking {
331 // Emoji don't seem to work here? Messes up my terminal.
332 t = "*"
333 }
Josh Bleecher Snyder23b6a2d2025-04-30 04:07:52 +0000334 p := fmt.Sprintf("%s ($%0.2f/%0.2f)%s> ",
335 ui.httpURL, ui.agent.TotalUsage().TotalCostUSD, ui.agent.OriginalBudget().MaxDollars, t)
Earl Lee2e463fb2025-04-17 11:22:22 -0700336 ui.trm.SetPrompt(p)
337}
338
David Crawshaw93fec602025-05-05 08:40:06 -0700339func (ui *TermUI) initializeTerminalUI(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700340 ui.mu.Lock()
341 defer ui.mu.Unlock()
342
343 if !term.IsTerminal(int(ui.stdin.Fd())) {
Philip Zeyligerc5b8ed42025-05-05 20:28:34 +0000344 return fmt.Errorf("this command requires terminal I/O when termui=true")
Earl Lee2e463fb2025-04-17 11:22:22 -0700345 }
346
347 oldState, err := term.MakeRaw(int(ui.stdin.Fd()))
348 if err != nil {
349 return err
350 }
351 ui.oldState = oldState
352 ui.trm = term.NewTerminal(ui.stdin, "")
353 width, height, err := term.GetSize(int(ui.stdin.Fd()))
354 if err != nil {
355 return fmt.Errorf("Error getting terminal size: %v\n", err)
356 }
357 ui.trm.SetSize(width, height)
358 // Handle terminal resizes...
359 sig := make(chan os.Signal, 1)
360 signal.Notify(sig, syscall.SIGWINCH)
361 go func() {
362 for {
363 <-sig
364 newWidth, newHeight, err := term.GetSize(int(ui.stdin.Fd()))
365 if err != nil {
366 continue
367 }
368 if newWidth != width || newHeight != height {
369 width, height = newWidth, newHeight
370 ui.trm.SetSize(width, height)
371 }
372 }
373 }()
374
375 ui.updatePrompt(false)
376
377 // This is the only place where we should call fe.trm.Write:
378 go func() {
Sean McCullougha4b19f82025-05-05 10:22:59 -0700379 var lastMsg *chatMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700380 for {
381 select {
382 case <-ctx.Done():
383 return
384 case msg := <-ui.chatMsgCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000385 func() {
386 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700387 // Update prompt before writing, because otherwise it doesn't redraw the prompt.
388 ui.updatePrompt(msg.thinking)
389 lastMsg = &msg
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000390 // Sometimes claude doesn't say anything when it runs tools.
391 // No need to output anything in that case.
392 if strings.TrimSpace(msg.content) == "" {
393 return
394 }
395 s := fmt.Sprintf("%s %s\n", msg.sender, msg.content)
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000396 ui.trm.Write([]byte(s))
397 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700398 case logLine := <-ui.termLogCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000399 func() {
400 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700401 if lastMsg != nil {
402 ui.updatePrompt(lastMsg.thinking)
403 } else {
404 ui.updatePrompt(false)
405 }
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000406 b := []byte(logLine + "\n")
407 ui.trm.Write(b)
408 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700409 }
410 }
411 }()
412
413 return nil
414}
415
David Crawshaw93fec602025-05-05 08:40:06 -0700416func (ui *TermUI) RestoreOldState() error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700417 ui.mu.Lock()
418 defer ui.mu.Unlock()
419 return term.Restore(int(ui.stdin.Fd()), ui.oldState)
420}
421
422// AppendChatMessage is for showing responses the user's request, conversational dialog etc
David Crawshaw93fec602025-05-05 08:40:06 -0700423func (ui *TermUI) AppendChatMessage(msg chatMessage) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000424 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700425 ui.chatMsgCh <- msg
426}
427
428// AppendSystemMessage is for debug information, errors and such that are not part of the "conversation" per se,
429// but still need to be shown to the user.
David Crawshaw93fec602025-05-05 08:40:06 -0700430func (ui *TermUI) AppendSystemMessage(fmtString string, args ...any) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000431 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700432 ui.termLogCh <- fmt.Sprintf(fmtString, args...)
433}
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000434
Josh Bleecher Snyder8fdf7532025-05-06 00:56:12 +0000435// getShortSHA returns the short SHA for the given git reference, falling back to the original SHA on error.
436func getShortSHA(sha string) string {
437 cmd := exec.Command("git", "rev-parse", "--short", sha)
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000438 shortSha, err := cmd.Output()
439 if err == nil {
440 shortStr := strings.TrimSpace(string(shortSha))
441 if shortStr != "" {
442 return shortStr
443 }
444 }
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000445 return sha
446}