blob: b14593d35b7e8a5918d4305666893fb90a0119c9 [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" -}}
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000050๐ŸŒฑ git branch: sketch/{{.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{}
162 if err := toolUseTmpl.Execute(&buf, map[string]any{"msg": resp, "input": inputData, "output": resp.ToolResult}); err != nil {
163 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:")
250 if originalBudget.MaxResponses > 0 {
251 ui.AppendSystemMessage("- Max responses: %d", originalBudget.MaxResponses)
252 }
253 if originalBudget.MaxWallTime > 0 {
254 ui.AppendSystemMessage("- Max wall time: %v", originalBudget.MaxWallTime)
255 }
256 ui.AppendSystemMessage("- Max total cost: %0.2f", originalBudget.MaxDollars)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000257 case "browser", "open", "b":
258 if ui.httpURL != "" {
259 ui.AppendSystemMessage("๐ŸŒ Opening %s in browser", ui.httpURL)
260 go ui.agent.OpenBrowser(ui.httpURL)
261 } else {
262 ui.AppendSystemMessage("โŒ No web URL available for this session")
263 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700264 case "usage", "cost":
265 totalUsage := ui.agent.TotalUsage()
266 ui.AppendSystemMessage("๐Ÿ’ฐ Current usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000267 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
268 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700269 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
270 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
271 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
272 case "bye", "exit", "q", "quit":
273 ui.trm.SetPrompt("")
274 // Display final usage stats
275 totalUsage := ui.agent.TotalUsage()
276 ui.AppendSystemMessage("๐Ÿ’ฐ Final usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000277 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
278 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700279 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
280 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
281 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
282
283 // Display pushed branches
284 ui.mu.Lock()
285 if len(ui.pushedBranches) > 0 {
286 // Convert map keys to a slice for display
287 branches := make([]string, 0, len(ui.pushedBranches))
288 for branch := range ui.pushedBranches {
289 branches = append(branches, branch)
290 }
291
Philip Zeyliger49edc922025-05-14 09:45:45 -0700292 initialCommitRef := getShortSHA(ui.agent.SketchGitBase())
Earl Lee2e463fb2025-04-17 11:22:22 -0700293 if len(branches) == 1 {
294 ui.AppendSystemMessage("\n๐Ÿ”„ Branch pushed during session: %s", branches[0])
Josh Bleecher Snyder956626d2025-05-15 21:24:07 +0000295 ui.AppendSystemMessage("๐Ÿ’ Cherry-pick those changes: git cherry-pick %s..%s", initialCommitRef, branches[0])
296 ui.AppendSystemMessage("๐Ÿ”€ Merge those changes: git merge %s", branches[0])
297 ui.AppendSystemMessage("๐Ÿ—‘๏ธ Delete the branch: git branch -D %s", branches[0])
Earl Lee2e463fb2025-04-17 11:22:22 -0700298 } else {
299 ui.AppendSystemMessage("\n๐Ÿ”„ Branches pushed during session:")
300 for _, branch := range branches {
301 ui.AppendSystemMessage("- %s", branch)
302 }
303 ui.AppendSystemMessage("\n๐Ÿ’ To add all those changes to your branch:")
304 for _, branch := range branches {
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000305 ui.AppendSystemMessage("git cherry-pick %s..%s", initialCommitRef, branch)
Earl Lee2e463fb2025-04-17 11:22:22 -0700306 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700307 ui.AppendSystemMessage("\n๐Ÿ”€ or:")
308 for _, branch := range branches {
309 ui.AppendSystemMessage("git merge %s", branch)
310 }
Josh Bleecher Snyder956626d2025-05-15 21:24:07 +0000311
312 ui.AppendSystemMessage("\n๐Ÿ—‘๏ธ To delete branches:")
313 for _, branch := range branches {
314 ui.AppendSystemMessage("git branch -D %s", branch)
315 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700316 }
317 }
318 ui.mu.Unlock()
319
320 ui.AppendSystemMessage("\n๐Ÿ‘‹ Goodbye!")
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000321 // Wait for all pending messages to be processed before exiting
322 ui.messageWaitGroup.Wait()
Earl Lee2e463fb2025-04-17 11:22:22 -0700323 return nil
324 case "stop", "cancel", "abort":
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000325 ui.agent.CancelTurn(fmt.Errorf("user canceled the operation"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700326 case "panic":
327 panic("user forced a panic")
328 default:
329 if line == "" {
330 continue
331 }
332 if strings.HasPrefix(line, "!") {
333 // Execute as shell command
334 line = line[1:] // remove the '!' prefix
335 sendToLLM := strings.HasPrefix(line, "!")
336 if sendToLLM {
337 line = line[1:] // remove the second '!'
338 }
339
340 // Create a cmd and run it
341 // TODO: ui.trm contains a mutex inside its write call.
342 // It is potentially safe to attach ui.trm directly to this
343 // cmd object's Stdout/Stderr and stream the output.
344 // That would make a big difference for, e.g. wget.
345 cmd := exec.Command("bash", "-c", line)
346 out, err := cmd.CombinedOutput()
347 ui.AppendSystemMessage("%s", out)
348 if err != nil {
349 ui.AppendSystemMessage("โŒ Command error: %v", err)
350 }
351 if sendToLLM {
352 // Send the command and its output to the agent
353 message := fmt.Sprintf("I ran the command: `%s`\nOutput:\n```\n%s```", line, out)
354 if err != nil {
355 message += fmt.Sprintf("\n\nError: %v", err)
356 }
357 ui.agent.UserMessage(ctx, message)
358 }
359 continue
360 }
361
362 // Send it to the LLM
363 // chatMsg := chatMessage{sender: "you", content: line}
364 // ui.sendChatMessage(chatMsg)
365 ui.agent.UserMessage(ctx, line)
366 }
367 }
368}
369
David Crawshaw93fec602025-05-05 08:40:06 -0700370func (ui *TermUI) updatePrompt(thinking bool) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700371 var t string
372
373 if thinking {
374 // Emoji don't seem to work here? Messes up my terminal.
375 t = "*"
376 }
Josh Bleecher Snyder23b6a2d2025-04-30 04:07:52 +0000377 p := fmt.Sprintf("%s ($%0.2f/%0.2f)%s> ",
378 ui.httpURL, ui.agent.TotalUsage().TotalCostUSD, ui.agent.OriginalBudget().MaxDollars, t)
Earl Lee2e463fb2025-04-17 11:22:22 -0700379 ui.trm.SetPrompt(p)
380}
381
David Crawshaw93fec602025-05-05 08:40:06 -0700382func (ui *TermUI) initializeTerminalUI(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700383 ui.mu.Lock()
384 defer ui.mu.Unlock()
385
386 if !term.IsTerminal(int(ui.stdin.Fd())) {
Philip Zeyligerc5b8ed42025-05-05 20:28:34 +0000387 return fmt.Errorf("this command requires terminal I/O when termui=true")
Earl Lee2e463fb2025-04-17 11:22:22 -0700388 }
389
390 oldState, err := term.MakeRaw(int(ui.stdin.Fd()))
391 if err != nil {
392 return err
393 }
394 ui.oldState = oldState
395 ui.trm = term.NewTerminal(ui.stdin, "")
396 width, height, err := term.GetSize(int(ui.stdin.Fd()))
397 if err != nil {
398 return fmt.Errorf("Error getting terminal size: %v\n", err)
399 }
400 ui.trm.SetSize(width, height)
401 // Handle terminal resizes...
402 sig := make(chan os.Signal, 1)
403 signal.Notify(sig, syscall.SIGWINCH)
404 go func() {
405 for {
406 <-sig
407 newWidth, newHeight, err := term.GetSize(int(ui.stdin.Fd()))
408 if err != nil {
409 continue
410 }
411 if newWidth != width || newHeight != height {
412 width, height = newWidth, newHeight
413 ui.trm.SetSize(width, height)
414 }
415 }
416 }()
417
418 ui.updatePrompt(false)
419
420 // This is the only place where we should call fe.trm.Write:
421 go func() {
Sean McCullougha4b19f82025-05-05 10:22:59 -0700422 var lastMsg *chatMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700423 for {
424 select {
425 case <-ctx.Done():
426 return
427 case msg := <-ui.chatMsgCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000428 func() {
429 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700430 // Update prompt before writing, because otherwise it doesn't redraw the prompt.
431 ui.updatePrompt(msg.thinking)
432 lastMsg = &msg
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000433 // Sometimes claude doesn't say anything when it runs tools.
434 // No need to output anything in that case.
435 if strings.TrimSpace(msg.content) == "" {
436 return
437 }
438 s := fmt.Sprintf("%s %s\n", msg.sender, msg.content)
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000439 ui.trm.Write([]byte(s))
440 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700441 case logLine := <-ui.termLogCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000442 func() {
443 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700444 if lastMsg != nil {
445 ui.updatePrompt(lastMsg.thinking)
446 } else {
447 ui.updatePrompt(false)
448 }
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000449 b := []byte(logLine + "\n")
450 ui.trm.Write(b)
451 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700452 }
453 }
454 }()
455
456 return nil
457}
458
David Crawshaw93fec602025-05-05 08:40:06 -0700459func (ui *TermUI) RestoreOldState() error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700460 ui.mu.Lock()
461 defer ui.mu.Unlock()
462 return term.Restore(int(ui.stdin.Fd()), ui.oldState)
463}
464
465// AppendChatMessage is for showing responses the user's request, conversational dialog etc
David Crawshaw93fec602025-05-05 08:40:06 -0700466func (ui *TermUI) AppendChatMessage(msg chatMessage) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000467 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700468 ui.chatMsgCh <- msg
469}
470
471// AppendSystemMessage is for debug information, errors and such that are not part of the "conversation" per se,
472// but still need to be shown to the user.
David Crawshaw93fec602025-05-05 08:40:06 -0700473func (ui *TermUI) AppendSystemMessage(fmtString string, args ...any) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000474 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700475 ui.termLogCh <- fmt.Sprintf(fmtString, args...)
476}
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000477
Josh Bleecher Snyder8fdf7532025-05-06 00:56:12 +0000478// getShortSHA returns the short SHA for the given git reference, falling back to the original SHA on error.
479func getShortSHA(sha string) string {
480 cmd := exec.Command("git", "rev-parse", "--short", sha)
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000481 shortSha, err := cmd.Output()
482 if err == nil {
483 shortStr := strings.TrimSpace(string(shortSha))
484 if shortStr != "" {
485 return shortStr
486 }
487 }
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000488 return sha
489}