blob: 24f663b14dc62b33922bf8decd3110f8db55299a [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 -}}
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -070034{{else if eq .msg.ToolName "todo_read" -}}
35 ๐Ÿ“‹ Reading todo list
36{{else if eq .msg.ToolName "todo_write" }}
37{{range .input.tasks}}{{if eq .status "queued"}}โšช{{else if eq .status "in-progress"}}๐Ÿฆ‰{{else if eq .status "completed"}}โœ…{{end}} {{.task}}
38{{end}}
Earl Lee2e463fb2025-04-17 11:22:22 -070039{{else if eq .msg.ToolName "keyword_search" -}}
Josh Bleecher Snyder453a62f2025-05-01 10:14:33 -070040 ๐Ÿ” {{ .input.query}}: {{.input.search_terms -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070041{{else if eq .msg.ToolName "bash" -}}
Philip Zeyligerb60f0f22025-04-23 18:19:32 +000042 ๐Ÿ–ฅ๏ธ{{if .input.background}}๐Ÿ”„{{end}} {{ .input.command -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070043{{else if eq .msg.ToolName "patch" -}}
44 โŒจ๏ธ {{.input.path -}}
45{{else if eq .msg.ToolName "done" -}}
46{{/* nothing to show here, the agent will write more in its next message */}}
47{{else if eq .msg.ToolName "title" -}}
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000048๐Ÿท๏ธ {{.input.title}}
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +000049{{else if eq .msg.ToolName "precommit" -}}
Philip Zeyligerbe7802a2025-06-04 20:15:25 +000050๐ŸŒฑ git branch: {{.branch_prefix}}{{.input.branch_name}}
Josh Bleecher Snyder74d690e2025-05-14 18:16:03 -070051{{else if eq .msg.ToolName "about_sketch" -}}
52๐Ÿ“š About Sketch
Earl Lee2e463fb2025-04-17 11:22:22 -070053{{else if eq .msg.ToolName "codereview" -}}
54 ๐Ÿ› Running automated code review, may be slow
Sean McCullough485afc62025-04-28 14:28:39 -070055{{else if eq .msg.ToolName "multiplechoice" -}}
56 ๐Ÿ“ {{.input.question}}
57{{ range .input.responseOptions -}}
58 - {{ .caption}}: {{.responseText}}
59{{end -}}
Josh Bleecher Snyder2d081192025-05-29 13:46:04 +000060{{else if eq .msg.ToolName "browser_navigate" -}}
61 ๐ŸŒ {{.input.url -}}
62{{else if eq .msg.ToolName "browser_click" -}}
63 ๐Ÿ–ฑ๏ธ {{.input.selector -}}
64{{else if eq .msg.ToolName "browser_type" -}}
65 โŒจ๏ธ {{.input.selector}}: "{{.input.text}}"
66{{else if eq .msg.ToolName "browser_wait_for" -}}
67 โณ {{.input.selector -}}
68{{else if eq .msg.ToolName "browser_get_text" -}}
69 ๐Ÿ“– {{.input.selector -}}
70{{else if eq .msg.ToolName "browser_eval" -}}
71 ๐Ÿ“ฑ {{.input.expression -}}
72{{else if eq .msg.ToolName "browser_take_screenshot" -}}
73 ๐Ÿ“ธ Screenshot
74{{else if eq .msg.ToolName "browser_scroll_into_view" -}}
75 ๐Ÿ”„ {{.input.selector -}}
76{{else if eq .msg.ToolName "browser_resize" -}}
77 ๐Ÿ–ผ๏ธ {{.input.width}}x{{.input.height -}}
78{{else if eq .msg.ToolName "browser_read_image" -}}
79 ๐Ÿ–ผ๏ธ {{.input.path -}}
80{{else if eq .msg.ToolName "browser_recent_console_logs" -}}
81 ๐Ÿ“œ Console logs
82{{else if eq .msg.ToolName "browser_clear_console_logs" -}}
83 ๐Ÿงน Clear console logs
Earl Lee2e463fb2025-04-17 11:22:22 -070084{{else -}}
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000085 ๐Ÿ› ๏ธ {{ .msg.ToolName}}: {{.msg.ToolInput -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070086{{end -}}
87`
88 toolUseTmpl = template.Must(template.New("tool_use").Parse(toolUseTemplTxt))
89)
90
David Crawshaw93fec602025-05-05 08:40:06 -070091type TermUI struct {
Earl Lee2e463fb2025-04-17 11:22:22 -070092 stdin *os.File
93 stdout *os.File
94 stderr *os.File
95
96 agent loop.CodingAgent
97 httpURL string
98
99 trm *term.Terminal
100
101 // the chatMsgCh channel is for "conversation" messages, like responses to user input
102 // from the LLM, or output from executing slash-commands issued by the user.
103 chatMsgCh chan chatMessage
104
105 // the log channel is for secondary messages, like logging, errors, and debug information
106 // from local and remove subproceses.
107 termLogCh chan string
108
109 // protects following
110 mu sync.Mutex
111 oldState *term.State
112 // Tracks branches that were pushed during the session
113 pushedBranches map[string]struct{}
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000114
115 // Pending message count, for graceful shutdown
116 messageWaitGroup sync.WaitGroup
Earl Lee2e463fb2025-04-17 11:22:22 -0700117}
118
119type chatMessage struct {
120 idx int
121 sender string
122 content string
123 thinking bool
124}
125
David Crawshaw93fec602025-05-05 08:40:06 -0700126func New(agent loop.CodingAgent, httpURL string) *TermUI {
127 return &TermUI{
Earl Lee2e463fb2025-04-17 11:22:22 -0700128 agent: agent,
129 stdin: os.Stdin,
130 stdout: os.Stdout,
131 stderr: os.Stderr,
132 httpURL: httpURL,
133 chatMsgCh: make(chan chatMessage, 1),
134 termLogCh: make(chan string, 1),
135 pushedBranches: make(map[string]struct{}),
136 }
137}
138
David Crawshaw93fec602025-05-05 08:40:06 -0700139func (ui *TermUI) Run(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700140 fmt.Println(`๐ŸŒ ` + ui.httpURL + `/`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700141 fmt.Println(`๐Ÿ’ฌ type 'help' for help`)
142 fmt.Println()
143
144 // Start up the main terminal UI:
145 if err := ui.initializeTerminalUI(ctx); err != nil {
146 return err
147 }
148 go ui.receiveMessagesLoop(ctx)
149 if err := ui.inputLoop(ctx); err != nil {
150 return err
151 }
152 return nil
153}
154
David Crawshaw93fec602025-05-05 08:40:06 -0700155func (ui *TermUI) LogToolUse(resp *loop.AgentMessage) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700156 inputData := map[string]any{}
157 if err := json.Unmarshal([]byte(resp.ToolInput), &inputData); err != nil {
158 ui.AppendSystemMessage("error: %v", err)
159 return
160 }
161 buf := bytes.Buffer{}
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000162 if err := toolUseTmpl.Execute(&buf, map[string]any{"msg": resp, "input": inputData, "output": resp.ToolResult, "branch_prefix": ui.agent.BranchPrefix()}); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700163 ui.AppendSystemMessage("error: %v", err)
164 return
165 }
166 ui.AppendSystemMessage("%s\n", buf.String())
167}
168
David Crawshaw93fec602025-05-05 08:40:06 -0700169func (ui *TermUI) receiveMessagesLoop(ctx context.Context) {
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700170 it := ui.agent.NewIterator(ctx, 0)
Earl Lee2e463fb2025-04-17 11:22:22 -0700171 bold := color.New(color.Bold).SprintFunc()
172 for {
173 select {
174 case <-ctx.Done():
175 return
176 default:
177 }
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700178 resp := it.Next()
179 if resp == nil {
180 return
181 }
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000182 if resp.HideOutput {
183 continue
184 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700185 // Typically a user message will start the thinking and a (top-level
186 // conversation) end of turn will stop it.
187 thinking := !(resp.EndOfTurn && resp.ParentConversationID == nil)
188
189 switch resp.Type {
190 case loop.AgentMessageType:
Josh Bleecher Snyder2978ab22025-04-30 10:29:32 -0700191 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐Ÿ•ด๏ธ ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700192 case loop.ToolUseMessageType:
193 ui.LogToolUse(resp)
194 case loop.ErrorMessageType:
195 ui.AppendSystemMessage("โŒ %s", resp.Content)
196 case loop.BudgetMessageType:
197 ui.AppendSystemMessage("๐Ÿ’ฐ %s", resp.Content)
198 case loop.AutoMessageType:
199 ui.AppendSystemMessage("๐Ÿง %s", resp.Content)
200 case loop.UserMessageType:
Josh Bleecher Snyderc2d26102025-04-30 06:19:43 -0700201 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐Ÿฆธ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700202 case loop.CommitMessageType:
203 // Display each commit in the terminal
204 for _, commit := range resp.Commits {
205 if commit.PushedBranch != "" {
Sean McCullough43664f62025-04-20 16:13:03 -0700206 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s\npushed to: %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch))
Earl Lee2e463fb2025-04-17 11:22:22 -0700207
208 // Track the pushed branch in our map
209 ui.mu.Lock()
210 ui.pushedBranches[commit.PushedBranch] = struct{}{}
211 ui.mu.Unlock()
212 } else {
213 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s", commit.Hash[:8], commit.Subject)
214 }
215 }
216 default:
217 ui.AppendSystemMessage("โŒ Unexpected Message Type %s %v", resp.Type, resp)
218 }
219 }
220}
221
David Crawshaw93fec602025-05-05 08:40:06 -0700222func (ui *TermUI) inputLoop(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700223 for {
224 line, err := ui.trm.ReadLine()
225 if errors.Is(err, io.EOF) {
226 ui.AppendSystemMessage("\n")
227 line = "exit"
228 } else if err != nil {
229 return err
230 }
231
232 line = strings.TrimSpace(line)
233
234 switch line {
235 case "?", "help":
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700236 ui.AppendSystemMessage(`General use:
237Use chat to ask sketch to tackle a task or answer a question about this repo.
238
239Special commands:
240- help, ? : Show this help message
241- budget : Show original budget
242- usage, cost : Show current token usage and cost
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000243- browser, open, b : Open current conversation in browser
Earl Lee2e463fb2025-04-17 11:22:22 -0700244- stop, cancel, abort : Cancel the current operation
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700245- exit, quit, q : Exit sketch
246- ! <command> : Execute a shell command (e.g. !ls -la)`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700247 case "budget":
248 originalBudget := ui.agent.OriginalBudget()
249 ui.AppendSystemMessage("๐Ÿ’ฐ Budget summary:")
Philip Zeyligere6c294d2025-06-04 16:55:21 +0000250
Earl Lee2e463fb2025-04-17 11:22:22 -0700251 ui.AppendSystemMessage("- Max total cost: %0.2f", originalBudget.MaxDollars)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000252 case "browser", "open", "b":
253 if ui.httpURL != "" {
254 ui.AppendSystemMessage("๐ŸŒ Opening %s in browser", ui.httpURL)
255 go ui.agent.OpenBrowser(ui.httpURL)
256 } else {
257 ui.AppendSystemMessage("โŒ No web URL available for this session")
258 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700259 case "usage", "cost":
260 totalUsage := ui.agent.TotalUsage()
261 ui.AppendSystemMessage("๐Ÿ’ฐ Current usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000262 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
263 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700264 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
265 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
266 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
267 case "bye", "exit", "q", "quit":
268 ui.trm.SetPrompt("")
269 // Display final usage stats
270 totalUsage := ui.agent.TotalUsage()
271 ui.AppendSystemMessage("๐Ÿ’ฐ Final usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000272 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
273 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700274 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
275 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
276 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
277
278 // Display pushed branches
279 ui.mu.Lock()
280 if len(ui.pushedBranches) > 0 {
281 // Convert map keys to a slice for display
282 branches := make([]string, 0, len(ui.pushedBranches))
283 for branch := range ui.pushedBranches {
284 branches = append(branches, branch)
285 }
286
Philip Zeyliger49edc922025-05-14 09:45:45 -0700287 initialCommitRef := getShortSHA(ui.agent.SketchGitBase())
Earl Lee2e463fb2025-04-17 11:22:22 -0700288 if len(branches) == 1 {
289 ui.AppendSystemMessage("\n๐Ÿ”„ Branch pushed during session: %s", branches[0])
Josh Bleecher Snyder956626d2025-05-15 21:24:07 +0000290 ui.AppendSystemMessage("๐Ÿ’ Cherry-pick those changes: git cherry-pick %s..%s", initialCommitRef, branches[0])
291 ui.AppendSystemMessage("๐Ÿ”€ Merge those changes: git merge %s", branches[0])
292 ui.AppendSystemMessage("๐Ÿ—‘๏ธ Delete the branch: git branch -D %s", branches[0])
Earl Lee2e463fb2025-04-17 11:22:22 -0700293 } else {
294 ui.AppendSystemMessage("\n๐Ÿ”„ Branches pushed during session:")
295 for _, branch := range branches {
296 ui.AppendSystemMessage("- %s", branch)
297 }
298 ui.AppendSystemMessage("\n๐Ÿ’ To add all those changes to your branch:")
299 for _, branch := range branches {
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000300 ui.AppendSystemMessage("git cherry-pick %s..%s", initialCommitRef, branch)
Earl Lee2e463fb2025-04-17 11:22:22 -0700301 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700302 ui.AppendSystemMessage("\n๐Ÿ”€ or:")
303 for _, branch := range branches {
304 ui.AppendSystemMessage("git merge %s", branch)
305 }
Josh Bleecher Snyder956626d2025-05-15 21:24:07 +0000306
307 ui.AppendSystemMessage("\n๐Ÿ—‘๏ธ To delete branches:")
308 for _, branch := range branches {
309 ui.AppendSystemMessage("git branch -D %s", branch)
310 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700311 }
312 }
313 ui.mu.Unlock()
314
315 ui.AppendSystemMessage("\n๐Ÿ‘‹ Goodbye!")
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000316 // Wait for all pending messages to be processed before exiting
317 ui.messageWaitGroup.Wait()
Earl Lee2e463fb2025-04-17 11:22:22 -0700318 return nil
319 case "stop", "cancel", "abort":
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000320 ui.agent.CancelTurn(fmt.Errorf("user canceled the operation"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700321 case "panic":
322 panic("user forced a panic")
323 default:
324 if line == "" {
325 continue
326 }
327 if strings.HasPrefix(line, "!") {
328 // Execute as shell command
329 line = line[1:] // remove the '!' prefix
330 sendToLLM := strings.HasPrefix(line, "!")
331 if sendToLLM {
332 line = line[1:] // remove the second '!'
333 }
334
335 // Create a cmd and run it
336 // TODO: ui.trm contains a mutex inside its write call.
337 // It is potentially safe to attach ui.trm directly to this
338 // cmd object's Stdout/Stderr and stream the output.
339 // That would make a big difference for, e.g. wget.
340 cmd := exec.Command("bash", "-c", line)
341 out, err := cmd.CombinedOutput()
342 ui.AppendSystemMessage("%s", out)
343 if err != nil {
344 ui.AppendSystemMessage("โŒ Command error: %v", err)
345 }
346 if sendToLLM {
347 // Send the command and its output to the agent
348 message := fmt.Sprintf("I ran the command: `%s`\nOutput:\n```\n%s```", line, out)
349 if err != nil {
350 message += fmt.Sprintf("\n\nError: %v", err)
351 }
352 ui.agent.UserMessage(ctx, message)
353 }
354 continue
355 }
356
357 // Send it to the LLM
358 // chatMsg := chatMessage{sender: "you", content: line}
359 // ui.sendChatMessage(chatMsg)
360 ui.agent.UserMessage(ctx, line)
361 }
362 }
363}
364
David Crawshaw93fec602025-05-05 08:40:06 -0700365func (ui *TermUI) updatePrompt(thinking bool) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700366 var t string
Earl Lee2e463fb2025-04-17 11:22:22 -0700367 if thinking {
368 // Emoji don't seem to work here? Messes up my terminal.
369 t = "*"
370 }
Josh Bleecher Snyder03376232025-06-05 14:29:48 -0700371 var money string
372 if totalCost := ui.agent.TotalUsage().TotalCostUSD; totalCost > 0 {
373 money = fmt.Sprintf("($%0.2f/%0.2f)", totalCost, ui.agent.OriginalBudget().MaxDollars)
374 }
375 p := fmt.Sprintf("%s %s%s> ", ui.httpURL, money, t)
Earl Lee2e463fb2025-04-17 11:22:22 -0700376 ui.trm.SetPrompt(p)
377}
378
David Crawshaw93fec602025-05-05 08:40:06 -0700379func (ui *TermUI) initializeTerminalUI(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700380 ui.mu.Lock()
381 defer ui.mu.Unlock()
382
383 if !term.IsTerminal(int(ui.stdin.Fd())) {
Philip Zeyligerc5b8ed42025-05-05 20:28:34 +0000384 return fmt.Errorf("this command requires terminal I/O when termui=true")
Earl Lee2e463fb2025-04-17 11:22:22 -0700385 }
386
387 oldState, err := term.MakeRaw(int(ui.stdin.Fd()))
388 if err != nil {
389 return err
390 }
391 ui.oldState = oldState
392 ui.trm = term.NewTerminal(ui.stdin, "")
393 width, height, err := term.GetSize(int(ui.stdin.Fd()))
394 if err != nil {
395 return fmt.Errorf("Error getting terminal size: %v\n", err)
396 }
397 ui.trm.SetSize(width, height)
398 // Handle terminal resizes...
399 sig := make(chan os.Signal, 1)
400 signal.Notify(sig, syscall.SIGWINCH)
401 go func() {
402 for {
403 <-sig
404 newWidth, newHeight, err := term.GetSize(int(ui.stdin.Fd()))
405 if err != nil {
406 continue
407 }
408 if newWidth != width || newHeight != height {
409 width, height = newWidth, newHeight
410 ui.trm.SetSize(width, height)
411 }
412 }
413 }()
414
415 ui.updatePrompt(false)
416
417 // This is the only place where we should call fe.trm.Write:
418 go func() {
Sean McCullougha4b19f82025-05-05 10:22:59 -0700419 var lastMsg *chatMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700420 for {
421 select {
422 case <-ctx.Done():
423 return
424 case msg := <-ui.chatMsgCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000425 func() {
426 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700427 // Update prompt before writing, because otherwise it doesn't redraw the prompt.
428 ui.updatePrompt(msg.thinking)
429 lastMsg = &msg
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000430 // Sometimes claude doesn't say anything when it runs tools.
431 // No need to output anything in that case.
432 if strings.TrimSpace(msg.content) == "" {
433 return
434 }
435 s := fmt.Sprintf("%s %s\n", msg.sender, msg.content)
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000436 ui.trm.Write([]byte(s))
437 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700438 case logLine := <-ui.termLogCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000439 func() {
440 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700441 if lastMsg != nil {
442 ui.updatePrompt(lastMsg.thinking)
443 } else {
444 ui.updatePrompt(false)
445 }
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000446 b := []byte(logLine + "\n")
447 ui.trm.Write(b)
448 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700449 }
450 }
451 }()
452
453 return nil
454}
455
David Crawshaw93fec602025-05-05 08:40:06 -0700456func (ui *TermUI) RestoreOldState() error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700457 ui.mu.Lock()
458 defer ui.mu.Unlock()
459 return term.Restore(int(ui.stdin.Fd()), ui.oldState)
460}
461
462// AppendChatMessage is for showing responses the user's request, conversational dialog etc
David Crawshaw93fec602025-05-05 08:40:06 -0700463func (ui *TermUI) AppendChatMessage(msg chatMessage) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000464 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700465 ui.chatMsgCh <- msg
466}
467
468// AppendSystemMessage is for debug information, errors and such that are not part of the "conversation" per se,
469// but still need to be shown to the user.
David Crawshaw93fec602025-05-05 08:40:06 -0700470func (ui *TermUI) AppendSystemMessage(fmtString string, args ...any) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000471 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700472 ui.termLogCh <- fmt.Sprintf(fmtString, args...)
473}
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000474
Josh Bleecher Snyder8fdf7532025-05-06 00:56:12 +0000475// getShortSHA returns the short SHA for the given git reference, falling back to the original SHA on error.
476func getShortSHA(sha string) string {
477 cmd := exec.Command("git", "rev-parse", "--short", sha)
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000478 shortSha, err := cmd.Output()
479 if err == nil {
480 shortStr := strings.TrimSpace(string(shortSha))
481 if shortStr != "" {
482 return shortStr
483 }
484 }
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000485 return sha
486}