blob: af6376d30b0772870a003528415deee3a44f15cb [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"
philip.zeyliger6d3de482025-06-10 19:38:14 -070013 "regexp"
Earl Lee2e463fb2025-04-17 11:22:22 -070014 "strings"
15 "sync"
16 "syscall"
17 "text/template"
18 "time"
19
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +000020 "github.com/dustin/go-humanize"
Earl Lee2e463fb2025-04-17 11:22:22 -070021 "github.com/fatih/color"
22 "golang.org/x/term"
23 "sketch.dev/loop"
24)
25
26var (
27 // toolUseTemplTxt defines how tool invocations appear in the terminal UI.
28 // Keep this template in sync with the tools defined in claudetool package
29 // and registered in loop/agent.go.
30 // Add formatting for new tools as they are created.
31 // 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 -070032 toolUseTemplTxt = `{{if .msg.ToolError}}ใ€ฐ๏ธ {{end -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070033{{if eq .msg.ToolName "think" -}}
34 ๐Ÿง  {{.input.thoughts -}}
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -070035{{else if eq .msg.ToolName "todo_read" -}}
36 ๐Ÿ“‹ Reading todo list
37{{else if eq .msg.ToolName "todo_write" }}
38{{range .input.tasks}}{{if eq .status "queued"}}โšช{{else if eq .status "in-progress"}}๐Ÿฆ‰{{else if eq .status "completed"}}โœ…{{end}} {{.task}}
39{{end}}
Earl Lee2e463fb2025-04-17 11:22:22 -070040{{else if eq .msg.ToolName "keyword_search" -}}
Josh Bleecher Snyder453a62f2025-05-01 10:14:33 -070041 ๐Ÿ” {{ .input.query}}: {{.input.search_terms -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070042{{else if eq .msg.ToolName "bash" -}}
Philip Zeyligerb60f0f22025-04-23 18:19:32 +000043 ๐Ÿ–ฅ๏ธ{{if .input.background}}๐Ÿ”„{{end}} {{ .input.command -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070044{{else if eq .msg.ToolName "patch" -}}
45 โŒจ๏ธ {{.input.path -}}
46{{else if eq .msg.ToolName "done" -}}
47{{/* nothing to show here, the agent will write more in its next message */}}
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -070048{{else if eq .msg.ToolName "set-slug" -}}
49๐ŸŒ {{.input.slug}}
50{{else if eq .msg.ToolName "commit-message-style" -}}
51๐ŸŒฑ learn git commit message style
Josh Bleecher Snyder74d690e2025-05-14 18:16:03 -070052{{else if eq .msg.ToolName "about_sketch" -}}
53๐Ÿ“š About Sketch
Earl Lee2e463fb2025-04-17 11:22:22 -070054{{else if eq .msg.ToolName "codereview" -}}
55 ๐Ÿ› Running automated code review, may be slow
Sean McCullough485afc62025-04-28 14:28:39 -070056{{else if eq .msg.ToolName "multiplechoice" -}}
57 ๐Ÿ“ {{.input.question}}
58{{ range .input.responseOptions -}}
59 - {{ .caption}}: {{.responseText}}
60{{end -}}
Josh Bleecher Snyder2d081192025-05-29 13:46:04 +000061{{else if eq .msg.ToolName "browser_navigate" -}}
62 ๐ŸŒ {{.input.url -}}
63{{else if eq .msg.ToolName "browser_click" -}}
64 ๐Ÿ–ฑ๏ธ {{.input.selector -}}
65{{else if eq .msg.ToolName "browser_type" -}}
66 โŒจ๏ธ {{.input.selector}}: "{{.input.text}}"
67{{else if eq .msg.ToolName "browser_wait_for" -}}
68 โณ {{.input.selector -}}
69{{else if eq .msg.ToolName "browser_get_text" -}}
70 ๐Ÿ“– {{.input.selector -}}
71{{else if eq .msg.ToolName "browser_eval" -}}
72 ๐Ÿ“ฑ {{.input.expression -}}
73{{else if eq .msg.ToolName "browser_take_screenshot" -}}
74 ๐Ÿ“ธ Screenshot
75{{else if eq .msg.ToolName "browser_scroll_into_view" -}}
76 ๐Ÿ”„ {{.input.selector -}}
77{{else if eq .msg.ToolName "browser_resize" -}}
78 ๐Ÿ–ผ๏ธ {{.input.width}}x{{.input.height -}}
Philip Zeyliger542bda32025-06-11 18:31:03 -070079{{else if eq .msg.ToolName "read_image" -}}
Josh Bleecher Snyder2d081192025-05-29 13:46:04 +000080 ๐Ÿ–ผ๏ธ {{.input.path -}}
81{{else if eq .msg.ToolName "browser_recent_console_logs" -}}
82 ๐Ÿ“œ Console logs
83{{else if eq .msg.ToolName "browser_clear_console_logs" -}}
84 ๐Ÿงน Clear console logs
Philip Zeyligerc17ffe32025-06-05 19:49:13 -070085{{else if eq .msg.ToolName "list_recent_sketch_sessions" -}}
86 ๐Ÿ“š List recent sketch sessions
87{{else if eq .msg.ToolName "read_sketch_session" -}}
88 ๐Ÿ“– Read session {{.input.session_id}}
Earl Lee2e463fb2025-04-17 11:22:22 -070089{{else -}}
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000090 ๐Ÿ› ๏ธ {{ .msg.ToolName}}: {{.msg.ToolInput -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070091{{end -}}
92`
93 toolUseTmpl = template.Must(template.New("tool_use").Parse(toolUseTemplTxt))
94)
95
David Crawshaw93fec602025-05-05 08:40:06 -070096type TermUI struct {
Earl Lee2e463fb2025-04-17 11:22:22 -070097 stdin *os.File
98 stdout *os.File
99 stderr *os.File
100
101 agent loop.CodingAgent
102 httpURL string
103
104 trm *term.Terminal
105
106 // the chatMsgCh channel is for "conversation" messages, like responses to user input
107 // from the LLM, or output from executing slash-commands issued by the user.
108 chatMsgCh chan chatMessage
109
110 // the log channel is for secondary messages, like logging, errors, and debug information
111 // from local and remove subproceses.
112 termLogCh chan string
113
114 // protects following
115 mu sync.Mutex
116 oldState *term.State
117 // Tracks branches that were pushed during the session
118 pushedBranches map[string]struct{}
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000119
120 // Pending message count, for graceful shutdown
121 messageWaitGroup sync.WaitGroup
Earl Lee2e463fb2025-04-17 11:22:22 -0700122}
123
124type chatMessage struct {
125 idx int
126 sender string
127 content string
128 thinking bool
129}
130
David Crawshaw93fec602025-05-05 08:40:06 -0700131func New(agent loop.CodingAgent, httpURL string) *TermUI {
132 return &TermUI{
Earl Lee2e463fb2025-04-17 11:22:22 -0700133 agent: agent,
134 stdin: os.Stdin,
135 stdout: os.Stdout,
136 stderr: os.Stderr,
137 httpURL: httpURL,
138 chatMsgCh: make(chan chatMessage, 1),
139 termLogCh: make(chan string, 1),
140 pushedBranches: make(map[string]struct{}),
141 }
142}
143
David Crawshaw93fec602025-05-05 08:40:06 -0700144func (ui *TermUI) Run(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700145 fmt.Println(`๐ŸŒ ` + ui.httpURL + `/`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700146 fmt.Println(`๐Ÿ’ฌ type 'help' for help`)
147 fmt.Println()
148
149 // Start up the main terminal UI:
150 if err := ui.initializeTerminalUI(ctx); err != nil {
151 return err
152 }
153 go ui.receiveMessagesLoop(ctx)
154 if err := ui.inputLoop(ctx); err != nil {
155 return err
156 }
157 return nil
158}
159
David Crawshaw93fec602025-05-05 08:40:06 -0700160func (ui *TermUI) LogToolUse(resp *loop.AgentMessage) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700161 inputData := map[string]any{}
162 if err := json.Unmarshal([]byte(resp.ToolInput), &inputData); err != nil {
163 ui.AppendSystemMessage("error: %v", err)
164 return
165 }
166 buf := bytes.Buffer{}
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000167 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 -0700168 ui.AppendSystemMessage("error: %v", err)
169 return
170 }
171 ui.AppendSystemMessage("%s\n", buf.String())
172}
173
David Crawshaw93fec602025-05-05 08:40:06 -0700174func (ui *TermUI) receiveMessagesLoop(ctx context.Context) {
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700175 it := ui.agent.NewIterator(ctx, 0)
Earl Lee2e463fb2025-04-17 11:22:22 -0700176 bold := color.New(color.Bold).SprintFunc()
177 for {
178 select {
179 case <-ctx.Done():
180 return
181 default:
182 }
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700183 resp := it.Next()
184 if resp == nil {
185 return
186 }
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000187 if resp.HideOutput {
188 continue
189 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700190 // Typically a user message will start the thinking and a (top-level
191 // conversation) end of turn will stop it.
192 thinking := !(resp.EndOfTurn && resp.ParentConversationID == nil)
193
194 switch resp.Type {
195 case loop.AgentMessageType:
Josh Bleecher Snyder2978ab22025-04-30 10:29:32 -0700196 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐Ÿ•ด๏ธ ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700197 case loop.ToolUseMessageType:
198 ui.LogToolUse(resp)
199 case loop.ErrorMessageType:
200 ui.AppendSystemMessage("โŒ %s", resp.Content)
201 case loop.BudgetMessageType:
202 ui.AppendSystemMessage("๐Ÿ’ฐ %s", resp.Content)
203 case loop.AutoMessageType:
204 ui.AppendSystemMessage("๐Ÿง %s", resp.Content)
205 case loop.UserMessageType:
Josh Bleecher Snyderc2d26102025-04-30 06:19:43 -0700206 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐Ÿฆธ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700207 case loop.CommitMessageType:
208 // Display each commit in the terminal
209 for _, commit := range resp.Commits {
210 if commit.PushedBranch != "" {
philip.zeyliger6d3de482025-06-10 19:38:14 -0700211 // Check if we should show a GitHub link
212 githubURL := ui.getGitHubBranchURL(commit.PushedBranch)
213 if githubURL != "" {
214 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s\npushed to: %s\n๐Ÿ”— %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch), githubURL)
215 } else {
216 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s\npushed to: %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch))
217 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700218
219 // Track the pushed branch in our map
220 ui.mu.Lock()
221 ui.pushedBranches[commit.PushedBranch] = struct{}{}
222 ui.mu.Unlock()
223 } else {
224 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s", commit.Hash[:8], commit.Subject)
225 }
226 }
227 default:
228 ui.AppendSystemMessage("โŒ Unexpected Message Type %s %v", resp.Type, resp)
229 }
230 }
231}
232
David Crawshaw93fec602025-05-05 08:40:06 -0700233func (ui *TermUI) inputLoop(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700234 for {
235 line, err := ui.trm.ReadLine()
236 if errors.Is(err, io.EOF) {
237 ui.AppendSystemMessage("\n")
238 line = "exit"
239 } else if err != nil {
240 return err
241 }
242
243 line = strings.TrimSpace(line)
244
245 switch line {
246 case "?", "help":
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700247 ui.AppendSystemMessage(`General use:
248Use chat to ask sketch to tackle a task or answer a question about this repo.
249
250Special commands:
251- help, ? : Show this help message
252- budget : Show original budget
253- usage, cost : Show current token usage and cost
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000254- browser, open, b : Open current conversation in browser
Earl Lee2e463fb2025-04-17 11:22:22 -0700255- stop, cancel, abort : Cancel the current operation
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700256- exit, quit, q : Exit sketch
257- ! <command> : Execute a shell command (e.g. !ls -la)`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700258 case "budget":
259 originalBudget := ui.agent.OriginalBudget()
260 ui.AppendSystemMessage("๐Ÿ’ฐ Budget summary:")
Philip Zeyligere6c294d2025-06-04 16:55:21 +0000261
Earl Lee2e463fb2025-04-17 11:22:22 -0700262 ui.AppendSystemMessage("- Max total cost: %0.2f", originalBudget.MaxDollars)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000263 case "browser", "open", "b":
264 if ui.httpURL != "" {
265 ui.AppendSystemMessage("๐ŸŒ Opening %s in browser", ui.httpURL)
266 go ui.agent.OpenBrowser(ui.httpURL)
267 } else {
268 ui.AppendSystemMessage("โŒ No web URL available for this session")
269 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700270 case "usage", "cost":
271 totalUsage := ui.agent.TotalUsage()
272 ui.AppendSystemMessage("๐Ÿ’ฐ Current usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000273 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
274 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700275 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
276 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
277 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
278 case "bye", "exit", "q", "quit":
279 ui.trm.SetPrompt("")
280 // Display final usage stats
281 totalUsage := ui.agent.TotalUsage()
282 ui.AppendSystemMessage("๐Ÿ’ฐ Final usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000283 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
284 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700285 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
286 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
287 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
288
289 // Display pushed branches
290 ui.mu.Lock()
291 if len(ui.pushedBranches) > 0 {
292 // Convert map keys to a slice for display
293 branches := make([]string, 0, len(ui.pushedBranches))
294 for branch := range ui.pushedBranches {
295 branches = append(branches, branch)
296 }
297
Philip Zeyliger49edc922025-05-14 09:45:45 -0700298 initialCommitRef := getShortSHA(ui.agent.SketchGitBase())
Earl Lee2e463fb2025-04-17 11:22:22 -0700299 if len(branches) == 1 {
300 ui.AppendSystemMessage("\n๐Ÿ”„ Branch pushed during session: %s", branches[0])
philip.zeyliger6d3de482025-06-10 19:38:14 -0700301 // Add GitHub link if available
302 if githubURL := ui.getGitHubBranchURL(branches[0]); githubURL != "" {
303 ui.AppendSystemMessage("๐Ÿ”— %s", githubURL)
304 }
Josh Bleecher Snyder956626d2025-05-15 21:24:07 +0000305 ui.AppendSystemMessage("๐Ÿ’ Cherry-pick those changes: git cherry-pick %s..%s", initialCommitRef, branches[0])
306 ui.AppendSystemMessage("๐Ÿ”€ Merge those changes: git merge %s", branches[0])
307 ui.AppendSystemMessage("๐Ÿ—‘๏ธ Delete the branch: git branch -D %s", branches[0])
Earl Lee2e463fb2025-04-17 11:22:22 -0700308 } else {
309 ui.AppendSystemMessage("\n๐Ÿ”„ Branches pushed during session:")
310 for _, branch := range branches {
311 ui.AppendSystemMessage("- %s", branch)
philip.zeyliger6d3de482025-06-10 19:38:14 -0700312 // Add GitHub link if available
313 if githubURL := ui.getGitHubBranchURL(branch); githubURL != "" {
314 ui.AppendSystemMessage(" ๐Ÿ”— %s", githubURL)
315 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700316 }
317 ui.AppendSystemMessage("\n๐Ÿ’ To add all those changes to your branch:")
318 for _, branch := range branches {
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000319 ui.AppendSystemMessage("git cherry-pick %s..%s", initialCommitRef, branch)
Earl Lee2e463fb2025-04-17 11:22:22 -0700320 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700321 ui.AppendSystemMessage("\n๐Ÿ”€ or:")
322 for _, branch := range branches {
323 ui.AppendSystemMessage("git merge %s", branch)
324 }
Josh Bleecher Snyder956626d2025-05-15 21:24:07 +0000325
326 ui.AppendSystemMessage("\n๐Ÿ—‘๏ธ To delete branches:")
327 for _, branch := range branches {
328 ui.AppendSystemMessage("git branch -D %s", branch)
329 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700330 }
331 }
332 ui.mu.Unlock()
333
334 ui.AppendSystemMessage("\n๐Ÿ‘‹ Goodbye!")
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000335 // Wait for all pending messages to be processed before exiting
336 ui.messageWaitGroup.Wait()
Earl Lee2e463fb2025-04-17 11:22:22 -0700337 return nil
338 case "stop", "cancel", "abort":
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000339 ui.agent.CancelTurn(fmt.Errorf("user canceled the operation"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700340 case "panic":
341 panic("user forced a panic")
342 default:
343 if line == "" {
344 continue
345 }
346 if strings.HasPrefix(line, "!") {
347 // Execute as shell command
348 line = line[1:] // remove the '!' prefix
349 sendToLLM := strings.HasPrefix(line, "!")
350 if sendToLLM {
351 line = line[1:] // remove the second '!'
352 }
353
354 // Create a cmd and run it
355 // TODO: ui.trm contains a mutex inside its write call.
356 // It is potentially safe to attach ui.trm directly to this
357 // cmd object's Stdout/Stderr and stream the output.
358 // That would make a big difference for, e.g. wget.
359 cmd := exec.Command("bash", "-c", line)
360 out, err := cmd.CombinedOutput()
361 ui.AppendSystemMessage("%s", out)
362 if err != nil {
363 ui.AppendSystemMessage("โŒ Command error: %v", err)
364 }
365 if sendToLLM {
366 // Send the command and its output to the agent
367 message := fmt.Sprintf("I ran the command: `%s`\nOutput:\n```\n%s```", line, out)
368 if err != nil {
369 message += fmt.Sprintf("\n\nError: %v", err)
370 }
371 ui.agent.UserMessage(ctx, message)
372 }
373 continue
374 }
375
376 // Send it to the LLM
377 // chatMsg := chatMessage{sender: "you", content: line}
378 // ui.sendChatMessage(chatMsg)
379 ui.agent.UserMessage(ctx, line)
380 }
381 }
382}
383
David Crawshaw93fec602025-05-05 08:40:06 -0700384func (ui *TermUI) updatePrompt(thinking bool) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700385 var t string
Earl Lee2e463fb2025-04-17 11:22:22 -0700386 if thinking {
387 // Emoji don't seem to work here? Messes up my terminal.
388 t = "*"
389 }
Josh Bleecher Snyder03376232025-06-05 14:29:48 -0700390 var money string
391 if totalCost := ui.agent.TotalUsage().TotalCostUSD; totalCost > 0 {
392 money = fmt.Sprintf("($%0.2f/%0.2f)", totalCost, ui.agent.OriginalBudget().MaxDollars)
393 }
394 p := fmt.Sprintf("%s %s%s> ", ui.httpURL, money, t)
Earl Lee2e463fb2025-04-17 11:22:22 -0700395 ui.trm.SetPrompt(p)
396}
397
David Crawshaw93fec602025-05-05 08:40:06 -0700398func (ui *TermUI) initializeTerminalUI(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700399 ui.mu.Lock()
400 defer ui.mu.Unlock()
401
402 if !term.IsTerminal(int(ui.stdin.Fd())) {
Philip Zeyligerc5b8ed42025-05-05 20:28:34 +0000403 return fmt.Errorf("this command requires terminal I/O when termui=true")
Earl Lee2e463fb2025-04-17 11:22:22 -0700404 }
405
406 oldState, err := term.MakeRaw(int(ui.stdin.Fd()))
407 if err != nil {
408 return err
409 }
410 ui.oldState = oldState
411 ui.trm = term.NewTerminal(ui.stdin, "")
412 width, height, err := term.GetSize(int(ui.stdin.Fd()))
413 if err != nil {
414 return fmt.Errorf("Error getting terminal size: %v\n", err)
415 }
416 ui.trm.SetSize(width, height)
417 // Handle terminal resizes...
418 sig := make(chan os.Signal, 1)
419 signal.Notify(sig, syscall.SIGWINCH)
420 go func() {
421 for {
422 <-sig
423 newWidth, newHeight, err := term.GetSize(int(ui.stdin.Fd()))
424 if err != nil {
425 continue
426 }
427 if newWidth != width || newHeight != height {
428 width, height = newWidth, newHeight
429 ui.trm.SetSize(width, height)
430 }
431 }
432 }()
433
434 ui.updatePrompt(false)
435
436 // This is the only place where we should call fe.trm.Write:
437 go func() {
Sean McCullougha4b19f82025-05-05 10:22:59 -0700438 var lastMsg *chatMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700439 for {
440 select {
441 case <-ctx.Done():
442 return
443 case msg := <-ui.chatMsgCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000444 func() {
445 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700446 // Update prompt before writing, because otherwise it doesn't redraw the prompt.
447 ui.updatePrompt(msg.thinking)
448 lastMsg = &msg
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000449 // Sometimes claude doesn't say anything when it runs tools.
450 // No need to output anything in that case.
451 if strings.TrimSpace(msg.content) == "" {
452 return
453 }
454 s := fmt.Sprintf("%s %s\n", msg.sender, msg.content)
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000455 ui.trm.Write([]byte(s))
456 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700457 case logLine := <-ui.termLogCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000458 func() {
459 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700460 if lastMsg != nil {
461 ui.updatePrompt(lastMsg.thinking)
462 } else {
463 ui.updatePrompt(false)
464 }
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000465 b := []byte(logLine + "\n")
466 ui.trm.Write(b)
467 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700468 }
469 }
470 }()
471
472 return nil
473}
474
David Crawshaw93fec602025-05-05 08:40:06 -0700475func (ui *TermUI) RestoreOldState() error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700476 ui.mu.Lock()
477 defer ui.mu.Unlock()
478 return term.Restore(int(ui.stdin.Fd()), ui.oldState)
479}
480
481// AppendChatMessage is for showing responses the user's request, conversational dialog etc
David Crawshaw93fec602025-05-05 08:40:06 -0700482func (ui *TermUI) AppendChatMessage(msg chatMessage) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000483 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700484 ui.chatMsgCh <- msg
485}
486
487// AppendSystemMessage is for debug information, errors and such that are not part of the "conversation" per se,
488// but still need to be shown to the user.
David Crawshaw93fec602025-05-05 08:40:06 -0700489func (ui *TermUI) AppendSystemMessage(fmtString string, args ...any) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000490 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700491 ui.termLogCh <- fmt.Sprintf(fmtString, args...)
492}
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000493
Josh Bleecher Snyder8fdf7532025-05-06 00:56:12 +0000494// getShortSHA returns the short SHA for the given git reference, falling back to the original SHA on error.
495func getShortSHA(sha string) string {
496 cmd := exec.Command("git", "rev-parse", "--short", sha)
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000497 shortSha, err := cmd.Output()
498 if err == nil {
499 shortStr := strings.TrimSpace(string(shortSha))
500 if shortStr != "" {
501 return shortStr
502 }
503 }
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000504 return sha
505}
philip.zeyliger6d3de482025-06-10 19:38:14 -0700506
507// isGitHubRepo checks if the git origin URL is a GitHub repository
508func (ui *TermUI) isGitHubRepo() bool {
509 gitOrigin := ui.agent.GitOrigin()
510 if gitOrigin == "" {
511 return false
512 }
513
514 // Common GitHub URL patterns
515 patterns := []string{
516 `^https://github\.com/[^/]+/[^/\s.]+(?:\.git)?`,
517 `^git@github\.com:[^/]+/[^/\s.]+(?:\.git)?`,
518 `^git://github\.com/[^/]+/[^/\s.]+(?:\.git)?`,
519 }
520
521 for _, pattern := range patterns {
522 if matched, _ := regexp.MatchString(pattern, gitOrigin); matched {
523 return true
524 }
525 }
526 return false
527}
528
529// getGitHubBranchURL generates a GitHub branch URL if conditions are met
530func (ui *TermUI) getGitHubBranchURL(branchName string) string {
531 if !ui.agent.LinkToGitHub() || branchName == "" {
532 return ""
533 }
534
535 gitOrigin := ui.agent.GitOrigin()
536 if gitOrigin == "" || !ui.isGitHubRepo() {
537 return ""
538 }
539
540 // Extract owner and repo from GitHub URL
541 patterns := []string{
542 `^https://github\.com/([^/]+)/([^/\s.]+)(?:\.git)?`,
543 `^git@github\.com:([^/]+)/([^/\s.]+)(?:\.git)?`,
544 `^git://github\.com/([^/]+)/([^/\s.]+)(?:\.git)?`,
545 }
546
547 for _, pattern := range patterns {
548 re := regexp.MustCompile(pattern)
549 matches := re.FindStringSubmatch(gitOrigin)
550 if len(matches) == 3 {
551 owner := matches[1]
552 repo := matches[2]
553 return fmt.Sprintf("https://github.com/%s/%s/tree/%s", owner, repo, branchName)
554 }
555 }
556 return ""
557}