| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 1 | package termui |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "os/signal" |
| philip.zeyliger | 6d3de48 | 2025-06-10 19:38:14 -0700 | [diff] [blame] | 13 | "regexp" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 14 | "strings" |
| 15 | "sync" |
| 16 | "syscall" |
| 17 | "text/template" |
| 18 | "time" |
| 19 | |
| Josh Bleecher Snyder | a0801ad | 2025-04-25 19:34:53 +0000 | [diff] [blame] | 20 | "github.com/dustin/go-humanize" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 21 | "github.com/fatih/color" |
| 22 | "golang.org/x/term" |
| 23 | "sketch.dev/loop" |
| 24 | ) |
| 25 | |
| 26 | var ( |
| 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 Snyder | c3c2023 | 2025-05-07 05:46:04 -0700 | [diff] [blame] | 32 | toolUseTemplTxt = `{{if .msg.ToolError}}ใฐ๏ธ {{end -}} |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 33 | {{if eq .msg.ToolName "think" -}} |
| 34 | ๐ง {{.input.thoughts -}} |
| Josh Bleecher Snyder | 112b923 | 2025-05-23 11:26:33 -0700 | [diff] [blame] | 35 | {{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 Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 40 | {{else if eq .msg.ToolName "keyword_search" -}} |
| Josh Bleecher Snyder | 453a62f | 2025-05-01 10:14:33 -0700 | [diff] [blame] | 41 | ๐ {{ .input.query}}: {{.input.search_terms -}} |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 42 | {{else if eq .msg.ToolName "bash" -}} |
| Josh Bleecher Snyder | 17b2fd9 | 2025-07-09 22:47:13 +0000 | [diff] [blame] | 43 | ๐ฅ๏ธ {{if .input.background}}๐ฅท {{end}}{{if .input.slow_ok}}๐ข {{end}}{{ .input.command -}} |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 44 | {{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 Snyder | 74d690e | 2025-05-14 18:16:03 -0700 | [diff] [blame] | 48 | {{else if eq .msg.ToolName "about_sketch" -}} |
| 49 | ๐ About Sketch |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 50 | {{else if eq .msg.ToolName "codereview" -}} |
| 51 | ๐ Running automated code review, may be slow |
| Josh Bleecher Snyder | 2d08119 | 2025-05-29 13:46:04 +0000 | [diff] [blame] | 52 | {{else if eq .msg.ToolName "browser_navigate" -}} |
| 53 | ๐ {{.input.url -}} |
| 54 | {{else if eq .msg.ToolName "browser_click" -}} |
| 55 | ๐ฑ๏ธ {{.input.selector -}} |
| 56 | {{else if eq .msg.ToolName "browser_type" -}} |
| 57 | โจ๏ธ {{.input.selector}}: "{{.input.text}}" |
| 58 | {{else if eq .msg.ToolName "browser_wait_for" -}} |
| 59 | โณ {{.input.selector -}} |
| 60 | {{else if eq .msg.ToolName "browser_get_text" -}} |
| 61 | ๐ {{.input.selector -}} |
| 62 | {{else if eq .msg.ToolName "browser_eval" -}} |
| 63 | ๐ฑ {{.input.expression -}} |
| 64 | {{else if eq .msg.ToolName "browser_take_screenshot" -}} |
| 65 | ๐ธ Screenshot |
| 66 | {{else if eq .msg.ToolName "browser_scroll_into_view" -}} |
| 67 | ๐ {{.input.selector -}} |
| 68 | {{else if eq .msg.ToolName "browser_resize" -}} |
| 69 | ๐ผ๏ธ {{.input.width}}x{{.input.height -}} |
| Philip Zeyliger | 542bda3 | 2025-06-11 18:31:03 -0700 | [diff] [blame] | 70 | {{else if eq .msg.ToolName "read_image" -}} |
| Josh Bleecher Snyder | 2d08119 | 2025-05-29 13:46:04 +0000 | [diff] [blame] | 71 | ๐ผ๏ธ {{.input.path -}} |
| 72 | {{else if eq .msg.ToolName "browser_recent_console_logs" -}} |
| 73 | ๐ Console logs |
| 74 | {{else if eq .msg.ToolName "browser_clear_console_logs" -}} |
| 75 | ๐งน Clear console logs |
| Philip Zeyliger | c17ffe3 | 2025-06-05 19:49:13 -0700 | [diff] [blame] | 76 | {{else if eq .msg.ToolName "list_recent_sketch_sessions" -}} |
| 77 | ๐ List recent sketch sessions |
| 78 | {{else if eq .msg.ToolName "read_sketch_session" -}} |
| 79 | ๐ Read session {{.input.session_id}} |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 80 | {{else -}} |
| Josh Bleecher Snyder | 47b1936 | 2025-04-30 01:34:14 +0000 | [diff] [blame] | 81 | ๐ ๏ธ {{ .msg.ToolName}}: {{.msg.ToolInput -}} |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 82 | {{end -}} |
| 83 | ` |
| 84 | toolUseTmpl = template.Must(template.New("tool_use").Parse(toolUseTemplTxt)) |
| 85 | ) |
| 86 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 87 | type TermUI struct { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 88 | stdin *os.File |
| 89 | stdout *os.File |
| 90 | stderr *os.File |
| 91 | |
| 92 | agent loop.CodingAgent |
| 93 | httpURL string |
| 94 | |
| 95 | trm *term.Terminal |
| 96 | |
| 97 | // the chatMsgCh channel is for "conversation" messages, like responses to user input |
| 98 | // from the LLM, or output from executing slash-commands issued by the user. |
| 99 | chatMsgCh chan chatMessage |
| 100 | |
| 101 | // the log channel is for secondary messages, like logging, errors, and debug information |
| 102 | // from local and remove subproceses. |
| 103 | termLogCh chan string |
| 104 | |
| 105 | // protects following |
| 106 | mu sync.Mutex |
| 107 | oldState *term.State |
| 108 | // Tracks branches that were pushed during the session |
| 109 | pushedBranches map[string]struct{} |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 110 | |
| 111 | // Pending message count, for graceful shutdown |
| 112 | messageWaitGroup sync.WaitGroup |
| Josh Bleecher Snyder | 2153f8b | 2025-07-04 02:41:20 +0000 | [diff] [blame] | 113 | |
| 114 | currentSlug string |
| 115 | titlePushed bool |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 116 | } |
| 117 | |
| 118 | type chatMessage struct { |
| 119 | idx int |
| 120 | sender string |
| 121 | content string |
| 122 | thinking bool |
| 123 | } |
| 124 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 125 | func New(agent loop.CodingAgent, httpURL string) *TermUI { |
| 126 | return &TermUI{ |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 127 | agent: agent, |
| 128 | stdin: os.Stdin, |
| 129 | stdout: os.Stdout, |
| 130 | stderr: os.Stderr, |
| 131 | httpURL: httpURL, |
| 132 | chatMsgCh: make(chan chatMessage, 1), |
| 133 | termLogCh: make(chan string, 1), |
| 134 | pushedBranches: make(map[string]struct{}), |
| 135 | } |
| 136 | } |
| 137 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 138 | func (ui *TermUI) Run(ctx context.Context) error { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 139 | fmt.Println(`๐ ` + ui.httpURL + `/`) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 140 | fmt.Println(`๐ฌ type 'help' for help`) |
| 141 | fmt.Println() |
| 142 | |
| 143 | // Start up the main terminal UI: |
| 144 | if err := ui.initializeTerminalUI(ctx); err != nil { |
| 145 | return err |
| 146 | } |
| 147 | go ui.receiveMessagesLoop(ctx) |
| 148 | if err := ui.inputLoop(ctx); err != nil { |
| 149 | return err |
| 150 | } |
| 151 | return nil |
| 152 | } |
| 153 | |
| Josh Bleecher Snyder | 2153f8b | 2025-07-04 02:41:20 +0000 | [diff] [blame] | 154 | func (ui *TermUI) HandleToolUse(resp *loop.AgentMessage) { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 155 | inputData := map[string]any{} |
| 156 | if err := json.Unmarshal([]byte(resp.ToolInput), &inputData); err != nil { |
| 157 | ui.AppendSystemMessage("error: %v", err) |
| 158 | return |
| 159 | } |
| 160 | buf := bytes.Buffer{} |
| Philip Zeyliger | be7802a | 2025-06-04 20:15:25 +0000 | [diff] [blame] | 161 | if err := toolUseTmpl.Execute(&buf, map[string]any{"msg": resp, "input": inputData, "output": resp.ToolResult, "branch_prefix": ui.agent.BranchPrefix()}); err != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 162 | ui.AppendSystemMessage("error: %v", err) |
| 163 | return |
| 164 | } |
| 165 | ui.AppendSystemMessage("%s\n", buf.String()) |
| 166 | } |
| 167 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 168 | func (ui *TermUI) receiveMessagesLoop(ctx context.Context) { |
| Philip Zeyliger | b7c5875 | 2025-05-01 10:10:17 -0700 | [diff] [blame] | 169 | it := ui.agent.NewIterator(ctx, 0) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 170 | bold := color.New(color.Bold).SprintFunc() |
| 171 | for { |
| 172 | select { |
| 173 | case <-ctx.Done(): |
| 174 | return |
| 175 | default: |
| 176 | } |
| Philip Zeyliger | b7c5875 | 2025-05-01 10:10:17 -0700 | [diff] [blame] | 177 | resp := it.Next() |
| 178 | if resp == nil { |
| 179 | return |
| 180 | } |
| Josh Bleecher Snyder | 4d54493 | 2025-05-07 13:33:53 +0000 | [diff] [blame] | 181 | if resp.HideOutput { |
| 182 | continue |
| 183 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 184 | // Typically a user message will start the thinking and a (top-level |
| 185 | // conversation) end of turn will stop it. |
| 186 | thinking := !(resp.EndOfTurn && resp.ParentConversationID == nil) |
| 187 | |
| 188 | switch resp.Type { |
| 189 | case loop.AgentMessageType: |
| Josh Bleecher Snyder | 2978ab2 | 2025-04-30 10:29:32 -0700 | [diff] [blame] | 190 | ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐ด๏ธ ", content: resp.Content}) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 191 | case loop.ToolUseMessageType: |
| Josh Bleecher Snyder | 2153f8b | 2025-07-04 02:41:20 +0000 | [diff] [blame] | 192 | ui.HandleToolUse(resp) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 193 | case loop.ErrorMessageType: |
| 194 | ui.AppendSystemMessage("โ %s", resp.Content) |
| 195 | case loop.BudgetMessageType: |
| 196 | ui.AppendSystemMessage("๐ฐ %s", resp.Content) |
| 197 | case loop.AutoMessageType: |
| 198 | ui.AppendSystemMessage("๐ง %s", resp.Content) |
| 199 | case loop.UserMessageType: |
| Josh Bleecher Snyder | c2d2610 | 2025-04-30 06:19:43 -0700 | [diff] [blame] | 200 | ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "๐ฆธ", content: resp.Content}) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 201 | case loop.CommitMessageType: |
| 202 | // Display each commit in the terminal |
| 203 | for _, commit := range resp.Commits { |
| 204 | if commit.PushedBranch != "" { |
| philip.zeyliger | 6d3de48 | 2025-06-10 19:38:14 -0700 | [diff] [blame] | 205 | // Check if we should show a GitHub link |
| 206 | githubURL := ui.getGitHubBranchURL(commit.PushedBranch) |
| 207 | if githubURL != "" { |
| 208 | ui.AppendSystemMessage("๐ new commit: [%s] %s\npushed to: %s\n๐ %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch), githubURL) |
| 209 | } else { |
| 210 | ui.AppendSystemMessage("๐ new commit: [%s] %s\npushed to: %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch)) |
| 211 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 212 | |
| 213 | // Track the pushed branch in our map |
| 214 | ui.mu.Lock() |
| 215 | ui.pushedBranches[commit.PushedBranch] = struct{}{} |
| 216 | ui.mu.Unlock() |
| 217 | } else { |
| 218 | ui.AppendSystemMessage("๐ new commit: [%s] %s", commit.Hash[:8], commit.Subject) |
| 219 | } |
| 220 | } |
| Josh Bleecher Snyder | 289525b | 2025-07-08 04:03:02 +0000 | [diff] [blame] | 221 | case loop.PortMessageType: |
| 222 | ui.AppendSystemMessage("๐ %s", resp.Content) |
| Josh Bleecher Snyder | 3b44cc3 | 2025-07-22 02:28:14 +0000 | [diff] [blame] | 223 | case loop.SlugMessageType: |
| 224 | ui.updateTitleWithSlug(resp.Content) |
| 225 | case loop.CompactMessageType: |
| 226 | // TODO: print something for compaction? |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 227 | default: |
| 228 | ui.AppendSystemMessage("โ Unexpected Message Type %s %v", resp.Type, resp) |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 233 | func (ui *TermUI) inputLoop(ctx context.Context) error { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 234 | for { |
| 235 | line, err := ui.trm.ReadLine() |
| 236 | if errors.Is(err, io.EOF) { |
| 237 | ui.AppendSystemMessage("\n") |
| 238 | line = "exit" |
| 239 | } else if err != nil { |
| 240 | return err |
| 241 | } |
| 242 | |
| 243 | line = strings.TrimSpace(line) |
| 244 | |
| 245 | switch line { |
| 246 | case "?", "help": |
| Josh Bleecher Snyder | 8506894 | 2025-04-30 10:51:27 -0700 | [diff] [blame] | 247 | ui.AppendSystemMessage(`General use: |
| 248 | Use chat to ask sketch to tackle a task or answer a question about this repo. |
| 249 | |
| 250 | Special commands: |
| 251 | - help, ? : Show this help message |
| 252 | - budget : Show original budget |
| 253 | - usage, cost : Show current token usage and cost |
| Josh Bleecher Snyder | 3e2111b | 2025-04-30 17:53:28 +0000 | [diff] [blame] | 254 | - browser, open, b : Open current conversation in browser |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 255 | - stop, cancel, abort : Cancel the current operation |
| Josh Bleecher Snyder | 8506894 | 2025-04-30 10:51:27 -0700 | [diff] [blame] | 256 | - exit, quit, q : Exit sketch |
| 257 | - ! <command> : Execute a shell command (e.g. !ls -la)`) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 258 | case "budget": |
| 259 | originalBudget := ui.agent.OriginalBudget() |
| 260 | ui.AppendSystemMessage("๐ฐ Budget summary:") |
| Philip Zeyliger | e6c294d | 2025-06-04 16:55:21 +0000 | [diff] [blame] | 261 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 262 | ui.AppendSystemMessage("- Max total cost: %0.2f", originalBudget.MaxDollars) |
| Josh Bleecher Snyder | 89ba5f4 | 2025-07-17 14:21:43 -0700 | [diff] [blame] | 263 | case "browser", "open", "b", "v": // "v" is a common typo for "b" |
| Josh Bleecher Snyder | 3e2111b | 2025-04-30 17:53:28 +0000 | [diff] [blame] | 264 | if ui.httpURL != "" { |
| 265 | ui.AppendSystemMessage("๐ Opening %s in browser", ui.httpURL) |
| 266 | go ui.agent.OpenBrowser(ui.httpURL) |
| 267 | } else { |
| 268 | ui.AppendSystemMessage("โ No web URL available for this session") |
| 269 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 270 | case "usage", "cost": |
| 271 | totalUsage := ui.agent.TotalUsage() |
| 272 | ui.AppendSystemMessage("๐ฐ Current usage summary:") |
| Josh Bleecher Snyder | a0801ad | 2025-04-25 19:34:53 +0000 | [diff] [blame] | 273 | ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens()))) |
| 274 | ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens))) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 275 | ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses) |
| 276 | ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second)) |
| 277 | ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD) |
| 278 | case "bye", "exit", "q", "quit": |
| 279 | ui.trm.SetPrompt("") |
| 280 | // Display final usage stats |
| 281 | totalUsage := ui.agent.TotalUsage() |
| 282 | ui.AppendSystemMessage("๐ฐ Final usage summary:") |
| Josh Bleecher Snyder | a0801ad | 2025-04-25 19:34:53 +0000 | [diff] [blame] | 283 | ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens()))) |
| 284 | ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens))) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 285 | ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses) |
| 286 | ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second)) |
| 287 | ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD) |
| 288 | |
| 289 | // Display pushed branches |
| 290 | ui.mu.Lock() |
| 291 | if len(ui.pushedBranches) > 0 { |
| 292 | // Convert map keys to a slice for display |
| 293 | branches := make([]string, 0, len(ui.pushedBranches)) |
| 294 | for branch := range ui.pushedBranches { |
| 295 | branches = append(branches, branch) |
| 296 | } |
| 297 | |
| Philip Zeyliger | 49edc92 | 2025-05-14 09:45:45 -0700 | [diff] [blame] | 298 | initialCommitRef := getShortSHA(ui.agent.SketchGitBase()) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 299 | if len(branches) == 1 { |
| 300 | ui.AppendSystemMessage("\n๐ Branch pushed during session: %s", branches[0]) |
| philip.zeyliger | 6d3de48 | 2025-06-10 19:38:14 -0700 | [diff] [blame] | 301 | // Add GitHub link if available |
| 302 | if githubURL := ui.getGitHubBranchURL(branches[0]); githubURL != "" { |
| 303 | ui.AppendSystemMessage("๐ %s", githubURL) |
| 304 | } |
| Josh Bleecher Snyder | 956626d | 2025-05-15 21:24:07 +0000 | [diff] [blame] | 305 | ui.AppendSystemMessage("๐ Cherry-pick those changes: git cherry-pick %s..%s", initialCommitRef, branches[0]) |
| 306 | ui.AppendSystemMessage("๐ Merge those changes: git merge %s", branches[0]) |
| 307 | ui.AppendSystemMessage("๐๏ธ Delete the branch: git branch -D %s", branches[0]) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 308 | } else { |
| 309 | ui.AppendSystemMessage("\n๐ Branches pushed during session:") |
| 310 | for _, branch := range branches { |
| 311 | ui.AppendSystemMessage("- %s", branch) |
| philip.zeyliger | 6d3de48 | 2025-06-10 19:38:14 -0700 | [diff] [blame] | 312 | // Add GitHub link if available |
| 313 | if githubURL := ui.getGitHubBranchURL(branch); githubURL != "" { |
| 314 | ui.AppendSystemMessage(" ๐ %s", githubURL) |
| 315 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 316 | } |
| 317 | ui.AppendSystemMessage("\n๐ To add all those changes to your branch:") |
| 318 | for _, branch := range branches { |
| Josh Bleecher Snyder | 0137a7f | 2025-04-30 01:16:35 +0000 | [diff] [blame] | 319 | ui.AppendSystemMessage("git cherry-pick %s..%s", initialCommitRef, branch) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 320 | } |
| Philip Zeyliger | 49edc92 | 2025-05-14 09:45:45 -0700 | [diff] [blame] | 321 | ui.AppendSystemMessage("\n๐ or:") |
| 322 | for _, branch := range branches { |
| 323 | ui.AppendSystemMessage("git merge %s", branch) |
| 324 | } |
| Josh Bleecher Snyder | 956626d | 2025-05-15 21:24:07 +0000 | [diff] [blame] | 325 | |
| 326 | ui.AppendSystemMessage("\n๐๏ธ To delete branches:") |
| 327 | for _, branch := range branches { |
| 328 | ui.AppendSystemMessage("git branch -D %s", branch) |
| 329 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 330 | } |
| 331 | } |
| 332 | ui.mu.Unlock() |
| 333 | |
| 334 | ui.AppendSystemMessage("\n๐ Goodbye!") |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 335 | // Wait for all pending messages to be processed before exiting |
| 336 | ui.messageWaitGroup.Wait() |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 337 | return nil |
| 338 | case "stop", "cancel", "abort": |
| Sean McCullough | edc88dc | 2025-04-30 02:55:01 +0000 | [diff] [blame] | 339 | ui.agent.CancelTurn(fmt.Errorf("user canceled the operation")) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 340 | case "panic": |
| 341 | panic("user forced a panic") |
| 342 | default: |
| 343 | if line == "" { |
| 344 | continue |
| 345 | } |
| 346 | if strings.HasPrefix(line, "!") { |
| 347 | // Execute as shell command |
| 348 | line = line[1:] // remove the '!' prefix |
| 349 | sendToLLM := strings.HasPrefix(line, "!") |
| 350 | if sendToLLM { |
| 351 | line = line[1:] // remove the second '!' |
| 352 | } |
| 353 | |
| 354 | // Create a cmd and run it |
| 355 | // TODO: ui.trm contains a mutex inside its write call. |
| 356 | // It is potentially safe to attach ui.trm directly to this |
| 357 | // cmd object's Stdout/Stderr and stream the output. |
| 358 | // That would make a big difference for, e.g. wget. |
| 359 | cmd := exec.Command("bash", "-c", line) |
| 360 | out, err := cmd.CombinedOutput() |
| 361 | ui.AppendSystemMessage("%s", out) |
| 362 | if err != nil { |
| 363 | ui.AppendSystemMessage("โ Command error: %v", err) |
| 364 | } |
| 365 | if sendToLLM { |
| 366 | // Send the command and its output to the agent |
| 367 | message := fmt.Sprintf("I ran the command: `%s`\nOutput:\n```\n%s```", line, out) |
| 368 | if err != nil { |
| 369 | message += fmt.Sprintf("\n\nError: %v", err) |
| 370 | } |
| 371 | ui.agent.UserMessage(ctx, message) |
| 372 | } |
| 373 | continue |
| 374 | } |
| 375 | |
| 376 | // Send it to the LLM |
| 377 | // chatMsg := chatMessage{sender: "you", content: line} |
| 378 | // ui.sendChatMessage(chatMsg) |
| 379 | ui.agent.UserMessage(ctx, line) |
| 380 | } |
| 381 | } |
| 382 | } |
| 383 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 384 | func (ui *TermUI) updatePrompt(thinking bool) { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 385 | var t string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 386 | if thinking { |
| 387 | // Emoji don't seem to work here? Messes up my terminal. |
| Josh Bleecher Snyder | a77889b | 2025-07-28 13:08:14 -0700 | [diff] [blame] | 388 | t = " *" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 389 | } |
| Josh Bleecher Snyder | a77889b | 2025-07-28 13:08:14 -0700 | [diff] [blame] | 390 | p := fmt.Sprintf("%s%s> ", ui.agent.Slug(), t) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 391 | ui.trm.SetPrompt(p) |
| 392 | } |
| 393 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 394 | func (ui *TermUI) initializeTerminalUI(ctx context.Context) error { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 395 | ui.mu.Lock() |
| 396 | defer ui.mu.Unlock() |
| 397 | |
| 398 | if !term.IsTerminal(int(ui.stdin.Fd())) { |
| Philip Zeyliger | c5b8ed4 | 2025-05-05 20:28:34 +0000 | [diff] [blame] | 399 | return fmt.Errorf("this command requires terminal I/O when termui=true") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 400 | } |
| 401 | |
| 402 | oldState, err := term.MakeRaw(int(ui.stdin.Fd())) |
| 403 | if err != nil { |
| 404 | return err |
| 405 | } |
| 406 | ui.oldState = oldState |
| 407 | ui.trm = term.NewTerminal(ui.stdin, "") |
| 408 | width, height, err := term.GetSize(int(ui.stdin.Fd())) |
| 409 | if err != nil { |
| Josh Bleecher Snyder | 2153f8b | 2025-07-04 02:41:20 +0000 | [diff] [blame] | 410 | return fmt.Errorf("get terminal size: %v", err) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 411 | } |
| 412 | ui.trm.SetSize(width, height) |
| 413 | // Handle terminal resizes... |
| 414 | sig := make(chan os.Signal, 1) |
| 415 | signal.Notify(sig, syscall.SIGWINCH) |
| 416 | go func() { |
| 417 | for { |
| 418 | <-sig |
| 419 | newWidth, newHeight, err := term.GetSize(int(ui.stdin.Fd())) |
| 420 | if err != nil { |
| 421 | continue |
| 422 | } |
| 423 | if newWidth != width || newHeight != height { |
| 424 | width, height = newWidth, newHeight |
| 425 | ui.trm.SetSize(width, height) |
| 426 | } |
| 427 | } |
| 428 | }() |
| 429 | |
| 430 | ui.updatePrompt(false) |
| Josh Bleecher Snyder | 2153f8b | 2025-07-04 02:41:20 +0000 | [diff] [blame] | 431 | ui.pushTerminalTitle() |
| 432 | ui.setTerminalTitle("sketch") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 433 | |
| 434 | // This is the only place where we should call fe.trm.Write: |
| 435 | go func() { |
| Sean McCullough | a4b19f8 | 2025-05-05 10:22:59 -0700 | [diff] [blame] | 436 | var lastMsg *chatMessage |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 437 | for { |
| 438 | select { |
| 439 | case <-ctx.Done(): |
| 440 | return |
| 441 | case msg := <-ui.chatMsgCh: |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 442 | func() { |
| 443 | defer ui.messageWaitGroup.Done() |
| Sean McCullough | a4b19f8 | 2025-05-05 10:22:59 -0700 | [diff] [blame] | 444 | // Update prompt before writing, because otherwise it doesn't redraw the prompt. |
| 445 | ui.updatePrompt(msg.thinking) |
| 446 | lastMsg = &msg |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 447 | // Sometimes claude doesn't say anything when it runs tools. |
| 448 | // No need to output anything in that case. |
| 449 | if strings.TrimSpace(msg.content) == "" { |
| 450 | return |
| 451 | } |
| 452 | s := fmt.Sprintf("%s %s\n", msg.sender, msg.content) |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 453 | ui.trm.Write([]byte(s)) |
| 454 | }() |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 455 | case logLine := <-ui.termLogCh: |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 456 | func() { |
| 457 | defer ui.messageWaitGroup.Done() |
| Sean McCullough | a4b19f8 | 2025-05-05 10:22:59 -0700 | [diff] [blame] | 458 | if lastMsg != nil { |
| 459 | ui.updatePrompt(lastMsg.thinking) |
| 460 | } else { |
| 461 | ui.updatePrompt(false) |
| 462 | } |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 463 | b := []byte(logLine + "\n") |
| 464 | ui.trm.Write(b) |
| 465 | }() |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 466 | } |
| 467 | } |
| 468 | }() |
| 469 | |
| 470 | return nil |
| 471 | } |
| 472 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 473 | func (ui *TermUI) RestoreOldState() error { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 474 | ui.mu.Lock() |
| 475 | defer ui.mu.Unlock() |
| Josh Bleecher Snyder | 2153f8b | 2025-07-04 02:41:20 +0000 | [diff] [blame] | 476 | ui.setTerminalTitle("") |
| 477 | ui.popTerminalTitle() |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 478 | return term.Restore(int(ui.stdin.Fd()), ui.oldState) |
| 479 | } |
| 480 | |
| 481 | // AppendChatMessage is for showing responses the user's request, conversational dialog etc |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 482 | func (ui *TermUI) AppendChatMessage(msg chatMessage) { |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 483 | ui.messageWaitGroup.Add(1) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 484 | ui.chatMsgCh <- msg |
| 485 | } |
| 486 | |
| 487 | // AppendSystemMessage is for debug information, errors and such that are not part of the "conversation" per se, |
| 488 | // but still need to be shown to the user. |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 489 | func (ui *TermUI) AppendSystemMessage(fmtString string, args ...any) { |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 490 | ui.messageWaitGroup.Add(1) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 491 | ui.termLogCh <- fmt.Sprintf(fmtString, args...) |
| 492 | } |
| Josh Bleecher Snyder | 0137a7f | 2025-04-30 01:16:35 +0000 | [diff] [blame] | 493 | |
| Josh Bleecher Snyder | 8fdf753 | 2025-05-06 00:56:12 +0000 | [diff] [blame] | 494 | // getShortSHA returns the short SHA for the given git reference, falling back to the original SHA on error. |
| 495 | func getShortSHA(sha string) string { |
| 496 | cmd := exec.Command("git", "rev-parse", "--short", sha) |
| Josh Bleecher Snyder | 0137a7f | 2025-04-30 01:16:35 +0000 | [diff] [blame] | 497 | shortSha, err := cmd.Output() |
| 498 | if err == nil { |
| 499 | shortStr := strings.TrimSpace(string(shortSha)) |
| 500 | if shortStr != "" { |
| 501 | return shortStr |
| 502 | } |
| 503 | } |
| Josh Bleecher Snyder | 0137a7f | 2025-04-30 01:16:35 +0000 | [diff] [blame] | 504 | return sha |
| 505 | } |
| philip.zeyliger | 6d3de48 | 2025-06-10 19:38:14 -0700 | [diff] [blame] | 506 | |
| 507 | // isGitHubRepo checks if the git origin URL is a GitHub repository |
| 508 | func (ui *TermUI) isGitHubRepo() bool { |
| 509 | gitOrigin := ui.agent.GitOrigin() |
| 510 | if gitOrigin == "" { |
| 511 | return false |
| 512 | } |
| 513 | |
| 514 | // Common GitHub URL patterns |
| 515 | patterns := []string{ |
| 516 | `^https://github\.com/[^/]+/[^/\s.]+(?:\.git)?`, |
| 517 | `^git@github\.com:[^/]+/[^/\s.]+(?:\.git)?`, |
| 518 | `^git://github\.com/[^/]+/[^/\s.]+(?:\.git)?`, |
| 519 | } |
| 520 | |
| 521 | for _, pattern := range patterns { |
| 522 | if matched, _ := regexp.MatchString(pattern, gitOrigin); matched { |
| 523 | return true |
| 524 | } |
| 525 | } |
| 526 | return false |
| 527 | } |
| 528 | |
| 529 | // getGitHubBranchURL generates a GitHub branch URL if conditions are met |
| 530 | func (ui *TermUI) getGitHubBranchURL(branchName string) string { |
| 531 | if !ui.agent.LinkToGitHub() || branchName == "" { |
| 532 | return "" |
| 533 | } |
| 534 | |
| 535 | gitOrigin := ui.agent.GitOrigin() |
| 536 | if gitOrigin == "" || !ui.isGitHubRepo() { |
| 537 | return "" |
| 538 | } |
| 539 | |
| 540 | // Extract owner and repo from GitHub URL |
| 541 | patterns := []string{ |
| 542 | `^https://github\.com/([^/]+)/([^/\s.]+)(?:\.git)?`, |
| 543 | `^git@github\.com:([^/]+)/([^/\s.]+)(?:\.git)?`, |
| 544 | `^git://github\.com/([^/]+)/([^/\s.]+)(?:\.git)?`, |
| 545 | } |
| 546 | |
| 547 | for _, pattern := range patterns { |
| 548 | re := regexp.MustCompile(pattern) |
| 549 | matches := re.FindStringSubmatch(gitOrigin) |
| 550 | if len(matches) == 3 { |
| 551 | owner := matches[1] |
| 552 | repo := matches[2] |
| 553 | return fmt.Sprintf("https://github.com/%s/%s/tree/%s", owner, repo, branchName) |
| 554 | } |
| 555 | } |
| 556 | return "" |
| 557 | } |
| Josh Bleecher Snyder | 2153f8b | 2025-07-04 02:41:20 +0000 | [diff] [blame] | 558 | |
| 559 | // pushTerminalTitle pushes the current terminal title onto the title stack |
| 560 | // Only works on xterm-compatible terminals, but does no harm elsewhere |
| 561 | func (ui *TermUI) pushTerminalTitle() { |
| 562 | fmt.Fprintf(ui.stderr, "\033[22;0t") |
| 563 | ui.titlePushed = true |
| 564 | } |
| 565 | |
| 566 | // popTerminalTitle pops the terminal title from the title stack |
| 567 | func (ui *TermUI) popTerminalTitle() { |
| 568 | if ui.titlePushed { |
| 569 | fmt.Fprintf(ui.stderr, "\033[23;0t") |
| 570 | ui.titlePushed = false |
| 571 | } |
| 572 | } |
| 573 | |
| 574 | func (ui *TermUI) setTerminalTitle(title string) { |
| 575 | fmt.Fprintf(ui.stderr, "\033]0;%s\007", title) |
| 576 | } |
| 577 | |
| 578 | // updateTitleWithSlug updates the terminal title with slug slug |
| 579 | func (ui *TermUI) updateTitleWithSlug(slug string) { |
| 580 | ui.mu.Lock() |
| 581 | defer ui.mu.Unlock() |
| 582 | ui.currentSlug = slug |
| 583 | title := "sketch" |
| 584 | if slug != "" { |
| 585 | title = fmt.Sprintf("sketch: %s", slug) |
| 586 | } |
| 587 | ui.setTerminalTitle(title) |
| 588 | } |