blob: c85750fe1fbe011626bda8158dcd3cf19ce7001b [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 "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
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000122
123 currentSlug string
124 titlePushed bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700125}
126
127type chatMessage struct {
128 idx int
129 sender string
130 content string
131 thinking bool
132}
133
David Crawshaw93fec602025-05-05 08:40:06 -0700134func New(agent loop.CodingAgent, httpURL string) *TermUI {
135 return &TermUI{
Earl Lee2e463fb2025-04-17 11:22:22 -0700136 agent: agent,
137 stdin: os.Stdin,
138 stdout: os.Stdout,
139 stderr: os.Stderr,
140 httpURL: httpURL,
141 chatMsgCh: make(chan chatMessage, 1),
142 termLogCh: make(chan string, 1),
143 pushedBranches: make(map[string]struct{}),
144 }
145}
146
David Crawshaw93fec602025-05-05 08:40:06 -0700147func (ui *TermUI) Run(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700148 fmt.Println(`๐ŸŒ ` + ui.httpURL + `/`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700149 fmt.Println(`๐Ÿ’ฌ type 'help' for help`)
150 fmt.Println()
151
152 // Start up the main terminal UI:
153 if err := ui.initializeTerminalUI(ctx); err != nil {
154 return err
155 }
156 go ui.receiveMessagesLoop(ctx)
157 if err := ui.inputLoop(ctx); err != nil {
158 return err
159 }
160 return nil
161}
162
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000163func (ui *TermUI) HandleToolUse(resp *loop.AgentMessage) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700164 inputData := map[string]any{}
165 if err := json.Unmarshal([]byte(resp.ToolInput), &inputData); err != nil {
166 ui.AppendSystemMessage("error: %v", err)
167 return
168 }
169 buf := bytes.Buffer{}
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000170 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 -0700171 ui.AppendSystemMessage("error: %v", err)
172 return
173 }
174 ui.AppendSystemMessage("%s\n", buf.String())
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000175
176 if resp.ToolName == "set-slug" {
177 if slug, ok := inputData["slug"].(string); ok {
178 ui.updateTitleWithSlug(slug)
179 }
180 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700181}
182
David Crawshaw93fec602025-05-05 08:40:06 -0700183func (ui *TermUI) receiveMessagesLoop(ctx context.Context) {
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700184 it := ui.agent.NewIterator(ctx, 0)
Earl Lee2e463fb2025-04-17 11:22:22 -0700185 bold := color.New(color.Bold).SprintFunc()
186 for {
187 select {
188 case <-ctx.Done():
189 return
190 default:
191 }
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700192 resp := it.Next()
193 if resp == nil {
194 return
195 }
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000196 if resp.HideOutput {
197 continue
198 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700199 // Typically a user message will start the thinking and a (top-level
200 // conversation) end of turn will stop it.
201 thinking := !(resp.EndOfTurn && resp.ParentConversationID == nil)
202
203 switch resp.Type {
204 case loop.AgentMessageType:
Josh Bleecher Snyder2978ab22025-04-30 10:29:32 -0700205 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐Ÿ•ด๏ธ ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700206 case loop.ToolUseMessageType:
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000207 ui.HandleToolUse(resp)
Earl Lee2e463fb2025-04-17 11:22:22 -0700208 case loop.ErrorMessageType:
209 ui.AppendSystemMessage("โŒ %s", resp.Content)
210 case loop.BudgetMessageType:
211 ui.AppendSystemMessage("๐Ÿ’ฐ %s", resp.Content)
212 case loop.AutoMessageType:
213 ui.AppendSystemMessage("๐Ÿง %s", resp.Content)
214 case loop.UserMessageType:
Josh Bleecher Snyderc2d26102025-04-30 06:19:43 -0700215 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐Ÿฆธ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700216 case loop.CommitMessageType:
217 // Display each commit in the terminal
218 for _, commit := range resp.Commits {
219 if commit.PushedBranch != "" {
philip.zeyliger6d3de482025-06-10 19:38:14 -0700220 // Check if we should show a GitHub link
221 githubURL := ui.getGitHubBranchURL(commit.PushedBranch)
222 if githubURL != "" {
223 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s\npushed to: %s\n๐Ÿ”— %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch), githubURL)
224 } else {
225 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s\npushed to: %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch))
226 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700227
228 // Track the pushed branch in our map
229 ui.mu.Lock()
230 ui.pushedBranches[commit.PushedBranch] = struct{}{}
231 ui.mu.Unlock()
232 } else {
233 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s", commit.Hash[:8], commit.Subject)
234 }
235 }
Josh Bleecher Snyder289525b2025-07-08 04:03:02 +0000236 case loop.PortMessageType:
237 ui.AppendSystemMessage("๐Ÿ”Œ %s", resp.Content)
Earl Lee2e463fb2025-04-17 11:22:22 -0700238 default:
239 ui.AppendSystemMessage("โŒ Unexpected Message Type %s %v", resp.Type, resp)
240 }
241 }
242}
243
David Crawshaw93fec602025-05-05 08:40:06 -0700244func (ui *TermUI) inputLoop(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700245 for {
246 line, err := ui.trm.ReadLine()
247 if errors.Is(err, io.EOF) {
248 ui.AppendSystemMessage("\n")
249 line = "exit"
250 } else if err != nil {
251 return err
252 }
253
254 line = strings.TrimSpace(line)
255
256 switch line {
257 case "?", "help":
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700258 ui.AppendSystemMessage(`General use:
259Use chat to ask sketch to tackle a task or answer a question about this repo.
260
261Special commands:
262- help, ? : Show this help message
263- budget : Show original budget
264- usage, cost : Show current token usage and cost
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000265- browser, open, b : Open current conversation in browser
Earl Lee2e463fb2025-04-17 11:22:22 -0700266- stop, cancel, abort : Cancel the current operation
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700267- exit, quit, q : Exit sketch
268- ! <command> : Execute a shell command (e.g. !ls -la)`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700269 case "budget":
270 originalBudget := ui.agent.OriginalBudget()
271 ui.AppendSystemMessage("๐Ÿ’ฐ Budget summary:")
Philip Zeyligere6c294d2025-06-04 16:55:21 +0000272
Earl Lee2e463fb2025-04-17 11:22:22 -0700273 ui.AppendSystemMessage("- Max total cost: %0.2f", originalBudget.MaxDollars)
Josh Bleecher Snyder89ba5f42025-07-17 14:21:43 -0700274 case "browser", "open", "b", "v": // "v" is a common typo for "b"
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000275 if ui.httpURL != "" {
276 ui.AppendSystemMessage("๐ŸŒ Opening %s in browser", ui.httpURL)
277 go ui.agent.OpenBrowser(ui.httpURL)
278 } else {
279 ui.AppendSystemMessage("โŒ No web URL available for this session")
280 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700281 case "usage", "cost":
282 totalUsage := ui.agent.TotalUsage()
283 ui.AppendSystemMessage("๐Ÿ’ฐ Current usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000284 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
285 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700286 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
287 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
288 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
289 case "bye", "exit", "q", "quit":
290 ui.trm.SetPrompt("")
291 // Display final usage stats
292 totalUsage := ui.agent.TotalUsage()
293 ui.AppendSystemMessage("๐Ÿ’ฐ Final usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000294 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
295 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700296 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
297 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
298 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
299
300 // Display pushed branches
301 ui.mu.Lock()
302 if len(ui.pushedBranches) > 0 {
303 // Convert map keys to a slice for display
304 branches := make([]string, 0, len(ui.pushedBranches))
305 for branch := range ui.pushedBranches {
306 branches = append(branches, branch)
307 }
308
Philip Zeyliger49edc922025-05-14 09:45:45 -0700309 initialCommitRef := getShortSHA(ui.agent.SketchGitBase())
Earl Lee2e463fb2025-04-17 11:22:22 -0700310 if len(branches) == 1 {
311 ui.AppendSystemMessage("\n๐Ÿ”„ Branch pushed during session: %s", branches[0])
philip.zeyliger6d3de482025-06-10 19:38:14 -0700312 // Add GitHub link if available
313 if githubURL := ui.getGitHubBranchURL(branches[0]); githubURL != "" {
314 ui.AppendSystemMessage("๐Ÿ”— %s", githubURL)
315 }
Josh Bleecher Snyder956626d2025-05-15 21:24:07 +0000316 ui.AppendSystemMessage("๐Ÿ’ Cherry-pick those changes: git cherry-pick %s..%s", initialCommitRef, branches[0])
317 ui.AppendSystemMessage("๐Ÿ”€ Merge those changes: git merge %s", branches[0])
318 ui.AppendSystemMessage("๐Ÿ—‘๏ธ Delete the branch: git branch -D %s", branches[0])
Earl Lee2e463fb2025-04-17 11:22:22 -0700319 } else {
320 ui.AppendSystemMessage("\n๐Ÿ”„ Branches pushed during session:")
321 for _, branch := range branches {
322 ui.AppendSystemMessage("- %s", branch)
philip.zeyliger6d3de482025-06-10 19:38:14 -0700323 // Add GitHub link if available
324 if githubURL := ui.getGitHubBranchURL(branch); githubURL != "" {
325 ui.AppendSystemMessage(" ๐Ÿ”— %s", githubURL)
326 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700327 }
328 ui.AppendSystemMessage("\n๐Ÿ’ To add all those changes to your branch:")
329 for _, branch := range branches {
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000330 ui.AppendSystemMessage("git cherry-pick %s..%s", initialCommitRef, branch)
Earl Lee2e463fb2025-04-17 11:22:22 -0700331 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700332 ui.AppendSystemMessage("\n๐Ÿ”€ or:")
333 for _, branch := range branches {
334 ui.AppendSystemMessage("git merge %s", branch)
335 }
Josh Bleecher Snyder956626d2025-05-15 21:24:07 +0000336
337 ui.AppendSystemMessage("\n๐Ÿ—‘๏ธ To delete branches:")
338 for _, branch := range branches {
339 ui.AppendSystemMessage("git branch -D %s", branch)
340 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700341 }
342 }
343 ui.mu.Unlock()
344
345 ui.AppendSystemMessage("\n๐Ÿ‘‹ Goodbye!")
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000346 // Wait for all pending messages to be processed before exiting
347 ui.messageWaitGroup.Wait()
Earl Lee2e463fb2025-04-17 11:22:22 -0700348 return nil
349 case "stop", "cancel", "abort":
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000350 ui.agent.CancelTurn(fmt.Errorf("user canceled the operation"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700351 case "panic":
352 panic("user forced a panic")
353 default:
354 if line == "" {
355 continue
356 }
357 if strings.HasPrefix(line, "!") {
358 // Execute as shell command
359 line = line[1:] // remove the '!' prefix
360 sendToLLM := strings.HasPrefix(line, "!")
361 if sendToLLM {
362 line = line[1:] // remove the second '!'
363 }
364
365 // Create a cmd and run it
366 // TODO: ui.trm contains a mutex inside its write call.
367 // It is potentially safe to attach ui.trm directly to this
368 // cmd object's Stdout/Stderr and stream the output.
369 // That would make a big difference for, e.g. wget.
370 cmd := exec.Command("bash", "-c", line)
371 out, err := cmd.CombinedOutput()
372 ui.AppendSystemMessage("%s", out)
373 if err != nil {
374 ui.AppendSystemMessage("โŒ Command error: %v", err)
375 }
376 if sendToLLM {
377 // Send the command and its output to the agent
378 message := fmt.Sprintf("I ran the command: `%s`\nOutput:\n```\n%s```", line, out)
379 if err != nil {
380 message += fmt.Sprintf("\n\nError: %v", err)
381 }
382 ui.agent.UserMessage(ctx, message)
383 }
384 continue
385 }
386
387 // Send it to the LLM
388 // chatMsg := chatMessage{sender: "you", content: line}
389 // ui.sendChatMessage(chatMsg)
390 ui.agent.UserMessage(ctx, line)
391 }
392 }
393}
394
David Crawshaw93fec602025-05-05 08:40:06 -0700395func (ui *TermUI) updatePrompt(thinking bool) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700396 var t string
Earl Lee2e463fb2025-04-17 11:22:22 -0700397 if thinking {
398 // Emoji don't seem to work here? Messes up my terminal.
399 t = "*"
400 }
Josh Bleecher Snyder03376232025-06-05 14:29:48 -0700401 var money string
402 if totalCost := ui.agent.TotalUsage().TotalCostUSD; totalCost > 0 {
403 money = fmt.Sprintf("($%0.2f/%0.2f)", totalCost, ui.agent.OriginalBudget().MaxDollars)
404 }
405 p := fmt.Sprintf("%s %s%s> ", ui.httpURL, money, t)
Earl Lee2e463fb2025-04-17 11:22:22 -0700406 ui.trm.SetPrompt(p)
407}
408
David Crawshaw93fec602025-05-05 08:40:06 -0700409func (ui *TermUI) initializeTerminalUI(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700410 ui.mu.Lock()
411 defer ui.mu.Unlock()
412
413 if !term.IsTerminal(int(ui.stdin.Fd())) {
Philip Zeyligerc5b8ed42025-05-05 20:28:34 +0000414 return fmt.Errorf("this command requires terminal I/O when termui=true")
Earl Lee2e463fb2025-04-17 11:22:22 -0700415 }
416
417 oldState, err := term.MakeRaw(int(ui.stdin.Fd()))
418 if err != nil {
419 return err
420 }
421 ui.oldState = oldState
422 ui.trm = term.NewTerminal(ui.stdin, "")
423 width, height, err := term.GetSize(int(ui.stdin.Fd()))
424 if err != nil {
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000425 return fmt.Errorf("get terminal size: %v", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700426 }
427 ui.trm.SetSize(width, height)
428 // Handle terminal resizes...
429 sig := make(chan os.Signal, 1)
430 signal.Notify(sig, syscall.SIGWINCH)
431 go func() {
432 for {
433 <-sig
434 newWidth, newHeight, err := term.GetSize(int(ui.stdin.Fd()))
435 if err != nil {
436 continue
437 }
438 if newWidth != width || newHeight != height {
439 width, height = newWidth, newHeight
440 ui.trm.SetSize(width, height)
441 }
442 }
443 }()
444
445 ui.updatePrompt(false)
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000446 ui.pushTerminalTitle()
447 ui.setTerminalTitle("sketch")
Earl Lee2e463fb2025-04-17 11:22:22 -0700448
449 // This is the only place where we should call fe.trm.Write:
450 go func() {
Sean McCullougha4b19f82025-05-05 10:22:59 -0700451 var lastMsg *chatMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700452 for {
453 select {
454 case <-ctx.Done():
455 return
456 case msg := <-ui.chatMsgCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000457 func() {
458 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700459 // Update prompt before writing, because otherwise it doesn't redraw the prompt.
460 ui.updatePrompt(msg.thinking)
461 lastMsg = &msg
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000462 // Sometimes claude doesn't say anything when it runs tools.
463 // No need to output anything in that case.
464 if strings.TrimSpace(msg.content) == "" {
465 return
466 }
467 s := fmt.Sprintf("%s %s\n", msg.sender, msg.content)
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000468 ui.trm.Write([]byte(s))
469 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700470 case logLine := <-ui.termLogCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000471 func() {
472 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700473 if lastMsg != nil {
474 ui.updatePrompt(lastMsg.thinking)
475 } else {
476 ui.updatePrompt(false)
477 }
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000478 b := []byte(logLine + "\n")
479 ui.trm.Write(b)
480 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700481 }
482 }
483 }()
484
485 return nil
486}
487
David Crawshaw93fec602025-05-05 08:40:06 -0700488func (ui *TermUI) RestoreOldState() error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700489 ui.mu.Lock()
490 defer ui.mu.Unlock()
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000491 ui.setTerminalTitle("")
492 ui.popTerminalTitle()
Earl Lee2e463fb2025-04-17 11:22:22 -0700493 return term.Restore(int(ui.stdin.Fd()), ui.oldState)
494}
495
496// AppendChatMessage is for showing responses the user's request, conversational dialog etc
David Crawshaw93fec602025-05-05 08:40:06 -0700497func (ui *TermUI) AppendChatMessage(msg chatMessage) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000498 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700499 ui.chatMsgCh <- msg
500}
501
502// AppendSystemMessage is for debug information, errors and such that are not part of the "conversation" per se,
503// but still need to be shown to the user.
David Crawshaw93fec602025-05-05 08:40:06 -0700504func (ui *TermUI) AppendSystemMessage(fmtString string, args ...any) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000505 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700506 ui.termLogCh <- fmt.Sprintf(fmtString, args...)
507}
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000508
Josh Bleecher Snyder8fdf7532025-05-06 00:56:12 +0000509// getShortSHA returns the short SHA for the given git reference, falling back to the original SHA on error.
510func getShortSHA(sha string) string {
511 cmd := exec.Command("git", "rev-parse", "--short", sha)
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000512 shortSha, err := cmd.Output()
513 if err == nil {
514 shortStr := strings.TrimSpace(string(shortSha))
515 if shortStr != "" {
516 return shortStr
517 }
518 }
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000519 return sha
520}
philip.zeyliger6d3de482025-06-10 19:38:14 -0700521
522// isGitHubRepo checks if the git origin URL is a GitHub repository
523func (ui *TermUI) isGitHubRepo() bool {
524 gitOrigin := ui.agent.GitOrigin()
525 if gitOrigin == "" {
526 return false
527 }
528
529 // Common GitHub URL patterns
530 patterns := []string{
531 `^https://github\.com/[^/]+/[^/\s.]+(?:\.git)?`,
532 `^git@github\.com:[^/]+/[^/\s.]+(?:\.git)?`,
533 `^git://github\.com/[^/]+/[^/\s.]+(?:\.git)?`,
534 }
535
536 for _, pattern := range patterns {
537 if matched, _ := regexp.MatchString(pattern, gitOrigin); matched {
538 return true
539 }
540 }
541 return false
542}
543
544// getGitHubBranchURL generates a GitHub branch URL if conditions are met
545func (ui *TermUI) getGitHubBranchURL(branchName string) string {
546 if !ui.agent.LinkToGitHub() || branchName == "" {
547 return ""
548 }
549
550 gitOrigin := ui.agent.GitOrigin()
551 if gitOrigin == "" || !ui.isGitHubRepo() {
552 return ""
553 }
554
555 // Extract owner and repo from GitHub URL
556 patterns := []string{
557 `^https://github\.com/([^/]+)/([^/\s.]+)(?:\.git)?`,
558 `^git@github\.com:([^/]+)/([^/\s.]+)(?:\.git)?`,
559 `^git://github\.com/([^/]+)/([^/\s.]+)(?:\.git)?`,
560 }
561
562 for _, pattern := range patterns {
563 re := regexp.MustCompile(pattern)
564 matches := re.FindStringSubmatch(gitOrigin)
565 if len(matches) == 3 {
566 owner := matches[1]
567 repo := matches[2]
568 return fmt.Sprintf("https://github.com/%s/%s/tree/%s", owner, repo, branchName)
569 }
570 }
571 return ""
572}
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000573
574// pushTerminalTitle pushes the current terminal title onto the title stack
575// Only works on xterm-compatible terminals, but does no harm elsewhere
576func (ui *TermUI) pushTerminalTitle() {
577 fmt.Fprintf(ui.stderr, "\033[22;0t")
578 ui.titlePushed = true
579}
580
581// popTerminalTitle pops the terminal title from the title stack
582func (ui *TermUI) popTerminalTitle() {
583 if ui.titlePushed {
584 fmt.Fprintf(ui.stderr, "\033[23;0t")
585 ui.titlePushed = false
586 }
587}
588
589func (ui *TermUI) setTerminalTitle(title string) {
590 fmt.Fprintf(ui.stderr, "\033]0;%s\007", title)
591}
592
593// updateTitleWithSlug updates the terminal title with slug slug
594func (ui *TermUI) updateTitleWithSlug(slug string) {
595 ui.mu.Lock()
596 defer ui.mu.Unlock()
597 ui.currentSlug = slug
598 title := "sketch"
599 if slug != "" {
600 title = fmt.Sprintf("sketch: %s", slug)
601 }
602 ui.setTerminalTitle(title)
603}