blob: bc8a610c87724f9285a193ddd28af7e7c2e51ed7 [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 Snyder19969a92025-06-05 14:34:02 -070048{{else if eq .msg.ToolName "commit-message-style" -}}
49๐ŸŒฑ learn git commit message style
Josh Bleecher Snyder74d690e2025-05-14 18:16:03 -070050{{else if eq .msg.ToolName "about_sketch" -}}
51๐Ÿ“š About Sketch
Earl Lee2e463fb2025-04-17 11:22:22 -070052{{else if eq .msg.ToolName "codereview" -}}
53 ๐Ÿ› Running automated code review, may be slow
Josh Bleecher Snyder2d081192025-05-29 13:46:04 +000054{{else if eq .msg.ToolName "browser_navigate" -}}
55 ๐ŸŒ {{.input.url -}}
56{{else if eq .msg.ToolName "browser_click" -}}
57 ๐Ÿ–ฑ๏ธ {{.input.selector -}}
58{{else if eq .msg.ToolName "browser_type" -}}
59 โŒจ๏ธ {{.input.selector}}: "{{.input.text}}"
60{{else if eq .msg.ToolName "browser_wait_for" -}}
61 โณ {{.input.selector -}}
62{{else if eq .msg.ToolName "browser_get_text" -}}
63 ๐Ÿ“– {{.input.selector -}}
64{{else if eq .msg.ToolName "browser_eval" -}}
65 ๐Ÿ“ฑ {{.input.expression -}}
66{{else if eq .msg.ToolName "browser_take_screenshot" -}}
67 ๐Ÿ“ธ Screenshot
68{{else if eq .msg.ToolName "browser_scroll_into_view" -}}
69 ๐Ÿ”„ {{.input.selector -}}
70{{else if eq .msg.ToolName "browser_resize" -}}
71 ๐Ÿ–ผ๏ธ {{.input.width}}x{{.input.height -}}
Philip Zeyliger542bda32025-06-11 18:31:03 -070072{{else if eq .msg.ToolName "read_image" -}}
Josh Bleecher Snyder2d081192025-05-29 13:46:04 +000073 ๐Ÿ–ผ๏ธ {{.input.path -}}
74{{else if eq .msg.ToolName "browser_recent_console_logs" -}}
75 ๐Ÿ“œ Console logs
76{{else if eq .msg.ToolName "browser_clear_console_logs" -}}
77 ๐Ÿงน Clear console logs
Philip Zeyligerc17ffe32025-06-05 19:49:13 -070078{{else if eq .msg.ToolName "list_recent_sketch_sessions" -}}
79 ๐Ÿ“š List recent sketch sessions
80{{else if eq .msg.ToolName "read_sketch_session" -}}
81 ๐Ÿ“– Read session {{.input.session_id}}
Earl Lee2e463fb2025-04-17 11:22:22 -070082{{else -}}
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000083 ๐Ÿ› ๏ธ {{ .msg.ToolName}}: {{.msg.ToolInput -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070084{{end -}}
85`
86 toolUseTmpl = template.Must(template.New("tool_use").Parse(toolUseTemplTxt))
87)
88
David Crawshaw93fec602025-05-05 08:40:06 -070089type TermUI struct {
Earl Lee2e463fb2025-04-17 11:22:22 -070090 stdin *os.File
91 stdout *os.File
92 stderr *os.File
93
94 agent loop.CodingAgent
95 httpURL string
96
97 trm *term.Terminal
98
99 // the chatMsgCh channel is for "conversation" messages, like responses to user input
100 // from the LLM, or output from executing slash-commands issued by the user.
101 chatMsgCh chan chatMessage
102
103 // the log channel is for secondary messages, like logging, errors, and debug information
104 // from local and remove subproceses.
105 termLogCh chan string
106
107 // protects following
108 mu sync.Mutex
109 oldState *term.State
110 // Tracks branches that were pushed during the session
111 pushedBranches map[string]struct{}
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000112
113 // Pending message count, for graceful shutdown
114 messageWaitGroup sync.WaitGroup
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000115
116 currentSlug string
117 titlePushed bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700118}
119
120type chatMessage struct {
121 idx int
122 sender string
123 content string
124 thinking bool
125}
126
David Crawshaw93fec602025-05-05 08:40:06 -0700127func New(agent loop.CodingAgent, httpURL string) *TermUI {
128 return &TermUI{
Earl Lee2e463fb2025-04-17 11:22:22 -0700129 agent: agent,
130 stdin: os.Stdin,
131 stdout: os.Stdout,
132 stderr: os.Stderr,
133 httpURL: httpURL,
134 chatMsgCh: make(chan chatMessage, 1),
135 termLogCh: make(chan string, 1),
136 pushedBranches: make(map[string]struct{}),
137 }
138}
139
David Crawshaw93fec602025-05-05 08:40:06 -0700140func (ui *TermUI) Run(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700141 fmt.Println(`๐ŸŒ ` + ui.httpURL + `/`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700142 fmt.Println(`๐Ÿ’ฌ type 'help' for help`)
143 fmt.Println()
144
145 // Start up the main terminal UI:
146 if err := ui.initializeTerminalUI(ctx); err != nil {
147 return err
148 }
149 go ui.receiveMessagesLoop(ctx)
150 if err := ui.inputLoop(ctx); err != nil {
151 return err
152 }
153 return nil
154}
155
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000156func (ui *TermUI) HandleToolUse(resp *loop.AgentMessage) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700157 inputData := map[string]any{}
158 if err := json.Unmarshal([]byte(resp.ToolInput), &inputData); err != nil {
159 ui.AppendSystemMessage("error: %v", err)
160 return
161 }
162 buf := bytes.Buffer{}
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000163 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 -0700164 ui.AppendSystemMessage("error: %v", err)
165 return
166 }
167 ui.AppendSystemMessage("%s\n", buf.String())
168}
169
David Crawshaw93fec602025-05-05 08:40:06 -0700170func (ui *TermUI) receiveMessagesLoop(ctx context.Context) {
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700171 it := ui.agent.NewIterator(ctx, 0)
Earl Lee2e463fb2025-04-17 11:22:22 -0700172 bold := color.New(color.Bold).SprintFunc()
173 for {
174 select {
175 case <-ctx.Done():
176 return
177 default:
178 }
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700179 resp := it.Next()
180 if resp == nil {
181 return
182 }
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000183 if resp.HideOutput {
184 continue
185 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700186 // Typically a user message will start the thinking and a (top-level
187 // conversation) end of turn will stop it.
188 thinking := !(resp.EndOfTurn && resp.ParentConversationID == nil)
189
190 switch resp.Type {
191 case loop.AgentMessageType:
Josh Bleecher Snyder2978ab22025-04-30 10:29:32 -0700192 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐Ÿ•ด๏ธ ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700193 case loop.ToolUseMessageType:
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000194 ui.HandleToolUse(resp)
Earl Lee2e463fb2025-04-17 11:22:22 -0700195 case loop.ErrorMessageType:
196 ui.AppendSystemMessage("โŒ %s", resp.Content)
197 case loop.BudgetMessageType:
198 ui.AppendSystemMessage("๐Ÿ’ฐ %s", resp.Content)
199 case loop.AutoMessageType:
200 ui.AppendSystemMessage("๐Ÿง %s", resp.Content)
201 case loop.UserMessageType:
Josh Bleecher Snyderc2d26102025-04-30 06:19:43 -0700202 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐Ÿฆธ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700203 case loop.CommitMessageType:
204 // Display each commit in the terminal
205 for _, commit := range resp.Commits {
206 if commit.PushedBranch != "" {
philip.zeyliger6d3de482025-06-10 19:38:14 -0700207 // Check if we should show a GitHub link
208 githubURL := ui.getGitHubBranchURL(commit.PushedBranch)
209 if githubURL != "" {
210 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s\npushed to: %s\n๐Ÿ”— %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch), githubURL)
211 } else {
212 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s\npushed to: %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch))
213 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700214
215 // Track the pushed branch in our map
216 ui.mu.Lock()
217 ui.pushedBranches[commit.PushedBranch] = struct{}{}
218 ui.mu.Unlock()
219 } else {
220 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s", commit.Hash[:8], commit.Subject)
221 }
222 }
Josh Bleecher Snyder289525b2025-07-08 04:03:02 +0000223 case loop.PortMessageType:
224 ui.AppendSystemMessage("๐Ÿ”Œ %s", resp.Content)
Josh Bleecher Snyder3b44cc32025-07-22 02:28:14 +0000225 case loop.SlugMessageType:
226 ui.updateTitleWithSlug(resp.Content)
227 case loop.CompactMessageType:
228 // TODO: print something for compaction?
Earl Lee2e463fb2025-04-17 11:22:22 -0700229 default:
230 ui.AppendSystemMessage("โŒ Unexpected Message Type %s %v", resp.Type, resp)
231 }
232 }
233}
234
David Crawshaw93fec602025-05-05 08:40:06 -0700235func (ui *TermUI) inputLoop(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700236 for {
237 line, err := ui.trm.ReadLine()
238 if errors.Is(err, io.EOF) {
239 ui.AppendSystemMessage("\n")
240 line = "exit"
241 } else if err != nil {
242 return err
243 }
244
245 line = strings.TrimSpace(line)
246
247 switch line {
248 case "?", "help":
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700249 ui.AppendSystemMessage(`General use:
250Use chat to ask sketch to tackle a task or answer a question about this repo.
251
252Special commands:
253- help, ? : Show this help message
254- budget : Show original budget
255- usage, cost : Show current token usage and cost
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000256- browser, open, b : Open current conversation in browser
Earl Lee2e463fb2025-04-17 11:22:22 -0700257- stop, cancel, abort : Cancel the current operation
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700258- exit, quit, q : Exit sketch
259- ! <command> : Execute a shell command (e.g. !ls -la)`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700260 case "budget":
261 originalBudget := ui.agent.OriginalBudget()
262 ui.AppendSystemMessage("๐Ÿ’ฐ Budget summary:")
Philip Zeyligere6c294d2025-06-04 16:55:21 +0000263
Earl Lee2e463fb2025-04-17 11:22:22 -0700264 ui.AppendSystemMessage("- Max total cost: %0.2f", originalBudget.MaxDollars)
Josh Bleecher Snyder89ba5f42025-07-17 14:21:43 -0700265 case "browser", "open", "b", "v": // "v" is a common typo for "b"
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000266 if ui.httpURL != "" {
267 ui.AppendSystemMessage("๐ŸŒ Opening %s in browser", ui.httpURL)
268 go ui.agent.OpenBrowser(ui.httpURL)
269 } else {
270 ui.AppendSystemMessage("โŒ No web URL available for this session")
271 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700272 case "usage", "cost":
273 totalUsage := ui.agent.TotalUsage()
274 ui.AppendSystemMessage("๐Ÿ’ฐ Current usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000275 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
276 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700277 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
278 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
279 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
280 case "bye", "exit", "q", "quit":
281 ui.trm.SetPrompt("")
282 // Display final usage stats
283 totalUsage := ui.agent.TotalUsage()
284 ui.AppendSystemMessage("๐Ÿ’ฐ Final usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000285 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
286 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700287 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
288 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
289 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
290
291 // Display pushed branches
292 ui.mu.Lock()
293 if len(ui.pushedBranches) > 0 {
294 // Convert map keys to a slice for display
295 branches := make([]string, 0, len(ui.pushedBranches))
296 for branch := range ui.pushedBranches {
297 branches = append(branches, branch)
298 }
299
Philip Zeyliger49edc922025-05-14 09:45:45 -0700300 initialCommitRef := getShortSHA(ui.agent.SketchGitBase())
Earl Lee2e463fb2025-04-17 11:22:22 -0700301 if len(branches) == 1 {
302 ui.AppendSystemMessage("\n๐Ÿ”„ Branch pushed during session: %s", branches[0])
philip.zeyliger6d3de482025-06-10 19:38:14 -0700303 // Add GitHub link if available
304 if githubURL := ui.getGitHubBranchURL(branches[0]); githubURL != "" {
305 ui.AppendSystemMessage("๐Ÿ”— %s", githubURL)
306 }
Josh Bleecher Snyder956626d2025-05-15 21:24:07 +0000307 ui.AppendSystemMessage("๐Ÿ’ Cherry-pick those changes: git cherry-pick %s..%s", initialCommitRef, branches[0])
308 ui.AppendSystemMessage("๐Ÿ”€ Merge those changes: git merge %s", branches[0])
309 ui.AppendSystemMessage("๐Ÿ—‘๏ธ Delete the branch: git branch -D %s", branches[0])
Earl Lee2e463fb2025-04-17 11:22:22 -0700310 } else {
311 ui.AppendSystemMessage("\n๐Ÿ”„ Branches pushed during session:")
312 for _, branch := range branches {
313 ui.AppendSystemMessage("- %s", branch)
philip.zeyliger6d3de482025-06-10 19:38:14 -0700314 // Add GitHub link if available
315 if githubURL := ui.getGitHubBranchURL(branch); githubURL != "" {
316 ui.AppendSystemMessage(" ๐Ÿ”— %s", githubURL)
317 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700318 }
319 ui.AppendSystemMessage("\n๐Ÿ’ To add all those changes to your branch:")
320 for _, branch := range branches {
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000321 ui.AppendSystemMessage("git cherry-pick %s..%s", initialCommitRef, branch)
Earl Lee2e463fb2025-04-17 11:22:22 -0700322 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700323 ui.AppendSystemMessage("\n๐Ÿ”€ or:")
324 for _, branch := range branches {
325 ui.AppendSystemMessage("git merge %s", branch)
326 }
Josh Bleecher Snyder956626d2025-05-15 21:24:07 +0000327
328 ui.AppendSystemMessage("\n๐Ÿ—‘๏ธ To delete branches:")
329 for _, branch := range branches {
330 ui.AppendSystemMessage("git branch -D %s", branch)
331 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700332 }
333 }
334 ui.mu.Unlock()
335
336 ui.AppendSystemMessage("\n๐Ÿ‘‹ Goodbye!")
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000337 // Wait for all pending messages to be processed before exiting
338 ui.messageWaitGroup.Wait()
Earl Lee2e463fb2025-04-17 11:22:22 -0700339 return nil
340 case "stop", "cancel", "abort":
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000341 ui.agent.CancelTurn(fmt.Errorf("user canceled the operation"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700342 case "panic":
343 panic("user forced a panic")
344 default:
345 if line == "" {
346 continue
347 }
348 if strings.HasPrefix(line, "!") {
349 // Execute as shell command
350 line = line[1:] // remove the '!' prefix
351 sendToLLM := strings.HasPrefix(line, "!")
352 if sendToLLM {
353 line = line[1:] // remove the second '!'
354 }
355
356 // Create a cmd and run it
357 // TODO: ui.trm contains a mutex inside its write call.
358 // It is potentially safe to attach ui.trm directly to this
359 // cmd object's Stdout/Stderr and stream the output.
360 // That would make a big difference for, e.g. wget.
361 cmd := exec.Command("bash", "-c", line)
362 out, err := cmd.CombinedOutput()
363 ui.AppendSystemMessage("%s", out)
364 if err != nil {
365 ui.AppendSystemMessage("โŒ Command error: %v", err)
366 }
367 if sendToLLM {
368 // Send the command and its output to the agent
369 message := fmt.Sprintf("I ran the command: `%s`\nOutput:\n```\n%s```", line, out)
370 if err != nil {
371 message += fmt.Sprintf("\n\nError: %v", err)
372 }
373 ui.agent.UserMessage(ctx, message)
374 }
375 continue
376 }
377
378 // Send it to the LLM
379 // chatMsg := chatMessage{sender: "you", content: line}
380 // ui.sendChatMessage(chatMsg)
381 ui.agent.UserMessage(ctx, line)
382 }
383 }
384}
385
David Crawshaw93fec602025-05-05 08:40:06 -0700386func (ui *TermUI) updatePrompt(thinking bool) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700387 var t string
Earl Lee2e463fb2025-04-17 11:22:22 -0700388 if thinking {
389 // Emoji don't seem to work here? Messes up my terminal.
390 t = "*"
391 }
Josh Bleecher Snyder03376232025-06-05 14:29:48 -0700392 var money string
393 if totalCost := ui.agent.TotalUsage().TotalCostUSD; totalCost > 0 {
394 money = fmt.Sprintf("($%0.2f/%0.2f)", totalCost, ui.agent.OriginalBudget().MaxDollars)
395 }
396 p := fmt.Sprintf("%s %s%s> ", ui.httpURL, money, t)
Earl Lee2e463fb2025-04-17 11:22:22 -0700397 ui.trm.SetPrompt(p)
398}
399
David Crawshaw93fec602025-05-05 08:40:06 -0700400func (ui *TermUI) initializeTerminalUI(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700401 ui.mu.Lock()
402 defer ui.mu.Unlock()
403
404 if !term.IsTerminal(int(ui.stdin.Fd())) {
Philip Zeyligerc5b8ed42025-05-05 20:28:34 +0000405 return fmt.Errorf("this command requires terminal I/O when termui=true")
Earl Lee2e463fb2025-04-17 11:22:22 -0700406 }
407
408 oldState, err := term.MakeRaw(int(ui.stdin.Fd()))
409 if err != nil {
410 return err
411 }
412 ui.oldState = oldState
413 ui.trm = term.NewTerminal(ui.stdin, "")
414 width, height, err := term.GetSize(int(ui.stdin.Fd()))
415 if err != nil {
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000416 return fmt.Errorf("get terminal size: %v", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700417 }
418 ui.trm.SetSize(width, height)
419 // Handle terminal resizes...
420 sig := make(chan os.Signal, 1)
421 signal.Notify(sig, syscall.SIGWINCH)
422 go func() {
423 for {
424 <-sig
425 newWidth, newHeight, err := term.GetSize(int(ui.stdin.Fd()))
426 if err != nil {
427 continue
428 }
429 if newWidth != width || newHeight != height {
430 width, height = newWidth, newHeight
431 ui.trm.SetSize(width, height)
432 }
433 }
434 }()
435
436 ui.updatePrompt(false)
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000437 ui.pushTerminalTitle()
438 ui.setTerminalTitle("sketch")
Earl Lee2e463fb2025-04-17 11:22:22 -0700439
440 // This is the only place where we should call fe.trm.Write:
441 go func() {
Sean McCullougha4b19f82025-05-05 10:22:59 -0700442 var lastMsg *chatMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700443 for {
444 select {
445 case <-ctx.Done():
446 return
447 case msg := <-ui.chatMsgCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000448 func() {
449 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700450 // Update prompt before writing, because otherwise it doesn't redraw the prompt.
451 ui.updatePrompt(msg.thinking)
452 lastMsg = &msg
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000453 // Sometimes claude doesn't say anything when it runs tools.
454 // No need to output anything in that case.
455 if strings.TrimSpace(msg.content) == "" {
456 return
457 }
458 s := fmt.Sprintf("%s %s\n", msg.sender, msg.content)
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000459 ui.trm.Write([]byte(s))
460 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700461 case logLine := <-ui.termLogCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000462 func() {
463 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700464 if lastMsg != nil {
465 ui.updatePrompt(lastMsg.thinking)
466 } else {
467 ui.updatePrompt(false)
468 }
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000469 b := []byte(logLine + "\n")
470 ui.trm.Write(b)
471 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700472 }
473 }
474 }()
475
476 return nil
477}
478
David Crawshaw93fec602025-05-05 08:40:06 -0700479func (ui *TermUI) RestoreOldState() error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700480 ui.mu.Lock()
481 defer ui.mu.Unlock()
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000482 ui.setTerminalTitle("")
483 ui.popTerminalTitle()
Earl Lee2e463fb2025-04-17 11:22:22 -0700484 return term.Restore(int(ui.stdin.Fd()), ui.oldState)
485}
486
487// AppendChatMessage is for showing responses the user's request, conversational dialog etc
David Crawshaw93fec602025-05-05 08:40:06 -0700488func (ui *TermUI) AppendChatMessage(msg chatMessage) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000489 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700490 ui.chatMsgCh <- msg
491}
492
493// AppendSystemMessage is for debug information, errors and such that are not part of the "conversation" per se,
494// but still need to be shown to the user.
David Crawshaw93fec602025-05-05 08:40:06 -0700495func (ui *TermUI) AppendSystemMessage(fmtString string, args ...any) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000496 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700497 ui.termLogCh <- fmt.Sprintf(fmtString, args...)
498}
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000499
Josh Bleecher Snyder8fdf7532025-05-06 00:56:12 +0000500// getShortSHA returns the short SHA for the given git reference, falling back to the original SHA on error.
501func getShortSHA(sha string) string {
502 cmd := exec.Command("git", "rev-parse", "--short", sha)
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000503 shortSha, err := cmd.Output()
504 if err == nil {
505 shortStr := strings.TrimSpace(string(shortSha))
506 if shortStr != "" {
507 return shortStr
508 }
509 }
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000510 return sha
511}
philip.zeyliger6d3de482025-06-10 19:38:14 -0700512
513// isGitHubRepo checks if the git origin URL is a GitHub repository
514func (ui *TermUI) isGitHubRepo() bool {
515 gitOrigin := ui.agent.GitOrigin()
516 if gitOrigin == "" {
517 return false
518 }
519
520 // Common GitHub URL patterns
521 patterns := []string{
522 `^https://github\.com/[^/]+/[^/\s.]+(?:\.git)?`,
523 `^git@github\.com:[^/]+/[^/\s.]+(?:\.git)?`,
524 `^git://github\.com/[^/]+/[^/\s.]+(?:\.git)?`,
525 }
526
527 for _, pattern := range patterns {
528 if matched, _ := regexp.MatchString(pattern, gitOrigin); matched {
529 return true
530 }
531 }
532 return false
533}
534
535// getGitHubBranchURL generates a GitHub branch URL if conditions are met
536func (ui *TermUI) getGitHubBranchURL(branchName string) string {
537 if !ui.agent.LinkToGitHub() || branchName == "" {
538 return ""
539 }
540
541 gitOrigin := ui.agent.GitOrigin()
542 if gitOrigin == "" || !ui.isGitHubRepo() {
543 return ""
544 }
545
546 // Extract owner and repo from GitHub URL
547 patterns := []string{
548 `^https://github\.com/([^/]+)/([^/\s.]+)(?:\.git)?`,
549 `^git@github\.com:([^/]+)/([^/\s.]+)(?:\.git)?`,
550 `^git://github\.com/([^/]+)/([^/\s.]+)(?:\.git)?`,
551 }
552
553 for _, pattern := range patterns {
554 re := regexp.MustCompile(pattern)
555 matches := re.FindStringSubmatch(gitOrigin)
556 if len(matches) == 3 {
557 owner := matches[1]
558 repo := matches[2]
559 return fmt.Sprintf("https://github.com/%s/%s/tree/%s", owner, repo, branchName)
560 }
561 }
562 return ""
563}
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000564
565// pushTerminalTitle pushes the current terminal title onto the title stack
566// Only works on xterm-compatible terminals, but does no harm elsewhere
567func (ui *TermUI) pushTerminalTitle() {
568 fmt.Fprintf(ui.stderr, "\033[22;0t")
569 ui.titlePushed = true
570}
571
572// popTerminalTitle pops the terminal title from the title stack
573func (ui *TermUI) popTerminalTitle() {
574 if ui.titlePushed {
575 fmt.Fprintf(ui.stderr, "\033[23;0t")
576 ui.titlePushed = false
577 }
578}
579
580func (ui *TermUI) setTerminalTitle(title string) {
581 fmt.Fprintf(ui.stderr, "\033]0;%s\007", title)
582}
583
584// updateTitleWithSlug updates the terminal title with slug slug
585func (ui *TermUI) updateTitleWithSlug(slug string) {
586 ui.mu.Lock()
587 defer ui.mu.Unlock()
588 ui.currentSlug = slug
589 title := "sketch"
590 if slug != "" {
591 title = fmt.Sprintf("sketch: %s", slug)
592 }
593 ui.setTerminalTitle(title)
594}