blob: b3b85a343053fd41e1d571bdfd4b8a317fdcc10e [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" -}}
Josh Bleecher Snyder17b2fd92025-07-09 22:47:13 +000043 ๐Ÿ–ฅ๏ธ {{if .input.background}}๐Ÿฅท {{end}}{{if .input.slow_ok}}๐Ÿข {{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 Snyder74d690e2025-05-14 18:16:03 -070048{{else if eq .msg.ToolName "about_sketch" -}}
49๐Ÿ“š About Sketch
Earl Lee2e463fb2025-04-17 11:22:22 -070050{{else if eq .msg.ToolName "codereview" -}}
51 ๐Ÿ› Running automated code review, may be slow
Josh Bleecher Snyder2d081192025-05-29 13:46:04 +000052{{else if eq .msg.ToolName "browser_navigate" -}}
53 ๐ŸŒ {{.input.url -}}
Josh Bleecher Snyder2d081192025-05-29 13:46:04 +000054{{else if eq .msg.ToolName "browser_eval" -}}
55 ๐Ÿ“ฑ {{.input.expression -}}
56{{else if eq .msg.ToolName "browser_take_screenshot" -}}
57 ๐Ÿ“ธ Screenshot
Philip Zeyliger542bda32025-06-11 18:31:03 -070058{{else if eq .msg.ToolName "read_image" -}}
Josh Bleecher Snyder2d081192025-05-29 13:46:04 +000059 ๐Ÿ–ผ๏ธ {{.input.path -}}
60{{else if eq .msg.ToolName "browser_recent_console_logs" -}}
61 ๐Ÿ“œ Console logs
62{{else if eq .msg.ToolName "browser_clear_console_logs" -}}
63 ๐Ÿงน Clear console logs
Philip Zeyligerc17ffe32025-06-05 19:49:13 -070064{{else if eq .msg.ToolName "list_recent_sketch_sessions" -}}
65 ๐Ÿ“š List recent sketch sessions
66{{else if eq .msg.ToolName "read_sketch_session" -}}
67 ๐Ÿ“– Read session {{.input.session_id}}
Earl Lee2e463fb2025-04-17 11:22:22 -070068{{else -}}
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000069 ๐Ÿ› ๏ธ {{ .msg.ToolName}}: {{.msg.ToolInput -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070070{{end -}}
71`
72 toolUseTmpl = template.Must(template.New("tool_use").Parse(toolUseTemplTxt))
73)
74
David Crawshaw93fec602025-05-05 08:40:06 -070075type TermUI struct {
Earl Lee2e463fb2025-04-17 11:22:22 -070076 stdin *os.File
77 stdout *os.File
78 stderr *os.File
79
80 agent loop.CodingAgent
81 httpURL string
82
83 trm *term.Terminal
84
85 // the chatMsgCh channel is for "conversation" messages, like responses to user input
86 // from the LLM, or output from executing slash-commands issued by the user.
87 chatMsgCh chan chatMessage
88
89 // the log channel is for secondary messages, like logging, errors, and debug information
90 // from local and remove subproceses.
91 termLogCh chan string
92
93 // protects following
94 mu sync.Mutex
95 oldState *term.State
96 // Tracks branches that were pushed during the session
97 pushedBranches map[string]struct{}
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +000098
99 // Pending message count, for graceful shutdown
100 messageWaitGroup sync.WaitGroup
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000101
102 currentSlug string
103 titlePushed bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700104}
105
106type chatMessage struct {
107 idx int
108 sender string
109 content string
110 thinking bool
111}
112
David Crawshaw93fec602025-05-05 08:40:06 -0700113func New(agent loop.CodingAgent, httpURL string) *TermUI {
114 return &TermUI{
Earl Lee2e463fb2025-04-17 11:22:22 -0700115 agent: agent,
116 stdin: os.Stdin,
117 stdout: os.Stdout,
118 stderr: os.Stderr,
119 httpURL: httpURL,
120 chatMsgCh: make(chan chatMessage, 1),
121 termLogCh: make(chan string, 1),
122 pushedBranches: make(map[string]struct{}),
123 }
124}
125
David Crawshaw93fec602025-05-05 08:40:06 -0700126func (ui *TermUI) Run(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700127 fmt.Println(`๐ŸŒ ` + ui.httpURL + `/`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700128 fmt.Println(`๐Ÿ’ฌ type 'help' for help`)
129 fmt.Println()
130
131 // Start up the main terminal UI:
132 if err := ui.initializeTerminalUI(ctx); err != nil {
133 return err
134 }
135 go ui.receiveMessagesLoop(ctx)
136 if err := ui.inputLoop(ctx); err != nil {
137 return err
138 }
139 return nil
140}
141
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000142func (ui *TermUI) HandleToolUse(resp *loop.AgentMessage) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700143 inputData := map[string]any{}
144 if err := json.Unmarshal([]byte(resp.ToolInput), &inputData); err != nil {
145 ui.AppendSystemMessage("error: %v", err)
146 return
147 }
148 buf := bytes.Buffer{}
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000149 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 -0700150 ui.AppendSystemMessage("error: %v", err)
151 return
152 }
153 ui.AppendSystemMessage("%s\n", buf.String())
154}
155
David Crawshaw93fec602025-05-05 08:40:06 -0700156func (ui *TermUI) receiveMessagesLoop(ctx context.Context) {
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700157 it := ui.agent.NewIterator(ctx, 0)
Earl Lee2e463fb2025-04-17 11:22:22 -0700158 bold := color.New(color.Bold).SprintFunc()
159 for {
160 select {
161 case <-ctx.Done():
162 return
163 default:
164 }
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700165 resp := it.Next()
166 if resp == nil {
167 return
168 }
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000169 if resp.HideOutput {
170 continue
171 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700172 // Typically a user message will start the thinking and a (top-level
173 // conversation) end of turn will stop it.
174 thinking := !(resp.EndOfTurn && resp.ParentConversationID == nil)
175
176 switch resp.Type {
177 case loop.AgentMessageType:
Josh Bleecher Snyder2978ab22025-04-30 10:29:32 -0700178 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐Ÿ•ด๏ธ ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700179 case loop.ToolUseMessageType:
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000180 ui.HandleToolUse(resp)
Earl Lee2e463fb2025-04-17 11:22:22 -0700181 case loop.ErrorMessageType:
182 ui.AppendSystemMessage("โŒ %s", resp.Content)
183 case loop.BudgetMessageType:
184 ui.AppendSystemMessage("๐Ÿ’ฐ %s", resp.Content)
185 case loop.AutoMessageType:
186 ui.AppendSystemMessage("๐Ÿง %s", resp.Content)
187 case loop.UserMessageType:
Josh Bleecher Snyderc2d26102025-04-30 06:19:43 -0700188 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐Ÿฆธ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700189 case loop.CommitMessageType:
190 // Display each commit in the terminal
191 for _, commit := range resp.Commits {
192 if commit.PushedBranch != "" {
philip.zeyliger6d3de482025-06-10 19:38:14 -0700193 // Check if we should show a GitHub link
194 githubURL := ui.getGitHubBranchURL(commit.PushedBranch)
195 if githubURL != "" {
196 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s\npushed to: %s\n๐Ÿ”— %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch), githubURL)
197 } else {
198 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s\npushed to: %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch))
199 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700200
201 // Track the pushed branch in our map
202 ui.mu.Lock()
203 ui.pushedBranches[commit.PushedBranch] = struct{}{}
204 ui.mu.Unlock()
205 } else {
206 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s", commit.Hash[:8], commit.Subject)
207 }
208 }
Josh Bleecher Snyder289525b2025-07-08 04:03:02 +0000209 case loop.PortMessageType:
210 ui.AppendSystemMessage("๐Ÿ”Œ %s", resp.Content)
Josh Bleecher Snyder3b44cc32025-07-22 02:28:14 +0000211 case loop.SlugMessageType:
212 ui.updateTitleWithSlug(resp.Content)
213 case loop.CompactMessageType:
214 // TODO: print something for compaction?
Earl Lee2e463fb2025-04-17 11:22:22 -0700215 default:
216 ui.AppendSystemMessage("โŒ Unexpected Message Type %s %v", resp.Type, resp)
217 }
218 }
219}
220
David Crawshaw93fec602025-05-05 08:40:06 -0700221func (ui *TermUI) inputLoop(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700222 for {
223 line, err := ui.trm.ReadLine()
224 if errors.Is(err, io.EOF) {
225 ui.AppendSystemMessage("\n")
226 line = "exit"
227 } else if err != nil {
228 return err
229 }
230
231 line = strings.TrimSpace(line)
232
233 switch line {
234 case "?", "help":
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700235 ui.AppendSystemMessage(`General use:
236Use chat to ask sketch to tackle a task or answer a question about this repo.
237
238Special commands:
239- help, ? : Show this help message
240- budget : Show original budget
241- usage, cost : Show current token usage and cost
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000242- browser, open, b : Open current conversation in browser
Earl Lee2e463fb2025-04-17 11:22:22 -0700243- stop, cancel, abort : Cancel the current operation
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700244- exit, quit, q : Exit sketch
245- ! <command> : Execute a shell command (e.g. !ls -la)`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700246 case "budget":
247 originalBudget := ui.agent.OriginalBudget()
248 ui.AppendSystemMessage("๐Ÿ’ฐ Budget summary:")
Philip Zeyligere6c294d2025-06-04 16:55:21 +0000249
Earl Lee2e463fb2025-04-17 11:22:22 -0700250 ui.AppendSystemMessage("- Max total cost: %0.2f", originalBudget.MaxDollars)
Josh Bleecher Snyder89ba5f42025-07-17 14:21:43 -0700251 case "browser", "open", "b", "v": // "v" is a common typo for "b"
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000252 if ui.httpURL != "" {
253 ui.AppendSystemMessage("๐ŸŒ Opening %s in browser", ui.httpURL)
254 go ui.agent.OpenBrowser(ui.httpURL)
255 } else {
256 ui.AppendSystemMessage("โŒ No web URL available for this session")
257 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700258 case "usage", "cost":
259 totalUsage := ui.agent.TotalUsage()
260 ui.AppendSystemMessage("๐Ÿ’ฐ Current usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000261 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
262 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700263 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
264 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
265 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
266 case "bye", "exit", "q", "quit":
267 ui.trm.SetPrompt("")
268 // Display final usage stats
269 totalUsage := ui.agent.TotalUsage()
270 ui.AppendSystemMessage("๐Ÿ’ฐ Final usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000271 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
272 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700273 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
274 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
275 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
276
277 // Display pushed branches
278 ui.mu.Lock()
279 if len(ui.pushedBranches) > 0 {
280 // Convert map keys to a slice for display
281 branches := make([]string, 0, len(ui.pushedBranches))
282 for branch := range ui.pushedBranches {
283 branches = append(branches, branch)
284 }
285
Philip Zeyliger49edc922025-05-14 09:45:45 -0700286 initialCommitRef := getShortSHA(ui.agent.SketchGitBase())
Earl Lee2e463fb2025-04-17 11:22:22 -0700287 if len(branches) == 1 {
288 ui.AppendSystemMessage("\n๐Ÿ”„ Branch pushed during session: %s", branches[0])
philip.zeyliger6d3de482025-06-10 19:38:14 -0700289 // Add GitHub link if available
290 if githubURL := ui.getGitHubBranchURL(branches[0]); githubURL != "" {
291 ui.AppendSystemMessage("๐Ÿ”— %s", githubURL)
292 }
Josh Bleecher Snyder956626d2025-05-15 21:24:07 +0000293 ui.AppendSystemMessage("๐Ÿ’ Cherry-pick those changes: git cherry-pick %s..%s", initialCommitRef, branches[0])
294 ui.AppendSystemMessage("๐Ÿ”€ Merge those changes: git merge %s", branches[0])
295 ui.AppendSystemMessage("๐Ÿ—‘๏ธ Delete the branch: git branch -D %s", branches[0])
Earl Lee2e463fb2025-04-17 11:22:22 -0700296 } else {
297 ui.AppendSystemMessage("\n๐Ÿ”„ Branches pushed during session:")
298 for _, branch := range branches {
299 ui.AppendSystemMessage("- %s", branch)
philip.zeyliger6d3de482025-06-10 19:38:14 -0700300 // Add GitHub link if available
301 if githubURL := ui.getGitHubBranchURL(branch); githubURL != "" {
302 ui.AppendSystemMessage(" ๐Ÿ”— %s", githubURL)
303 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700304 }
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
Earl Lee2e463fb2025-04-17 11:22:22 -0700374 if thinking {
375 // Emoji don't seem to work here? Messes up my terminal.
Josh Bleecher Snydera77889b2025-07-28 13:08:14 -0700376 t = " *"
Earl Lee2e463fb2025-04-17 11:22:22 -0700377 }
Josh Bleecher Snydera77889b2025-07-28 13:08:14 -0700378 p := fmt.Sprintf("%s%s> ", ui.agent.Slug(), 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 {
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000398 return fmt.Errorf("get terminal size: %v", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700399 }
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)
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000419 ui.pushTerminalTitle()
420 ui.setTerminalTitle("sketch")
Earl Lee2e463fb2025-04-17 11:22:22 -0700421
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()
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000464 ui.setTerminalTitle("")
465 ui.popTerminalTitle()
Earl Lee2e463fb2025-04-17 11:22:22 -0700466 return term.Restore(int(ui.stdin.Fd()), ui.oldState)
467}
468
469// AppendChatMessage is for showing responses the user's request, conversational dialog etc
David Crawshaw93fec602025-05-05 08:40:06 -0700470func (ui *TermUI) AppendChatMessage(msg chatMessage) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000471 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700472 ui.chatMsgCh <- msg
473}
474
475// AppendSystemMessage is for debug information, errors and such that are not part of the "conversation" per se,
476// but still need to be shown to the user.
David Crawshaw93fec602025-05-05 08:40:06 -0700477func (ui *TermUI) AppendSystemMessage(fmtString string, args ...any) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000478 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700479 ui.termLogCh <- fmt.Sprintf(fmtString, args...)
480}
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000481
Josh Bleecher Snyder8fdf7532025-05-06 00:56:12 +0000482// getShortSHA returns the short SHA for the given git reference, falling back to the original SHA on error.
483func getShortSHA(sha string) string {
484 cmd := exec.Command("git", "rev-parse", "--short", sha)
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000485 shortSha, err := cmd.Output()
486 if err == nil {
487 shortStr := strings.TrimSpace(string(shortSha))
488 if shortStr != "" {
489 return shortStr
490 }
491 }
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000492 return sha
493}
philip.zeyliger6d3de482025-06-10 19:38:14 -0700494
495// isGitHubRepo checks if the git origin URL is a GitHub repository
496func (ui *TermUI) isGitHubRepo() bool {
497 gitOrigin := ui.agent.GitOrigin()
498 if gitOrigin == "" {
499 return false
500 }
501
502 // Common GitHub URL patterns
503 patterns := []string{
504 `^https://github\.com/[^/]+/[^/\s.]+(?:\.git)?`,
505 `^git@github\.com:[^/]+/[^/\s.]+(?:\.git)?`,
506 `^git://github\.com/[^/]+/[^/\s.]+(?:\.git)?`,
507 }
508
509 for _, pattern := range patterns {
510 if matched, _ := regexp.MatchString(pattern, gitOrigin); matched {
511 return true
512 }
513 }
514 return false
515}
516
517// getGitHubBranchURL generates a GitHub branch URL if conditions are met
518func (ui *TermUI) getGitHubBranchURL(branchName string) string {
519 if !ui.agent.LinkToGitHub() || branchName == "" {
520 return ""
521 }
522
523 gitOrigin := ui.agent.GitOrigin()
524 if gitOrigin == "" || !ui.isGitHubRepo() {
525 return ""
526 }
527
528 // Extract owner and repo from GitHub URL
529 patterns := []string{
530 `^https://github\.com/([^/]+)/([^/\s.]+)(?:\.git)?`,
531 `^git@github\.com:([^/]+)/([^/\s.]+)(?:\.git)?`,
532 `^git://github\.com/([^/]+)/([^/\s.]+)(?:\.git)?`,
533 }
534
535 for _, pattern := range patterns {
536 re := regexp.MustCompile(pattern)
537 matches := re.FindStringSubmatch(gitOrigin)
538 if len(matches) == 3 {
539 owner := matches[1]
540 repo := matches[2]
541 return fmt.Sprintf("https://github.com/%s/%s/tree/%s", owner, repo, branchName)
542 }
543 }
544 return ""
545}
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000546
547// pushTerminalTitle pushes the current terminal title onto the title stack
548// Only works on xterm-compatible terminals, but does no harm elsewhere
549func (ui *TermUI) pushTerminalTitle() {
550 fmt.Fprintf(ui.stderr, "\033[22;0t")
551 ui.titlePushed = true
552}
553
554// popTerminalTitle pops the terminal title from the title stack
555func (ui *TermUI) popTerminalTitle() {
556 if ui.titlePushed {
557 fmt.Fprintf(ui.stderr, "\033[23;0t")
558 ui.titlePushed = false
559 }
560}
561
562func (ui *TermUI) setTerminalTitle(title string) {
563 fmt.Fprintf(ui.stderr, "\033]0;%s\007", title)
564}
565
566// updateTitleWithSlug updates the terminal title with slug slug
567func (ui *TermUI) updateTitleWithSlug(slug string) {
568 ui.mu.Lock()
569 defer ui.mu.Unlock()
570 ui.currentSlug = slug
571 title := "sketch"
572 if slug != "" {
573 title = fmt.Sprintf("sketch: %s", slug)
574 }
575 ui.setTerminalTitle(title)
576}