| 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" |
| 13 | "strings" |
| 14 | "sync" |
| 15 | "syscall" |
| 16 | "text/template" |
| 17 | "time" |
| 18 | |
| Josh Bleecher Snyder | a0801ad | 2025-04-25 19:34:53 +0000 | [diff] [blame] | 19 | "github.com/dustin/go-humanize" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 20 | "github.com/fatih/color" |
| 21 | "golang.org/x/term" |
| 22 | "sketch.dev/loop" |
| 23 | ) |
| 24 | |
| 25 | var ( |
| 26 | // toolUseTemplTxt defines how tool invocations appear in the terminal UI. |
| 27 | // Keep this template in sync with the tools defined in claudetool package |
| 28 | // and registered in loop/agent.go. |
| 29 | // Add formatting for new tools as they are created. |
| 30 | // 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] | 31 | toolUseTemplTxt = `{{if .msg.ToolError}}ć°ļø {{end -}} |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 32 | {{if eq .msg.ToolName "think" -}} |
| 33 | š§ {{.input.thoughts -}} |
| 34 | {{else if eq .msg.ToolName "keyword_search" -}} |
| Josh Bleecher Snyder | 453a62f | 2025-05-01 10:14:33 -0700 | [diff] [blame] | 35 | š {{ .input.query}}: {{.input.search_terms -}} |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 36 | {{else if eq .msg.ToolName "bash" -}} |
| Philip Zeyliger | b60f0f2 | 2025-04-23 18:19:32 +0000 | [diff] [blame] | 37 | š„ļø{{if .input.background}}š{{end}} {{ .input.command -}} |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 38 | {{else if eq .msg.ToolName "patch" -}} |
| 39 | āØļø {{.input.path -}} |
| 40 | {{else if eq .msg.ToolName "done" -}} |
| 41 | {{/* nothing to show here, the agent will write more in its next message */}} |
| 42 | {{else if eq .msg.ToolName "title" -}} |
| Josh Bleecher Snyder | 47b1936 | 2025-04-30 01:34:14 +0000 | [diff] [blame] | 43 | š·ļø {{.input.title}} |
| Josh Bleecher Snyder | a2a3150 | 2025-05-07 12:37:18 +0000 | [diff] [blame] | 44 | {{else if eq .msg.ToolName "precommit" -}} |
| Josh Bleecher Snyder | 47b1936 | 2025-04-30 01:34:14 +0000 | [diff] [blame] | 45 | š± git branch: sketch/{{.input.branch_name}} |
| Josh Bleecher Snyder | 74d690e | 2025-05-14 18:16:03 -0700 | [diff] [blame] | 46 | {{else if eq .msg.ToolName "about_sketch" -}} |
| 47 | š About Sketch |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 48 | {{else if eq .msg.ToolName "str_replace_editor" -}} |
| 49 | āļø {{.input.file_path -}} |
| 50 | {{else if eq .msg.ToolName "codereview" -}} |
| 51 | š Running automated code review, may be slow |
| Sean McCullough | 485afc6 | 2025-04-28 14:28:39 -0700 | [diff] [blame] | 52 | {{else if eq .msg.ToolName "multiplechoice" -}} |
| 53 | š {{.input.question}} |
| 54 | {{ range .input.responseOptions -}} |
| 55 | - {{ .caption}}: {{.responseText}} |
| 56 | {{end -}} |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 57 | {{else -}} |
| Josh Bleecher Snyder | 47b1936 | 2025-04-30 01:34:14 +0000 | [diff] [blame] | 58 | š ļø {{ .msg.ToolName}}: {{.msg.ToolInput -}} |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 59 | {{end -}} |
| 60 | ` |
| 61 | toolUseTmpl = template.Must(template.New("tool_use").Parse(toolUseTemplTxt)) |
| 62 | ) |
| 63 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 64 | type TermUI struct { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 65 | stdin *os.File |
| 66 | stdout *os.File |
| 67 | stderr *os.File |
| 68 | |
| 69 | agent loop.CodingAgent |
| 70 | httpURL string |
| 71 | |
| 72 | trm *term.Terminal |
| 73 | |
| 74 | // the chatMsgCh channel is for "conversation" messages, like responses to user input |
| 75 | // from the LLM, or output from executing slash-commands issued by the user. |
| 76 | chatMsgCh chan chatMessage |
| 77 | |
| 78 | // the log channel is for secondary messages, like logging, errors, and debug information |
| 79 | // from local and remove subproceses. |
| 80 | termLogCh chan string |
| 81 | |
| 82 | // protects following |
| 83 | mu sync.Mutex |
| 84 | oldState *term.State |
| 85 | // Tracks branches that were pushed during the session |
| 86 | pushedBranches map[string]struct{} |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 87 | |
| 88 | // Pending message count, for graceful shutdown |
| 89 | messageWaitGroup sync.WaitGroup |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 90 | } |
| 91 | |
| 92 | type chatMessage struct { |
| 93 | idx int |
| 94 | sender string |
| 95 | content string |
| 96 | thinking bool |
| 97 | } |
| 98 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 99 | func New(agent loop.CodingAgent, httpURL string) *TermUI { |
| 100 | return &TermUI{ |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 101 | agent: agent, |
| 102 | stdin: os.Stdin, |
| 103 | stdout: os.Stdout, |
| 104 | stderr: os.Stderr, |
| 105 | httpURL: httpURL, |
| 106 | chatMsgCh: make(chan chatMessage, 1), |
| 107 | termLogCh: make(chan string, 1), |
| 108 | pushedBranches: make(map[string]struct{}), |
| 109 | } |
| 110 | } |
| 111 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 112 | func (ui *TermUI) Run(ctx context.Context) error { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 113 | fmt.Println(`š ` + ui.httpURL + `/`) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 114 | fmt.Println(`š¬ type 'help' for help`) |
| 115 | fmt.Println() |
| 116 | |
| 117 | // Start up the main terminal UI: |
| 118 | if err := ui.initializeTerminalUI(ctx); err != nil { |
| 119 | return err |
| 120 | } |
| 121 | go ui.receiveMessagesLoop(ctx) |
| 122 | if err := ui.inputLoop(ctx); err != nil { |
| 123 | return err |
| 124 | } |
| 125 | return nil |
| 126 | } |
| 127 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 128 | func (ui *TermUI) LogToolUse(resp *loop.AgentMessage) { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 129 | inputData := map[string]any{} |
| 130 | if err := json.Unmarshal([]byte(resp.ToolInput), &inputData); err != nil { |
| 131 | ui.AppendSystemMessage("error: %v", err) |
| 132 | return |
| 133 | } |
| 134 | buf := bytes.Buffer{} |
| 135 | if err := toolUseTmpl.Execute(&buf, map[string]any{"msg": resp, "input": inputData, "output": resp.ToolResult}); err != nil { |
| 136 | ui.AppendSystemMessage("error: %v", err) |
| 137 | return |
| 138 | } |
| 139 | ui.AppendSystemMessage("%s\n", buf.String()) |
| 140 | } |
| 141 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 142 | func (ui *TermUI) receiveMessagesLoop(ctx context.Context) { |
| Philip Zeyliger | b7c5875 | 2025-05-01 10:10:17 -0700 | [diff] [blame] | 143 | it := ui.agent.NewIterator(ctx, 0) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 144 | bold := color.New(color.Bold).SprintFunc() |
| 145 | for { |
| 146 | select { |
| 147 | case <-ctx.Done(): |
| 148 | return |
| 149 | default: |
| 150 | } |
| Philip Zeyliger | b7c5875 | 2025-05-01 10:10:17 -0700 | [diff] [blame] | 151 | resp := it.Next() |
| 152 | if resp == nil { |
| 153 | return |
| 154 | } |
| Josh Bleecher Snyder | 4d54493 | 2025-05-07 13:33:53 +0000 | [diff] [blame] | 155 | if resp.HideOutput { |
| 156 | continue |
| 157 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 158 | // Typically a user message will start the thinking and a (top-level |
| 159 | // conversation) end of turn will stop it. |
| 160 | thinking := !(resp.EndOfTurn && resp.ParentConversationID == nil) |
| 161 | |
| 162 | switch resp.Type { |
| 163 | case loop.AgentMessageType: |
| Josh Bleecher Snyder | 2978ab2 | 2025-04-30 10:29:32 -0700 | [diff] [blame] | 164 | ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "š“ļø ", content: resp.Content}) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 165 | case loop.ToolUseMessageType: |
| 166 | ui.LogToolUse(resp) |
| 167 | case loop.ErrorMessageType: |
| 168 | ui.AppendSystemMessage("ā %s", resp.Content) |
| 169 | case loop.BudgetMessageType: |
| 170 | ui.AppendSystemMessage("š° %s", resp.Content) |
| 171 | case loop.AutoMessageType: |
| 172 | ui.AppendSystemMessage("š§ %s", resp.Content) |
| 173 | case loop.UserMessageType: |
| Josh Bleecher Snyder | c2d2610 | 2025-04-30 06:19:43 -0700 | [diff] [blame] | 174 | ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "š¦ø", content: resp.Content}) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 175 | case loop.CommitMessageType: |
| 176 | // Display each commit in the terminal |
| 177 | for _, commit := range resp.Commits { |
| 178 | if commit.PushedBranch != "" { |
| Sean McCullough | 43664f6 | 2025-04-20 16:13:03 -0700 | [diff] [blame] | 179 | ui.AppendSystemMessage("š new commit: [%s] %s\npushed to: %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch)) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 180 | |
| 181 | // Track the pushed branch in our map |
| 182 | ui.mu.Lock() |
| 183 | ui.pushedBranches[commit.PushedBranch] = struct{}{} |
| 184 | ui.mu.Unlock() |
| 185 | } else { |
| 186 | ui.AppendSystemMessage("š new commit: [%s] %s", commit.Hash[:8], commit.Subject) |
| 187 | } |
| 188 | } |
| 189 | default: |
| 190 | ui.AppendSystemMessage("ā Unexpected Message Type %s %v", resp.Type, resp) |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 195 | func (ui *TermUI) inputLoop(ctx context.Context) error { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 196 | for { |
| 197 | line, err := ui.trm.ReadLine() |
| 198 | if errors.Is(err, io.EOF) { |
| 199 | ui.AppendSystemMessage("\n") |
| 200 | line = "exit" |
| 201 | } else if err != nil { |
| 202 | return err |
| 203 | } |
| 204 | |
| 205 | line = strings.TrimSpace(line) |
| 206 | |
| 207 | switch line { |
| 208 | case "?", "help": |
| Josh Bleecher Snyder | 8506894 | 2025-04-30 10:51:27 -0700 | [diff] [blame] | 209 | ui.AppendSystemMessage(`General use: |
| 210 | Use chat to ask sketch to tackle a task or answer a question about this repo. |
| 211 | |
| 212 | Special commands: |
| 213 | - help, ? : Show this help message |
| 214 | - budget : Show original budget |
| 215 | - usage, cost : Show current token usage and cost |
| Josh Bleecher Snyder | 3e2111b | 2025-04-30 17:53:28 +0000 | [diff] [blame] | 216 | - browser, open, b : Open current conversation in browser |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 217 | - stop, cancel, abort : Cancel the current operation |
| Josh Bleecher Snyder | 8506894 | 2025-04-30 10:51:27 -0700 | [diff] [blame] | 218 | - exit, quit, q : Exit sketch |
| 219 | - ! <command> : Execute a shell command (e.g. !ls -la)`) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 220 | case "budget": |
| 221 | originalBudget := ui.agent.OriginalBudget() |
| 222 | ui.AppendSystemMessage("š° Budget summary:") |
| 223 | if originalBudget.MaxResponses > 0 { |
| 224 | ui.AppendSystemMessage("- Max responses: %d", originalBudget.MaxResponses) |
| 225 | } |
| 226 | if originalBudget.MaxWallTime > 0 { |
| 227 | ui.AppendSystemMessage("- Max wall time: %v", originalBudget.MaxWallTime) |
| 228 | } |
| 229 | ui.AppendSystemMessage("- Max total cost: %0.2f", originalBudget.MaxDollars) |
| Josh Bleecher Snyder | 3e2111b | 2025-04-30 17:53:28 +0000 | [diff] [blame] | 230 | case "browser", "open", "b": |
| 231 | if ui.httpURL != "" { |
| 232 | ui.AppendSystemMessage("š Opening %s in browser", ui.httpURL) |
| 233 | go ui.agent.OpenBrowser(ui.httpURL) |
| 234 | } else { |
| 235 | ui.AppendSystemMessage("ā No web URL available for this session") |
| 236 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 237 | case "usage", "cost": |
| 238 | totalUsage := ui.agent.TotalUsage() |
| 239 | ui.AppendSystemMessage("š° Current usage summary:") |
| Josh Bleecher Snyder | a0801ad | 2025-04-25 19:34:53 +0000 | [diff] [blame] | 240 | ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens()))) |
| 241 | ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens))) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 242 | ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses) |
| 243 | ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second)) |
| 244 | ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD) |
| 245 | case "bye", "exit", "q", "quit": |
| 246 | ui.trm.SetPrompt("") |
| 247 | // Display final usage stats |
| 248 | totalUsage := ui.agent.TotalUsage() |
| 249 | ui.AppendSystemMessage("š° Final usage summary:") |
| Josh Bleecher Snyder | a0801ad | 2025-04-25 19:34:53 +0000 | [diff] [blame] | 250 | ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens()))) |
| 251 | ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens))) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 252 | ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses) |
| 253 | ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second)) |
| 254 | ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD) |
| 255 | |
| 256 | // Display pushed branches |
| 257 | ui.mu.Lock() |
| 258 | if len(ui.pushedBranches) > 0 { |
| 259 | // Convert map keys to a slice for display |
| 260 | branches := make([]string, 0, len(ui.pushedBranches)) |
| 261 | for branch := range ui.pushedBranches { |
| 262 | branches = append(branches, branch) |
| 263 | } |
| 264 | |
| Philip Zeyliger | 49edc92 | 2025-05-14 09:45:45 -0700 | [diff] [blame] | 265 | initialCommitRef := getShortSHA(ui.agent.SketchGitBase()) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 266 | if len(branches) == 1 { |
| 267 | ui.AppendSystemMessage("\nš Branch pushed during session: %s", branches[0]) |
| Josh Bleecher Snyder | 0137a7f | 2025-04-30 01:16:35 +0000 | [diff] [blame] | 268 | ui.AppendSystemMessage("š To add those changes to your branch: git cherry-pick %s..%s", initialCommitRef, branches[0]) |
| Philip Zeyliger | 49edc92 | 2025-05-14 09:45:45 -0700 | [diff] [blame] | 269 | ui.AppendSystemMessage("š or git merge %s", branches[0]) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 270 | } else { |
| 271 | ui.AppendSystemMessage("\nš Branches pushed during session:") |
| 272 | for _, branch := range branches { |
| 273 | ui.AppendSystemMessage("- %s", branch) |
| 274 | } |
| 275 | ui.AppendSystemMessage("\nš To add all those changes to your branch:") |
| 276 | for _, branch := range branches { |
| Josh Bleecher Snyder | 0137a7f | 2025-04-30 01:16:35 +0000 | [diff] [blame] | 277 | ui.AppendSystemMessage("git cherry-pick %s..%s", initialCommitRef, branch) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 278 | } |
| Philip Zeyliger | 49edc92 | 2025-05-14 09:45:45 -0700 | [diff] [blame] | 279 | ui.AppendSystemMessage("\nš To add all those changes to your branch:") |
| 280 | for _, branch := range branches { |
| 281 | ui.AppendSystemMessage("git cherry-pick %s..%s", initialCommitRef, branch) |
| 282 | } |
| 283 | ui.AppendSystemMessage("\nš or:") |
| 284 | for _, branch := range branches { |
| 285 | ui.AppendSystemMessage("git merge %s", branch) |
| 286 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 287 | } |
| 288 | } |
| 289 | ui.mu.Unlock() |
| 290 | |
| 291 | ui.AppendSystemMessage("\nš Goodbye!") |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 292 | // Wait for all pending messages to be processed before exiting |
| 293 | ui.messageWaitGroup.Wait() |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 294 | return nil |
| 295 | case "stop", "cancel", "abort": |
| Sean McCullough | edc88dc | 2025-04-30 02:55:01 +0000 | [diff] [blame] | 296 | ui.agent.CancelTurn(fmt.Errorf("user canceled the operation")) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 297 | case "panic": |
| 298 | panic("user forced a panic") |
| 299 | default: |
| 300 | if line == "" { |
| 301 | continue |
| 302 | } |
| 303 | if strings.HasPrefix(line, "!") { |
| 304 | // Execute as shell command |
| 305 | line = line[1:] // remove the '!' prefix |
| 306 | sendToLLM := strings.HasPrefix(line, "!") |
| 307 | if sendToLLM { |
| 308 | line = line[1:] // remove the second '!' |
| 309 | } |
| 310 | |
| 311 | // Create a cmd and run it |
| 312 | // TODO: ui.trm contains a mutex inside its write call. |
| 313 | // It is potentially safe to attach ui.trm directly to this |
| 314 | // cmd object's Stdout/Stderr and stream the output. |
| 315 | // That would make a big difference for, e.g. wget. |
| 316 | cmd := exec.Command("bash", "-c", line) |
| 317 | out, err := cmd.CombinedOutput() |
| 318 | ui.AppendSystemMessage("%s", out) |
| 319 | if err != nil { |
| 320 | ui.AppendSystemMessage("ā Command error: %v", err) |
| 321 | } |
| 322 | if sendToLLM { |
| 323 | // Send the command and its output to the agent |
| 324 | message := fmt.Sprintf("I ran the command: `%s`\nOutput:\n```\n%s```", line, out) |
| 325 | if err != nil { |
| 326 | message += fmt.Sprintf("\n\nError: %v", err) |
| 327 | } |
| 328 | ui.agent.UserMessage(ctx, message) |
| 329 | } |
| 330 | continue |
| 331 | } |
| 332 | |
| 333 | // Send it to the LLM |
| 334 | // chatMsg := chatMessage{sender: "you", content: line} |
| 335 | // ui.sendChatMessage(chatMsg) |
| 336 | ui.agent.UserMessage(ctx, line) |
| 337 | } |
| 338 | } |
| 339 | } |
| 340 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 341 | func (ui *TermUI) updatePrompt(thinking bool) { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 342 | var t string |
| 343 | |
| 344 | if thinking { |
| 345 | // Emoji don't seem to work here? Messes up my terminal. |
| 346 | t = "*" |
| 347 | } |
| Josh Bleecher Snyder | 23b6a2d | 2025-04-30 04:07:52 +0000 | [diff] [blame] | 348 | p := fmt.Sprintf("%s ($%0.2f/%0.2f)%s> ", |
| 349 | ui.httpURL, ui.agent.TotalUsage().TotalCostUSD, ui.agent.OriginalBudget().MaxDollars, t) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 350 | ui.trm.SetPrompt(p) |
| 351 | } |
| 352 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 353 | func (ui *TermUI) initializeTerminalUI(ctx context.Context) error { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 354 | ui.mu.Lock() |
| 355 | defer ui.mu.Unlock() |
| 356 | |
| 357 | if !term.IsTerminal(int(ui.stdin.Fd())) { |
| Philip Zeyliger | c5b8ed4 | 2025-05-05 20:28:34 +0000 | [diff] [blame] | 358 | return fmt.Errorf("this command requires terminal I/O when termui=true") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 359 | } |
| 360 | |
| 361 | oldState, err := term.MakeRaw(int(ui.stdin.Fd())) |
| 362 | if err != nil { |
| 363 | return err |
| 364 | } |
| 365 | ui.oldState = oldState |
| 366 | ui.trm = term.NewTerminal(ui.stdin, "") |
| 367 | width, height, err := term.GetSize(int(ui.stdin.Fd())) |
| 368 | if err != nil { |
| 369 | return fmt.Errorf("Error getting terminal size: %v\n", err) |
| 370 | } |
| 371 | ui.trm.SetSize(width, height) |
| 372 | // Handle terminal resizes... |
| 373 | sig := make(chan os.Signal, 1) |
| 374 | signal.Notify(sig, syscall.SIGWINCH) |
| 375 | go func() { |
| 376 | for { |
| 377 | <-sig |
| 378 | newWidth, newHeight, err := term.GetSize(int(ui.stdin.Fd())) |
| 379 | if err != nil { |
| 380 | continue |
| 381 | } |
| 382 | if newWidth != width || newHeight != height { |
| 383 | width, height = newWidth, newHeight |
| 384 | ui.trm.SetSize(width, height) |
| 385 | } |
| 386 | } |
| 387 | }() |
| 388 | |
| 389 | ui.updatePrompt(false) |
| 390 | |
| 391 | // This is the only place where we should call fe.trm.Write: |
| 392 | go func() { |
| Sean McCullough | a4b19f8 | 2025-05-05 10:22:59 -0700 | [diff] [blame] | 393 | var lastMsg *chatMessage |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 394 | for { |
| 395 | select { |
| 396 | case <-ctx.Done(): |
| 397 | return |
| 398 | case msg := <-ui.chatMsgCh: |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 399 | func() { |
| 400 | defer ui.messageWaitGroup.Done() |
| Sean McCullough | a4b19f8 | 2025-05-05 10:22:59 -0700 | [diff] [blame] | 401 | // Update prompt before writing, because otherwise it doesn't redraw the prompt. |
| 402 | ui.updatePrompt(msg.thinking) |
| 403 | lastMsg = &msg |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 404 | // Sometimes claude doesn't say anything when it runs tools. |
| 405 | // No need to output anything in that case. |
| 406 | if strings.TrimSpace(msg.content) == "" { |
| 407 | return |
| 408 | } |
| 409 | s := fmt.Sprintf("%s %s\n", msg.sender, msg.content) |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 410 | ui.trm.Write([]byte(s)) |
| 411 | }() |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 412 | case logLine := <-ui.termLogCh: |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 413 | func() { |
| 414 | defer ui.messageWaitGroup.Done() |
| Sean McCullough | a4b19f8 | 2025-05-05 10:22:59 -0700 | [diff] [blame] | 415 | if lastMsg != nil { |
| 416 | ui.updatePrompt(lastMsg.thinking) |
| 417 | } else { |
| 418 | ui.updatePrompt(false) |
| 419 | } |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 420 | b := []byte(logLine + "\n") |
| 421 | ui.trm.Write(b) |
| 422 | }() |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 423 | } |
| 424 | } |
| 425 | }() |
| 426 | |
| 427 | return nil |
| 428 | } |
| 429 | |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 430 | func (ui *TermUI) RestoreOldState() error { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 431 | ui.mu.Lock() |
| 432 | defer ui.mu.Unlock() |
| 433 | return term.Restore(int(ui.stdin.Fd()), ui.oldState) |
| 434 | } |
| 435 | |
| 436 | // AppendChatMessage is for showing responses the user's request, conversational dialog etc |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 437 | func (ui *TermUI) AppendChatMessage(msg chatMessage) { |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 438 | ui.messageWaitGroup.Add(1) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 439 | ui.chatMsgCh <- msg |
| 440 | } |
| 441 | |
| 442 | // AppendSystemMessage is for debug information, errors and such that are not part of the "conversation" per se, |
| 443 | // but still need to be shown to the user. |
| David Crawshaw | 93fec60 | 2025-05-05 08:40:06 -0700 | [diff] [blame] | 444 | func (ui *TermUI) AppendSystemMessage(fmtString string, args ...any) { |
| Josh Bleecher Snyder | b1e8157 | 2025-05-01 00:53:27 +0000 | [diff] [blame] | 445 | ui.messageWaitGroup.Add(1) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 446 | ui.termLogCh <- fmt.Sprintf(fmtString, args...) |
| 447 | } |
| Josh Bleecher Snyder | 0137a7f | 2025-04-30 01:16:35 +0000 | [diff] [blame] | 448 | |
| Josh Bleecher Snyder | 8fdf753 | 2025-05-06 00:56:12 +0000 | [diff] [blame] | 449 | // getShortSHA returns the short SHA for the given git reference, falling back to the original SHA on error. |
| 450 | func getShortSHA(sha string) string { |
| 451 | cmd := exec.Command("git", "rev-parse", "--short", sha) |
| Josh Bleecher Snyder | 0137a7f | 2025-04-30 01:16:35 +0000 | [diff] [blame] | 452 | shortSha, err := cmd.Output() |
| 453 | if err == nil { |
| 454 | shortStr := strings.TrimSpace(string(shortSha)) |
| 455 | if shortStr != "" { |
| 456 | return shortStr |
| 457 | } |
| 458 | } |
| Josh Bleecher Snyder | 0137a7f | 2025-04-30 01:16:35 +0000 | [diff] [blame] | 459 | return sha |
| 460 | } |