blob: 1ed749661deee75488791693f95862828c13201d [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
Sean McCullough485afc62025-04-28 14:28:39 -070054{{else if eq .msg.ToolName "multiplechoice" -}}
55 ๐Ÿ“ {{.input.question}}
56{{ range .input.responseOptions -}}
57 - {{ .caption}}: {{.responseText}}
58{{end -}}
Josh Bleecher Snyder2d081192025-05-29 13:46:04 +000059{{else if eq .msg.ToolName "browser_navigate" -}}
60 ๐ŸŒ {{.input.url -}}
61{{else if eq .msg.ToolName "browser_click" -}}
62 ๐Ÿ–ฑ๏ธ {{.input.selector -}}
63{{else if eq .msg.ToolName "browser_type" -}}
64 โŒจ๏ธ {{.input.selector}}: "{{.input.text}}"
65{{else if eq .msg.ToolName "browser_wait_for" -}}
66 โณ {{.input.selector -}}
67{{else if eq .msg.ToolName "browser_get_text" -}}
68 ๐Ÿ“– {{.input.selector -}}
69{{else if eq .msg.ToolName "browser_eval" -}}
70 ๐Ÿ“ฑ {{.input.expression -}}
71{{else if eq .msg.ToolName "browser_take_screenshot" -}}
72 ๐Ÿ“ธ Screenshot
73{{else if eq .msg.ToolName "browser_scroll_into_view" -}}
74 ๐Ÿ”„ {{.input.selector -}}
75{{else if eq .msg.ToolName "browser_resize" -}}
76 ๐Ÿ–ผ๏ธ {{.input.width}}x{{.input.height -}}
Philip Zeyliger542bda32025-06-11 18:31:03 -070077{{else if eq .msg.ToolName "read_image" -}}
Josh Bleecher Snyder2d081192025-05-29 13:46:04 +000078 ๐Ÿ–ผ๏ธ {{.input.path -}}
79{{else if eq .msg.ToolName "browser_recent_console_logs" -}}
80 ๐Ÿ“œ Console logs
81{{else if eq .msg.ToolName "browser_clear_console_logs" -}}
82 ๐Ÿงน Clear console logs
Philip Zeyligerc17ffe32025-06-05 19:49:13 -070083{{else if eq .msg.ToolName "list_recent_sketch_sessions" -}}
84 ๐Ÿ“š List recent sketch sessions
85{{else if eq .msg.ToolName "read_sketch_session" -}}
86 ๐Ÿ“– Read session {{.input.session_id}}
Earl Lee2e463fb2025-04-17 11:22:22 -070087{{else -}}
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000088 ๐Ÿ› ๏ธ {{ .msg.ToolName}}: {{.msg.ToolInput -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070089{{end -}}
90`
91 toolUseTmpl = template.Must(template.New("tool_use").Parse(toolUseTemplTxt))
92)
93
David Crawshaw93fec602025-05-05 08:40:06 -070094type TermUI struct {
Earl Lee2e463fb2025-04-17 11:22:22 -070095 stdin *os.File
96 stdout *os.File
97 stderr *os.File
98
99 agent loop.CodingAgent
100 httpURL string
101
102 trm *term.Terminal
103
104 // the chatMsgCh channel is for "conversation" messages, like responses to user input
105 // from the LLM, or output from executing slash-commands issued by the user.
106 chatMsgCh chan chatMessage
107
108 // the log channel is for secondary messages, like logging, errors, and debug information
109 // from local and remove subproceses.
110 termLogCh chan string
111
112 // protects following
113 mu sync.Mutex
114 oldState *term.State
115 // Tracks branches that were pushed during the session
116 pushedBranches map[string]struct{}
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000117
118 // Pending message count, for graceful shutdown
119 messageWaitGroup sync.WaitGroup
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000120
121 currentSlug string
122 titlePushed bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700123}
124
125type chatMessage struct {
126 idx int
127 sender string
128 content string
129 thinking bool
130}
131
David Crawshaw93fec602025-05-05 08:40:06 -0700132func New(agent loop.CodingAgent, httpURL string) *TermUI {
133 return &TermUI{
Earl Lee2e463fb2025-04-17 11:22:22 -0700134 agent: agent,
135 stdin: os.Stdin,
136 stdout: os.Stdout,
137 stderr: os.Stderr,
138 httpURL: httpURL,
139 chatMsgCh: make(chan chatMessage, 1),
140 termLogCh: make(chan string, 1),
141 pushedBranches: make(map[string]struct{}),
142 }
143}
144
David Crawshaw93fec602025-05-05 08:40:06 -0700145func (ui *TermUI) Run(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700146 fmt.Println(`๐ŸŒ ` + ui.httpURL + `/`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700147 fmt.Println(`๐Ÿ’ฌ type 'help' for help`)
148 fmt.Println()
149
150 // Start up the main terminal UI:
151 if err := ui.initializeTerminalUI(ctx); err != nil {
152 return err
153 }
154 go ui.receiveMessagesLoop(ctx)
155 if err := ui.inputLoop(ctx); err != nil {
156 return err
157 }
158 return nil
159}
160
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000161func (ui *TermUI) HandleToolUse(resp *loop.AgentMessage) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700162 inputData := map[string]any{}
163 if err := json.Unmarshal([]byte(resp.ToolInput), &inputData); err != nil {
164 ui.AppendSystemMessage("error: %v", err)
165 return
166 }
167 buf := bytes.Buffer{}
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000168 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 -0700169 ui.AppendSystemMessage("error: %v", err)
170 return
171 }
172 ui.AppendSystemMessage("%s\n", buf.String())
173}
174
David Crawshaw93fec602025-05-05 08:40:06 -0700175func (ui *TermUI) receiveMessagesLoop(ctx context.Context) {
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700176 it := ui.agent.NewIterator(ctx, 0)
Earl Lee2e463fb2025-04-17 11:22:22 -0700177 bold := color.New(color.Bold).SprintFunc()
178 for {
179 select {
180 case <-ctx.Done():
181 return
182 default:
183 }
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700184 resp := it.Next()
185 if resp == nil {
186 return
187 }
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000188 if resp.HideOutput {
189 continue
190 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700191 // Typically a user message will start the thinking and a (top-level
192 // conversation) end of turn will stop it.
193 thinking := !(resp.EndOfTurn && resp.ParentConversationID == nil)
194
195 switch resp.Type {
196 case loop.AgentMessageType:
Josh Bleecher Snyder2978ab22025-04-30 10:29:32 -0700197 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐Ÿ•ด๏ธ ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700198 case loop.ToolUseMessageType:
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000199 ui.HandleToolUse(resp)
Earl Lee2e463fb2025-04-17 11:22:22 -0700200 case loop.ErrorMessageType:
201 ui.AppendSystemMessage("โŒ %s", resp.Content)
202 case loop.BudgetMessageType:
203 ui.AppendSystemMessage("๐Ÿ’ฐ %s", resp.Content)
204 case loop.AutoMessageType:
205 ui.AppendSystemMessage("๐Ÿง %s", resp.Content)
206 case loop.UserMessageType:
Josh Bleecher Snyderc2d26102025-04-30 06:19:43 -0700207 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐Ÿฆธ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700208 case loop.CommitMessageType:
209 // Display each commit in the terminal
210 for _, commit := range resp.Commits {
211 if commit.PushedBranch != "" {
philip.zeyliger6d3de482025-06-10 19:38:14 -0700212 // Check if we should show a GitHub link
213 githubURL := ui.getGitHubBranchURL(commit.PushedBranch)
214 if githubURL != "" {
215 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s\npushed to: %s\n๐Ÿ”— %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch), githubURL)
216 } else {
217 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s\npushed to: %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch))
218 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700219
220 // Track the pushed branch in our map
221 ui.mu.Lock()
222 ui.pushedBranches[commit.PushedBranch] = struct{}{}
223 ui.mu.Unlock()
224 } else {
225 ui.AppendSystemMessage("๐Ÿ”„ new commit: [%s] %s", commit.Hash[:8], commit.Subject)
226 }
227 }
Josh Bleecher Snyder289525b2025-07-08 04:03:02 +0000228 case loop.PortMessageType:
229 ui.AppendSystemMessage("๐Ÿ”Œ %s", resp.Content)
Josh Bleecher Snyder3b44cc32025-07-22 02:28:14 +0000230 case loop.SlugMessageType:
231 ui.updateTitleWithSlug(resp.Content)
232 case loop.CompactMessageType:
233 // TODO: print something for compaction?
Earl Lee2e463fb2025-04-17 11:22:22 -0700234 default:
235 ui.AppendSystemMessage("โŒ Unexpected Message Type %s %v", resp.Type, resp)
236 }
237 }
238}
239
David Crawshaw93fec602025-05-05 08:40:06 -0700240func (ui *TermUI) inputLoop(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700241 for {
242 line, err := ui.trm.ReadLine()
243 if errors.Is(err, io.EOF) {
244 ui.AppendSystemMessage("\n")
245 line = "exit"
246 } else if err != nil {
247 return err
248 }
249
250 line = strings.TrimSpace(line)
251
252 switch line {
253 case "?", "help":
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700254 ui.AppendSystemMessage(`General use:
255Use chat to ask sketch to tackle a task or answer a question about this repo.
256
257Special commands:
258- help, ? : Show this help message
259- budget : Show original budget
260- usage, cost : Show current token usage and cost
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000261- browser, open, b : Open current conversation in browser
Earl Lee2e463fb2025-04-17 11:22:22 -0700262- stop, cancel, abort : Cancel the current operation
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700263- exit, quit, q : Exit sketch
264- ! <command> : Execute a shell command (e.g. !ls -la)`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700265 case "budget":
266 originalBudget := ui.agent.OriginalBudget()
267 ui.AppendSystemMessage("๐Ÿ’ฐ Budget summary:")
Philip Zeyligere6c294d2025-06-04 16:55:21 +0000268
Earl Lee2e463fb2025-04-17 11:22:22 -0700269 ui.AppendSystemMessage("- Max total cost: %0.2f", originalBudget.MaxDollars)
Josh Bleecher Snyder89ba5f42025-07-17 14:21:43 -0700270 case "browser", "open", "b", "v": // "v" is a common typo for "b"
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000271 if ui.httpURL != "" {
272 ui.AppendSystemMessage("๐ŸŒ Opening %s in browser", ui.httpURL)
273 go ui.agent.OpenBrowser(ui.httpURL)
274 } else {
275 ui.AppendSystemMessage("โŒ No web URL available for this session")
276 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700277 case "usage", "cost":
278 totalUsage := ui.agent.TotalUsage()
279 ui.AppendSystemMessage("๐Ÿ’ฐ Current usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000280 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
281 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700282 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
283 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
284 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
285 case "bye", "exit", "q", "quit":
286 ui.trm.SetPrompt("")
287 // Display final usage stats
288 totalUsage := ui.agent.TotalUsage()
289 ui.AppendSystemMessage("๐Ÿ’ฐ Final usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000290 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
291 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700292 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
293 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
294 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
295
296 // Display pushed branches
297 ui.mu.Lock()
298 if len(ui.pushedBranches) > 0 {
299 // Convert map keys to a slice for display
300 branches := make([]string, 0, len(ui.pushedBranches))
301 for branch := range ui.pushedBranches {
302 branches = append(branches, branch)
303 }
304
Philip Zeyliger49edc922025-05-14 09:45:45 -0700305 initialCommitRef := getShortSHA(ui.agent.SketchGitBase())
Earl Lee2e463fb2025-04-17 11:22:22 -0700306 if len(branches) == 1 {
307 ui.AppendSystemMessage("\n๐Ÿ”„ Branch pushed during session: %s", branches[0])
philip.zeyliger6d3de482025-06-10 19:38:14 -0700308 // Add GitHub link if available
309 if githubURL := ui.getGitHubBranchURL(branches[0]); githubURL != "" {
310 ui.AppendSystemMessage("๐Ÿ”— %s", githubURL)
311 }
Josh Bleecher Snyder956626d2025-05-15 21:24:07 +0000312 ui.AppendSystemMessage("๐Ÿ’ Cherry-pick those changes: git cherry-pick %s..%s", initialCommitRef, branches[0])
313 ui.AppendSystemMessage("๐Ÿ”€ Merge those changes: git merge %s", branches[0])
314 ui.AppendSystemMessage("๐Ÿ—‘๏ธ Delete the branch: git branch -D %s", branches[0])
Earl Lee2e463fb2025-04-17 11:22:22 -0700315 } else {
316 ui.AppendSystemMessage("\n๐Ÿ”„ Branches pushed during session:")
317 for _, branch := range branches {
318 ui.AppendSystemMessage("- %s", branch)
philip.zeyliger6d3de482025-06-10 19:38:14 -0700319 // Add GitHub link if available
320 if githubURL := ui.getGitHubBranchURL(branch); githubURL != "" {
321 ui.AppendSystemMessage(" ๐Ÿ”— %s", githubURL)
322 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700323 }
324 ui.AppendSystemMessage("\n๐Ÿ’ To add all those changes to your branch:")
325 for _, branch := range branches {
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000326 ui.AppendSystemMessage("git cherry-pick %s..%s", initialCommitRef, branch)
Earl Lee2e463fb2025-04-17 11:22:22 -0700327 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700328 ui.AppendSystemMessage("\n๐Ÿ”€ or:")
329 for _, branch := range branches {
330 ui.AppendSystemMessage("git merge %s", branch)
331 }
Josh Bleecher Snyder956626d2025-05-15 21:24:07 +0000332
333 ui.AppendSystemMessage("\n๐Ÿ—‘๏ธ To delete branches:")
334 for _, branch := range branches {
335 ui.AppendSystemMessage("git branch -D %s", branch)
336 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700337 }
338 }
339 ui.mu.Unlock()
340
341 ui.AppendSystemMessage("\n๐Ÿ‘‹ Goodbye!")
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000342 // Wait for all pending messages to be processed before exiting
343 ui.messageWaitGroup.Wait()
Earl Lee2e463fb2025-04-17 11:22:22 -0700344 return nil
345 case "stop", "cancel", "abort":
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000346 ui.agent.CancelTurn(fmt.Errorf("user canceled the operation"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700347 case "panic":
348 panic("user forced a panic")
349 default:
350 if line == "" {
351 continue
352 }
353 if strings.HasPrefix(line, "!") {
354 // Execute as shell command
355 line = line[1:] // remove the '!' prefix
356 sendToLLM := strings.HasPrefix(line, "!")
357 if sendToLLM {
358 line = line[1:] // remove the second '!'
359 }
360
361 // Create a cmd and run it
362 // TODO: ui.trm contains a mutex inside its write call.
363 // It is potentially safe to attach ui.trm directly to this
364 // cmd object's Stdout/Stderr and stream the output.
365 // That would make a big difference for, e.g. wget.
366 cmd := exec.Command("bash", "-c", line)
367 out, err := cmd.CombinedOutput()
368 ui.AppendSystemMessage("%s", out)
369 if err != nil {
370 ui.AppendSystemMessage("โŒ Command error: %v", err)
371 }
372 if sendToLLM {
373 // Send the command and its output to the agent
374 message := fmt.Sprintf("I ran the command: `%s`\nOutput:\n```\n%s```", line, out)
375 if err != nil {
376 message += fmt.Sprintf("\n\nError: %v", err)
377 }
378 ui.agent.UserMessage(ctx, message)
379 }
380 continue
381 }
382
383 // Send it to the LLM
384 // chatMsg := chatMessage{sender: "you", content: line}
385 // ui.sendChatMessage(chatMsg)
386 ui.agent.UserMessage(ctx, line)
387 }
388 }
389}
390
David Crawshaw93fec602025-05-05 08:40:06 -0700391func (ui *TermUI) updatePrompt(thinking bool) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700392 var t string
Earl Lee2e463fb2025-04-17 11:22:22 -0700393 if thinking {
394 // Emoji don't seem to work here? Messes up my terminal.
395 t = "*"
396 }
Josh Bleecher Snyder03376232025-06-05 14:29:48 -0700397 var money string
398 if totalCost := ui.agent.TotalUsage().TotalCostUSD; totalCost > 0 {
399 money = fmt.Sprintf("($%0.2f/%0.2f)", totalCost, ui.agent.OriginalBudget().MaxDollars)
400 }
401 p := fmt.Sprintf("%s %s%s> ", ui.httpURL, money, t)
Earl Lee2e463fb2025-04-17 11:22:22 -0700402 ui.trm.SetPrompt(p)
403}
404
David Crawshaw93fec602025-05-05 08:40:06 -0700405func (ui *TermUI) initializeTerminalUI(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700406 ui.mu.Lock()
407 defer ui.mu.Unlock()
408
409 if !term.IsTerminal(int(ui.stdin.Fd())) {
Philip Zeyligerc5b8ed42025-05-05 20:28:34 +0000410 return fmt.Errorf("this command requires terminal I/O when termui=true")
Earl Lee2e463fb2025-04-17 11:22:22 -0700411 }
412
413 oldState, err := term.MakeRaw(int(ui.stdin.Fd()))
414 if err != nil {
415 return err
416 }
417 ui.oldState = oldState
418 ui.trm = term.NewTerminal(ui.stdin, "")
419 width, height, err := term.GetSize(int(ui.stdin.Fd()))
420 if err != nil {
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000421 return fmt.Errorf("get terminal size: %v", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700422 }
423 ui.trm.SetSize(width, height)
424 // Handle terminal resizes...
425 sig := make(chan os.Signal, 1)
426 signal.Notify(sig, syscall.SIGWINCH)
427 go func() {
428 for {
429 <-sig
430 newWidth, newHeight, err := term.GetSize(int(ui.stdin.Fd()))
431 if err != nil {
432 continue
433 }
434 if newWidth != width || newHeight != height {
435 width, height = newWidth, newHeight
436 ui.trm.SetSize(width, height)
437 }
438 }
439 }()
440
441 ui.updatePrompt(false)
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000442 ui.pushTerminalTitle()
443 ui.setTerminalTitle("sketch")
Earl Lee2e463fb2025-04-17 11:22:22 -0700444
445 // This is the only place where we should call fe.trm.Write:
446 go func() {
Sean McCullougha4b19f82025-05-05 10:22:59 -0700447 var lastMsg *chatMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700448 for {
449 select {
450 case <-ctx.Done():
451 return
452 case msg := <-ui.chatMsgCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000453 func() {
454 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700455 // Update prompt before writing, because otherwise it doesn't redraw the prompt.
456 ui.updatePrompt(msg.thinking)
457 lastMsg = &msg
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000458 // Sometimes claude doesn't say anything when it runs tools.
459 // No need to output anything in that case.
460 if strings.TrimSpace(msg.content) == "" {
461 return
462 }
463 s := fmt.Sprintf("%s %s\n", msg.sender, msg.content)
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000464 ui.trm.Write([]byte(s))
465 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700466 case logLine := <-ui.termLogCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000467 func() {
468 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700469 if lastMsg != nil {
470 ui.updatePrompt(lastMsg.thinking)
471 } else {
472 ui.updatePrompt(false)
473 }
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000474 b := []byte(logLine + "\n")
475 ui.trm.Write(b)
476 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700477 }
478 }
479 }()
480
481 return nil
482}
483
David Crawshaw93fec602025-05-05 08:40:06 -0700484func (ui *TermUI) RestoreOldState() error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700485 ui.mu.Lock()
486 defer ui.mu.Unlock()
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000487 ui.setTerminalTitle("")
488 ui.popTerminalTitle()
Earl Lee2e463fb2025-04-17 11:22:22 -0700489 return term.Restore(int(ui.stdin.Fd()), ui.oldState)
490}
491
492// AppendChatMessage is for showing responses the user's request, conversational dialog etc
David Crawshaw93fec602025-05-05 08:40:06 -0700493func (ui *TermUI) AppendChatMessage(msg chatMessage) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000494 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700495 ui.chatMsgCh <- msg
496}
497
498// AppendSystemMessage is for debug information, errors and such that are not part of the "conversation" per se,
499// but still need to be shown to the user.
David Crawshaw93fec602025-05-05 08:40:06 -0700500func (ui *TermUI) AppendSystemMessage(fmtString string, args ...any) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000501 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700502 ui.termLogCh <- fmt.Sprintf(fmtString, args...)
503}
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000504
Josh Bleecher Snyder8fdf7532025-05-06 00:56:12 +0000505// getShortSHA returns the short SHA for the given git reference, falling back to the original SHA on error.
506func getShortSHA(sha string) string {
507 cmd := exec.Command("git", "rev-parse", "--short", sha)
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000508 shortSha, err := cmd.Output()
509 if err == nil {
510 shortStr := strings.TrimSpace(string(shortSha))
511 if shortStr != "" {
512 return shortStr
513 }
514 }
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000515 return sha
516}
philip.zeyliger6d3de482025-06-10 19:38:14 -0700517
518// isGitHubRepo checks if the git origin URL is a GitHub repository
519func (ui *TermUI) isGitHubRepo() bool {
520 gitOrigin := ui.agent.GitOrigin()
521 if gitOrigin == "" {
522 return false
523 }
524
525 // Common GitHub URL patterns
526 patterns := []string{
527 `^https://github\.com/[^/]+/[^/\s.]+(?:\.git)?`,
528 `^git@github\.com:[^/]+/[^/\s.]+(?:\.git)?`,
529 `^git://github\.com/[^/]+/[^/\s.]+(?:\.git)?`,
530 }
531
532 for _, pattern := range patterns {
533 if matched, _ := regexp.MatchString(pattern, gitOrigin); matched {
534 return true
535 }
536 }
537 return false
538}
539
540// getGitHubBranchURL generates a GitHub branch URL if conditions are met
541func (ui *TermUI) getGitHubBranchURL(branchName string) string {
542 if !ui.agent.LinkToGitHub() || branchName == "" {
543 return ""
544 }
545
546 gitOrigin := ui.agent.GitOrigin()
547 if gitOrigin == "" || !ui.isGitHubRepo() {
548 return ""
549 }
550
551 // Extract owner and repo from GitHub URL
552 patterns := []string{
553 `^https://github\.com/([^/]+)/([^/\s.]+)(?:\.git)?`,
554 `^git@github\.com:([^/]+)/([^/\s.]+)(?:\.git)?`,
555 `^git://github\.com/([^/]+)/([^/\s.]+)(?:\.git)?`,
556 }
557
558 for _, pattern := range patterns {
559 re := regexp.MustCompile(pattern)
560 matches := re.FindStringSubmatch(gitOrigin)
561 if len(matches) == 3 {
562 owner := matches[1]
563 repo := matches[2]
564 return fmt.Sprintf("https://github.com/%s/%s/tree/%s", owner, repo, branchName)
565 }
566 }
567 return ""
568}
Josh Bleecher Snyder2153f8b2025-07-04 02:41:20 +0000569
570// pushTerminalTitle pushes the current terminal title onto the title stack
571// Only works on xterm-compatible terminals, but does no harm elsewhere
572func (ui *TermUI) pushTerminalTitle() {
573 fmt.Fprintf(ui.stderr, "\033[22;0t")
574 ui.titlePushed = true
575}
576
577// popTerminalTitle pops the terminal title from the title stack
578func (ui *TermUI) popTerminalTitle() {
579 if ui.titlePushed {
580 fmt.Fprintf(ui.stderr, "\033[23;0t")
581 ui.titlePushed = false
582 }
583}
584
585func (ui *TermUI) setTerminalTitle(title string) {
586 fmt.Fprintf(ui.stderr, "\033]0;%s\007", title)
587}
588
589// updateTitleWithSlug updates the terminal title with slug slug
590func (ui *TermUI) updateTitleWithSlug(slug string) {
591 ui.mu.Lock()
592 defer ui.mu.Unlock()
593 ui.currentSlug = slug
594 title := "sketch"
595 if slug != "" {
596 title = fmt.Sprintf("sketch: %s", slug)
597 }
598 ui.setTerminalTitle(title)
599}