blob: 014619019f6e3d66425d21b372e1372a25d581f7 [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 "str_replace_editor" -}}
54 โœ๏ธ {{.input.file_path -}}
55{{else if eq .msg.ToolName "codereview" -}}
56 ๐Ÿ› Running automated code review, may be slow
Sean McCullough485afc62025-04-28 14:28:39 -070057{{else if eq .msg.ToolName "multiplechoice" -}}
58 ๐Ÿ“ {{.input.question}}
59{{ range .input.responseOptions -}}
60 - {{ .caption}}: {{.responseText}}
61{{end -}}
Josh Bleecher Snyder2d081192025-05-29 13:46:04 +000062{{else if eq .msg.ToolName "browser_navigate" -}}
63 ๐ŸŒ {{.input.url -}}
64{{else if eq .msg.ToolName "browser_click" -}}
65 ๐Ÿ–ฑ๏ธ {{.input.selector -}}
66{{else if eq .msg.ToolName "browser_type" -}}
67 โŒจ๏ธ {{.input.selector}}: "{{.input.text}}"
68{{else if eq .msg.ToolName "browser_wait_for" -}}
69 โณ {{.input.selector -}}
70{{else if eq .msg.ToolName "browser_get_text" -}}
71 ๐Ÿ“– {{.input.selector -}}
72{{else if eq .msg.ToolName "browser_eval" -}}
73 ๐Ÿ“ฑ {{.input.expression -}}
74{{else if eq .msg.ToolName "browser_take_screenshot" -}}
75 ๐Ÿ“ธ Screenshot
76{{else if eq .msg.ToolName "browser_scroll_into_view" -}}
77 ๐Ÿ”„ {{.input.selector -}}
78{{else if eq .msg.ToolName "browser_resize" -}}
79 ๐Ÿ–ผ๏ธ {{.input.width}}x{{.input.height -}}
80{{else if eq .msg.ToolName "browser_read_image" -}}
81 ๐Ÿ–ผ๏ธ {{.input.path -}}
82{{else if eq .msg.ToolName "browser_recent_console_logs" -}}
83 ๐Ÿ“œ Console logs
84{{else if eq .msg.ToolName "browser_clear_console_logs" -}}
85 ๐Ÿงน Clear console logs
Earl Lee2e463fb2025-04-17 11:22:22 -070086{{else -}}
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000087 ๐Ÿ› ๏ธ {{ .msg.ToolName}}: {{.msg.ToolInput -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070088{{end -}}
89`
90 toolUseTmpl = template.Must(template.New("tool_use").Parse(toolUseTemplTxt))
91)
92
David Crawshaw93fec602025-05-05 08:40:06 -070093type TermUI struct {
Earl Lee2e463fb2025-04-17 11:22:22 -070094 stdin *os.File
95 stdout *os.File
96 stderr *os.File
97
98 agent loop.CodingAgent
99 httpURL string
100
101 trm *term.Terminal
102
103 // the chatMsgCh channel is for "conversation" messages, like responses to user input
104 // from the LLM, or output from executing slash-commands issued by the user.
105 chatMsgCh chan chatMessage
106
107 // the log channel is for secondary messages, like logging, errors, and debug information
108 // from local and remove subproceses.
109 termLogCh chan string
110
111 // protects following
112 mu sync.Mutex
113 oldState *term.State
114 // Tracks branches that were pushed during the session
115 pushedBranches map[string]struct{}
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000116
117 // Pending message count, for graceful shutdown
118 messageWaitGroup sync.WaitGroup
Earl Lee2e463fb2025-04-17 11:22:22 -0700119}
120
121type chatMessage struct {
122 idx int
123 sender string
124 content string
125 thinking bool
126}
127
David Crawshaw93fec602025-05-05 08:40:06 -0700128func New(agent loop.CodingAgent, httpURL string) *TermUI {
129 return &TermUI{
Earl Lee2e463fb2025-04-17 11:22:22 -0700130 agent: agent,
131 stdin: os.Stdin,
132 stdout: os.Stdout,
133 stderr: os.Stderr,
134 httpURL: httpURL,
135 chatMsgCh: make(chan chatMessage, 1),
136 termLogCh: make(chan string, 1),
137 pushedBranches: make(map[string]struct{}),
138 }
139}
140
David Crawshaw93fec602025-05-05 08:40:06 -0700141func (ui *TermUI) Run(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700142 fmt.Println(`๐ŸŒ ` + ui.httpURL + `/`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700143 fmt.Println(`๐Ÿ’ฌ type 'help' for help`)
144 fmt.Println()
145
146 // Start up the main terminal UI:
147 if err := ui.initializeTerminalUI(ctx); err != nil {
148 return err
149 }
150 go ui.receiveMessagesLoop(ctx)
151 if err := ui.inputLoop(ctx); err != nil {
152 return err
153 }
154 return nil
155}
156
David Crawshaw93fec602025-05-05 08:40:06 -0700157func (ui *TermUI) LogToolUse(resp *loop.AgentMessage) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700158 inputData := map[string]any{}
159 if err := json.Unmarshal([]byte(resp.ToolInput), &inputData); err != nil {
160 ui.AppendSystemMessage("error: %v", err)
161 return
162 }
163 buf := bytes.Buffer{}
164 if err := toolUseTmpl.Execute(&buf, map[string]any{"msg": resp, "input": inputData, "output": resp.ToolResult}); err != nil {
165 ui.AppendSystemMessage("error: %v", err)
166 return
167 }
168 ui.AppendSystemMessage("%s\n", buf.String())
169}
170
David Crawshaw93fec602025-05-05 08:40:06 -0700171func (ui *TermUI) receiveMessagesLoop(ctx context.Context) {
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700172 it := ui.agent.NewIterator(ctx, 0)
Earl Lee2e463fb2025-04-17 11:22:22 -0700173 bold := color.New(color.Bold).SprintFunc()
174 for {
175 select {
176 case <-ctx.Done():
177 return
178 default:
179 }
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700180 resp := it.Next()
181 if resp == nil {
182 return
183 }
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000184 if resp.HideOutput {
185 continue
186 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700187 // Typically a user message will start the thinking and a (top-level
188 // conversation) end of turn will stop it.
189 thinking := !(resp.EndOfTurn && resp.ParentConversationID == nil)
190
191 switch resp.Type {
192 case loop.AgentMessageType:
Josh Bleecher Snyder2978ab22025-04-30 10:29:32 -0700193 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐Ÿ•ด๏ธ ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700194 case loop.ToolUseMessageType:
195 ui.LogToolUse(resp)
196 case loop.ErrorMessageType:
197 ui.AppendSystemMessage("โŒ %s", resp.Content)
198 case loop.BudgetMessageType:
199 ui.AppendSystemMessage("๐Ÿ’ฐ %s", resp.Content)
200 case loop.AutoMessageType:
201 ui.AppendSystemMessage("๐Ÿง %s", resp.Content)
202 case loop.UserMessageType:
Josh Bleecher Snyderc2d26102025-04-30 06:19:43 -0700203 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐Ÿฆธ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700204 case loop.CommitMessageType:
205 // Display each commit in the terminal
206 for _, commit := range resp.Commits {
207 if commit.PushedBranch != "" {
Sean McCullough43664f62025-04-20 16:13:03 -0700208 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s\npushed to: %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch))
Earl Lee2e463fb2025-04-17 11:22:22 -0700209
210 // Track the pushed branch in our map
211 ui.mu.Lock()
212 ui.pushedBranches[commit.PushedBranch] = struct{}{}
213 ui.mu.Unlock()
214 } else {
215 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s", commit.Hash[:8], commit.Subject)
216 }
217 }
218 default:
219 ui.AppendSystemMessage("โŒ Unexpected Message Type %s %v", resp.Type, resp)
220 }
221 }
222}
223
David Crawshaw93fec602025-05-05 08:40:06 -0700224func (ui *TermUI) inputLoop(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700225 for {
226 line, err := ui.trm.ReadLine()
227 if errors.Is(err, io.EOF) {
228 ui.AppendSystemMessage("\n")
229 line = "exit"
230 } else if err != nil {
231 return err
232 }
233
234 line = strings.TrimSpace(line)
235
236 switch line {
237 case "?", "help":
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700238 ui.AppendSystemMessage(`General use:
239Use chat to ask sketch to tackle a task or answer a question about this repo.
240
241Special commands:
242- help, ? : Show this help message
243- budget : Show original budget
244- usage, cost : Show current token usage and cost
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000245- browser, open, b : Open current conversation in browser
Earl Lee2e463fb2025-04-17 11:22:22 -0700246- stop, cancel, abort : Cancel the current operation
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700247- exit, quit, q : Exit sketch
248- ! <command> : Execute a shell command (e.g. !ls -la)`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700249 case "budget":
250 originalBudget := ui.agent.OriginalBudget()
251 ui.AppendSystemMessage("๐Ÿ’ฐ Budget summary:")
252 if originalBudget.MaxResponses > 0 {
253 ui.AppendSystemMessage("- Max responses: %d", originalBudget.MaxResponses)
254 }
255 if originalBudget.MaxWallTime > 0 {
256 ui.AppendSystemMessage("- Max wall time: %v", originalBudget.MaxWallTime)
257 }
258 ui.AppendSystemMessage("- Max total cost: %0.2f", originalBudget.MaxDollars)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000259 case "browser", "open", "b":
260 if ui.httpURL != "" {
261 ui.AppendSystemMessage("๐ŸŒ Opening %s in browser", ui.httpURL)
262 go ui.agent.OpenBrowser(ui.httpURL)
263 } else {
264 ui.AppendSystemMessage("โŒ No web URL available for this session")
265 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700266 case "usage", "cost":
267 totalUsage := ui.agent.TotalUsage()
268 ui.AppendSystemMessage("๐Ÿ’ฐ Current usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000269 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
270 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700271 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
272 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
273 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
274 case "bye", "exit", "q", "quit":
275 ui.trm.SetPrompt("")
276 // Display final usage stats
277 totalUsage := ui.agent.TotalUsage()
278 ui.AppendSystemMessage("๐Ÿ’ฐ Final usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000279 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
280 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700281 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
282 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
283 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
284
285 // Display pushed branches
286 ui.mu.Lock()
287 if len(ui.pushedBranches) > 0 {
288 // Convert map keys to a slice for display
289 branches := make([]string, 0, len(ui.pushedBranches))
290 for branch := range ui.pushedBranches {
291 branches = append(branches, branch)
292 }
293
Philip Zeyliger49edc922025-05-14 09:45:45 -0700294 initialCommitRef := getShortSHA(ui.agent.SketchGitBase())
Earl Lee2e463fb2025-04-17 11:22:22 -0700295 if len(branches) == 1 {
296 ui.AppendSystemMessage("\n๐Ÿ”„ Branch pushed during session: %s", branches[0])
Josh Bleecher Snyder956626d2025-05-15 21:24:07 +0000297 ui.AppendSystemMessage("๐Ÿ’ Cherry-pick those changes: git cherry-pick %s..%s", initialCommitRef, branches[0])
298 ui.AppendSystemMessage("๐Ÿ”€ Merge those changes: git merge %s", branches[0])
299 ui.AppendSystemMessage("๐Ÿ—‘๏ธ Delete the branch: git branch -D %s", branches[0])
Earl Lee2e463fb2025-04-17 11:22:22 -0700300 } else {
301 ui.AppendSystemMessage("\n๐Ÿ”„ Branches pushed during session:")
302 for _, branch := range branches {
303 ui.AppendSystemMessage("- %s", branch)
304 }
305 ui.AppendSystemMessage("\n๐Ÿ’ To add all those changes to your branch:")
306 for _, branch := range branches {
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000307 ui.AppendSystemMessage("git cherry-pick %s..%s", initialCommitRef, branch)
Earl Lee2e463fb2025-04-17 11:22:22 -0700308 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700309 ui.AppendSystemMessage("\n๐Ÿ”€ or:")
310 for _, branch := range branches {
311 ui.AppendSystemMessage("git merge %s", branch)
312 }
Josh Bleecher Snyder956626d2025-05-15 21:24:07 +0000313
314 ui.AppendSystemMessage("\n๐Ÿ—‘๏ธ To delete branches:")
315 for _, branch := range branches {
316 ui.AppendSystemMessage("git branch -D %s", branch)
317 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700318 }
319 }
320 ui.mu.Unlock()
321
322 ui.AppendSystemMessage("\n๐Ÿ‘‹ Goodbye!")
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000323 // Wait for all pending messages to be processed before exiting
324 ui.messageWaitGroup.Wait()
Earl Lee2e463fb2025-04-17 11:22:22 -0700325 return nil
326 case "stop", "cancel", "abort":
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000327 ui.agent.CancelTurn(fmt.Errorf("user canceled the operation"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700328 case "panic":
329 panic("user forced a panic")
330 default:
331 if line == "" {
332 continue
333 }
334 if strings.HasPrefix(line, "!") {
335 // Execute as shell command
336 line = line[1:] // remove the '!' prefix
337 sendToLLM := strings.HasPrefix(line, "!")
338 if sendToLLM {
339 line = line[1:] // remove the second '!'
340 }
341
342 // Create a cmd and run it
343 // TODO: ui.trm contains a mutex inside its write call.
344 // It is potentially safe to attach ui.trm directly to this
345 // cmd object's Stdout/Stderr and stream the output.
346 // That would make a big difference for, e.g. wget.
347 cmd := exec.Command("bash", "-c", line)
348 out, err := cmd.CombinedOutput()
349 ui.AppendSystemMessage("%s", out)
350 if err != nil {
351 ui.AppendSystemMessage("โŒ Command error: %v", err)
352 }
353 if sendToLLM {
354 // Send the command and its output to the agent
355 message := fmt.Sprintf("I ran the command: `%s`\nOutput:\n```\n%s```", line, out)
356 if err != nil {
357 message += fmt.Sprintf("\n\nError: %v", err)
358 }
359 ui.agent.UserMessage(ctx, message)
360 }
361 continue
362 }
363
364 // Send it to the LLM
365 // chatMsg := chatMessage{sender: "you", content: line}
366 // ui.sendChatMessage(chatMsg)
367 ui.agent.UserMessage(ctx, line)
368 }
369 }
370}
371
David Crawshaw93fec602025-05-05 08:40:06 -0700372func (ui *TermUI) updatePrompt(thinking bool) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700373 var t string
374
375 if thinking {
376 // Emoji don't seem to work here? Messes up my terminal.
377 t = "*"
378 }
Josh Bleecher Snyder23b6a2d2025-04-30 04:07:52 +0000379 p := fmt.Sprintf("%s ($%0.2f/%0.2f)%s> ",
380 ui.httpURL, ui.agent.TotalUsage().TotalCostUSD, ui.agent.OriginalBudget().MaxDollars, t)
Earl Lee2e463fb2025-04-17 11:22:22 -0700381 ui.trm.SetPrompt(p)
382}
383
David Crawshaw93fec602025-05-05 08:40:06 -0700384func (ui *TermUI) initializeTerminalUI(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700385 ui.mu.Lock()
386 defer ui.mu.Unlock()
387
388 if !term.IsTerminal(int(ui.stdin.Fd())) {
Philip Zeyligerc5b8ed42025-05-05 20:28:34 +0000389 return fmt.Errorf("this command requires terminal I/O when termui=true")
Earl Lee2e463fb2025-04-17 11:22:22 -0700390 }
391
392 oldState, err := term.MakeRaw(int(ui.stdin.Fd()))
393 if err != nil {
394 return err
395 }
396 ui.oldState = oldState
397 ui.trm = term.NewTerminal(ui.stdin, "")
398 width, height, err := term.GetSize(int(ui.stdin.Fd()))
399 if err != nil {
400 return fmt.Errorf("Error getting terminal size: %v\n", err)
401 }
402 ui.trm.SetSize(width, height)
403 // Handle terminal resizes...
404 sig := make(chan os.Signal, 1)
405 signal.Notify(sig, syscall.SIGWINCH)
406 go func() {
407 for {
408 <-sig
409 newWidth, newHeight, err := term.GetSize(int(ui.stdin.Fd()))
410 if err != nil {
411 continue
412 }
413 if newWidth != width || newHeight != height {
414 width, height = newWidth, newHeight
415 ui.trm.SetSize(width, height)
416 }
417 }
418 }()
419
420 ui.updatePrompt(false)
421
422 // This is the only place where we should call fe.trm.Write:
423 go func() {
Sean McCullougha4b19f82025-05-05 10:22:59 -0700424 var lastMsg *chatMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700425 for {
426 select {
427 case <-ctx.Done():
428 return
429 case msg := <-ui.chatMsgCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000430 func() {
431 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700432 // Update prompt before writing, because otherwise it doesn't redraw the prompt.
433 ui.updatePrompt(msg.thinking)
434 lastMsg = &msg
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000435 // Sometimes claude doesn't say anything when it runs tools.
436 // No need to output anything in that case.
437 if strings.TrimSpace(msg.content) == "" {
438 return
439 }
440 s := fmt.Sprintf("%s %s\n", msg.sender, msg.content)
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000441 ui.trm.Write([]byte(s))
442 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700443 case logLine := <-ui.termLogCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000444 func() {
445 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700446 if lastMsg != nil {
447 ui.updatePrompt(lastMsg.thinking)
448 } else {
449 ui.updatePrompt(false)
450 }
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000451 b := []byte(logLine + "\n")
452 ui.trm.Write(b)
453 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700454 }
455 }
456 }()
457
458 return nil
459}
460
David Crawshaw93fec602025-05-05 08:40:06 -0700461func (ui *TermUI) RestoreOldState() error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700462 ui.mu.Lock()
463 defer ui.mu.Unlock()
464 return term.Restore(int(ui.stdin.Fd()), ui.oldState)
465}
466
467// AppendChatMessage is for showing responses the user's request, conversational dialog etc
David Crawshaw93fec602025-05-05 08:40:06 -0700468func (ui *TermUI) AppendChatMessage(msg chatMessage) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000469 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700470 ui.chatMsgCh <- msg
471}
472
473// AppendSystemMessage is for debug information, errors and such that are not part of the "conversation" per se,
474// but still need to be shown to the user.
David Crawshaw93fec602025-05-05 08:40:06 -0700475func (ui *TermUI) AppendSystemMessage(fmtString string, args ...any) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000476 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700477 ui.termLogCh <- fmt.Sprintf(fmtString, args...)
478}
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000479
Josh Bleecher Snyder8fdf7532025-05-06 00:56:12 +0000480// getShortSHA returns the short SHA for the given git reference, falling back to the original SHA on error.
481func getShortSHA(sha string) string {
482 cmd := exec.Command("git", "rev-parse", "--short", sha)
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000483 shortSha, err := cmd.Output()
484 if err == nil {
485 shortStr := strings.TrimSpace(string(shortSha))
486 if shortStr != "" {
487 return shortStr
488 }
489 }
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000490 return sha
491}