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