diff --git a/README.md b/README.md index dea8543..38db45e 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,7 @@ are gone, rexdiff marks the comment as stale. | `\|` | side by side or top to bottom | | `1` … `5` | overview, guide, diff, all files, or pull request | | `r` | in the guide: write it again | +| `a` | in the guide: pick the agent that writes it | | `?` | all keys | ## Tabs @@ -84,9 +85,13 @@ are gone, rexdiff marks the comment as stale. works with no forge and no login. - **Guide**: the changes in the order of their meaning, as on [pulls.review]. An agent groups the files into sections with a title and a summary; the diff - of each file shows beside its section. rexdiff runs the first of `claude -p`, - `pi -p`, and `codex exec -` that is installed, or `guide_agent`. It keeps - each guide, so the agent writes it once. Press `r` to write it again. + of each file shows beside its section. rexdiff runs the first of claude, pi, + codex, opencode, cursor-agent, and agy that is installed, or `guide_agent`. + Press `a` to pick another agent; in a terminal with the kitty graphics + protocol (Rex, Ghostty, kitty), the list shows their logos. opencode, + cursor-agent, and agy take the diff as one argument, so a diff over about + 1 MB (128 KB on Linux) turns them off. It keeps each + guide, so the agent writes it once. Press `r` to write it again. - **Diff**: the changes, one file at a time. A wide pane shows them side by side; a narrow one, top to bottom. Binary files are not diffed. @@ -110,8 +115,9 @@ Other settings: - `markdown_view` - `file_list` - `file_list_width` -- `guide_agent`: the command that writes the guide. It reads the prompt on its - standard input, for example `"claude -p --model sonnet"` +- `guide_agent`: the agent that writes the guide: `claude`, `pi`, `codex`, + `opencode`, `cursor-agent`, or `agy`, or a command that reads the prompt on + its standard input, for example `"claude -p --model sonnet"` - `diff_signs`: `true` marks changed lines with `+` and `-`, in place of a coloured bar - `cursor_line`: `false` turns off the tint of the line at the cursor - `renderer`: `"kitty"` draws the screen as pictures with the kitty graphics diff --git a/cmd/rexdiff/install.go b/cmd/rexdiff/install.go index 095f782..34ca6ed 100644 --- a/cmd/rexdiff/install.go +++ b/cmd/rexdiff/install.go @@ -44,7 +44,7 @@ local settings = { -- key = "shift+cmd+r", -- the key of the toggle, or false for none -- placement = "split", -- split, zoomed, tab, or overlay -- layout = "unified", -- split (side by side when it fits) or unified - -- guide_agent = "claude -p", -- the agent that writes the Guide tab + -- guide_agent = "claude", -- the agent that writes the Guide tab: claude, pi, codex, opencode, cursor-agent, agy, or a command -- renderer = "kitty", -- draw with the kitty graphics protocol, with no flicker } diff --git a/tui/config.go b/tui/config.go index e5cc516..4b270fc 100644 --- a/tui/config.go +++ b/tui/config.go @@ -81,10 +81,11 @@ type config struct { FileList position `json:"file_list"` // FileListWidth is in columns, minListWidth or more. FileListWidth int `json:"file_list_width"` - // GuideAgent is the command that writes the Guide tab, for example - // "claude -p". It reads the prompt on its standard input and prints - // the answer. "" picks the first of claude, pi, and codex that is - // installed. + // GuideAgent is the agent that writes the Guide tab: a name of + // guideAgents, for example "agy", or a command, for example + // "claude -p --model sonnet", that reads the prompt on its standard + // input and prints the answer. "" picks the first of guideAgents that + // is installed. GuideAgent string `json:"guide_agent"` // DiffSigns marks a changed line with + or -, in place of a bar. DiffSigns bool `json:"diff_signs"` @@ -163,6 +164,7 @@ type keybindings struct { NavigatorShrink []string `json:"navigator-shrink"` OpenPR []string `json:"open-pr"` Refresh []string `json:"refresh"` + GuideAgent []string `json:"guide-agent"` Keys []string `json:"keys"` Quit []string `json:"quit"` QuitDiscard []string `json:"quit-discard"` diff --git a/tui/guide.go b/tui/guide.go index d52d420..7b45962 100644 --- a/tui/guide.go +++ b/tui/guide.go @@ -1,7 +1,7 @@ package tui // The Guide tab reads the changes in the order of their meaning, as -// pulls.review does. An agent CLI (claude, pi, or codex) groups the +// pulls.review does. An agent CLI (claude, pi, codex, and others) groups the // changed files into sections, each with a title and a short summary. The // tab shows a section at the left and the diff of one of its files at the // right. The guide of a pair of trees is kept on disk, so the agent writes @@ -19,6 +19,7 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "slices" "strings" "time" @@ -41,13 +42,48 @@ const ( ) // guideAgents are the agent CLIs that can write the guide, in the order -// that rexdiff tries them. Each one reads the prompt on its standard input. -var guideAgents = []struct{ name, command string }{ - {"claude", "claude -p"}, - {"pi", "pi -p"}, - {"codex", "codex exec -"}, +// that rexdiff tries them. Each command reads the prompt on its standard +// input. opencode, cursor-agent, and agy take the prompt only as an +// argument, so their commands pass the standard input as one, and a big +// diff does not fit. opencode and cursor-agent run in their modes that do +// not edit, since the diff can hold instructions. +var guideAgents = []agentCLI{ + {"claude", "claude -p", false}, + {"pi", "pi -p", false}, + {"codex", "codex exec -", false}, + {"opencode", `opencode run --agent plan "$(cat)"`, true}, + {"cursor-agent", `cursor-agent -p --mode ask --trust "$(cat)"`, true}, + {"agy", `agy -p "$(cat)"`, true}, } +// agentCLI is an agent CLI that can write the guide, and its command. arg +// tells that the command takes the prompt as an argument. +type agentCLI struct { + name, command string + arg bool +} + +// maxArg is the longest prompt, in bytes, that an agent can take as an +// argument. Linux caps one argument (MAX_ARG_STRLEN), and macOS all the +// arguments and the environment together (ARG_MAX). A variable, so that +// tests can set it. +var maxArg = func() int { + if runtime.GOOS == "linux" { + return 128<<10 - 1 + } + env := 0 + for _, e := range os.Environ() { + env += len(e) + 1 + 8 // the text, its NUL, and its pointer + } + return 1<<20 - env - 4<<10 // ponytail: 4 KiB for the other arguments +}() + +// bigPrompt reports whether a prompt of n bytes does not fit an argument. +func bigPrompt(n int) bool { return n > maxArg } + +// megabytes writes n bytes in MB, for the messages about a big diff. +func megabytes(n int) string { return fmt.Sprintf("%.1f MB", float64(n)/(1<<20)) } + // guideSection is one part of the guide: the files of one change. type guideSection struct { Title string `json:"title"` @@ -161,18 +197,24 @@ func (m *model) guideNote() string { case g.running: return m.guideProgress() case g.err != "": - return g.err + " · press r to try again" + return g.err + " · press r to try again, a to pick the agent" case len(m.files) == 0: return cmp.Or(m.changes.note, "no changes to explain") } - return "press r to write a guide" + return "press r to write a guide, a to pick the agent" } // guideProgress tells which agent writes the guide, and for how long. func (m *model) guideProgress() string { - name, _, _ := strings.Cut(m.guide.agent, " ") secs := int(time.Since(m.guide.started).Seconds()) - return fmt.Sprintf("%s is reading the changes… %ds", name, secs) + return fmt.Sprintf("%s is reading the changes… %ds", agentName(m.guide.agent), secs) +} + +// agentName returns the program of the command of an agent, for example +// "claude" for "claude -p". +func agentName(command string) string { + name, _, _ := strings.Cut(strings.TrimSpace(command), " ") + return name } // guideLines renders h lines of the guide column: the section, its @@ -195,7 +237,13 @@ func (m *model) guideLines(h int) (lines []string, first, outline int) { lines = append(lines, "") switch { case m.guide.running: - add(noteStyle, "↻ "+m.guideProgress()) + icon := cmp.Or(m.agentLogo(agentName(m.guide.agent)), noteStyle.Render("↻")+" ") + for i, l := range strings.Split(wrapWords(m.guideProgress(), w-2-logoCols-1), "\n") { + if i > 0 { + icon = " " + } + lines = append(lines, " "+icon+" "+noteStyle.Render(l)) + } lines = append(lines, "") case m.guide.trees != m.shownTrees: add(noteStyle, "↻ the changes moved on · r to rewrite") @@ -276,17 +324,22 @@ func (m *model) writeGuide() tea.Cmd { m.renderGuide() return nil } - agent := m.guideAgent() - if agent == "" { - m.guide.err = "no agent to write the guide: install claude or pi, or set guide_agent" + prompt := guidePrompt(m.guideCommits(), m.files) + agent := m.guideAgent(len(prompt)) + if err := checkAgent(agent, len(prompt)); err != "" { + m.guide.err = err m.renderGuide() return nil } + if bigPrompt(len(prompt)) { + m.flash(fmt.Sprintf("the diff is big (%s): %s can take long", megabytes(len(prompt)), agentName(agent))) + } m.guide.running, m.guide.started, m.guide.agent, m.guide.err = true, time.Now(), agent, "" m.renderGuide() ctx, dir, trees := m.ctx, m.repo.Root(), m.shownTrees - prompt := guidePrompt(m.guideCommits(), m.files) + // The logos go with the first frame, after Bubble Tea is on the + // alternate screen, where the terminal keeps them. return tea.Batch(frame(m.guide.started), func() tea.Msg { out, err := runAgent(ctx, dir, agent, prompt) if err != nil { @@ -350,20 +403,114 @@ func (m *model) onGuide(msg guideMsg) { } } -// guideAgent returns the command that writes the guide: the setting, or -// the first agent CLI that is installed, or "". -func (m *model) guideAgent() string { - if m.cfg.GuideAgent != "" { - return m.cfg.GuideAgent +// guideAgent returns the command that writes a guide of a prompt of n +// bytes: the agent that the user picked, or the setting, or the first +// agent CLI that is installed and takes the prompt, or "". The pick and +// the setting are a name of guideAgents or a command. +func (m *model) guideAgent(n int) string { + if pick := cmp.Or(m.guidePick, m.cfg.GuideAgent); pick != "" { + for _, a := range guideAgents { + if a.name == pick { + return a.command + } + } + return pick } for _, a := range guideAgents { - if _, err := exec.LookPath(a.name); err == nil { + if installed(a.name) && !(a.arg && bigPrompt(n)) { return a.command } } return "" } +// checkAgent returns why the agent command cannot write a guide of a +// prompt of n bytes, or "". It checks only the agent CLIs of guideAgents: +// a command of the setting can start with a variable, as in +// "FOO=1 claude -p", and the shell tells when it finds no program. +func checkAgent(command string, n int) string { + if command == "" { + return "no agent found" + } + for _, a := range guideAgents { + switch { + case a.command != command: + case !installed(a.name): + return fmt.Sprintf("agent %q not found in PATH", a.name) + case a.arg && bigPrompt(n): + return fmt.Sprintf("the diff is too big for %s (%s, at most %s)", a.name, megabytes(n), megabytes(maxArg)) + } + } + return "" +} + +// installed reports whether the PATH has program. +func installed(program string) bool { + _, err := exec.LookPath(program) + return err == nil +} + +// openGuideAgentPicker lets the user pick the agent that writes the +// guide. The list has the agent CLIs, and the command of the setting if +// it is not one of them. +// +// A diff that is too big for an argument turns off the agents that take +// the prompt as one, and marks the others, which take long on it. +func (m *model) openGuideAgentPicker() tea.Cmd { + ov := newOverlay(overlayGuideAgent, "which agent writes the guide?") + n := len(guidePrompt(m.guideCommits(), m.files)) + cur := m.guideAgent(n) + var items []pickItem + for _, a := range guideAgents { + it := pickItem{label: a.name, id: a.command, logo: m.agentLogoID(a.name)} + var tags []string + switch { + case !installed(a.name): + tags, it.off = []string{"not installed"}, a.name+" is not installed" + case a.arg && bigPrompt(n): + tags, it.off = []string{"diff too big"}, checkAgent(a.command, n) + default: + if a.command == cur { + tags = append(tags, "current") + } + if bigPrompt(n) { + tags = append(tags, "big diff, slow") + } + } + it.tag = strings.Join(tags, " · ") + items = append(items, it) + } + if c := m.cfg.GuideAgent; c != "" && !slices.ContainsFunc(guideAgents, func(a agentCLI) bool { + return a.name == c || a.command == c + }) { + tag := "" + if c == cur { + tag = "current" + } + items = append(items, pickItem{label: "guide_agent", detail: c, tag: tag, id: c}) + } + ov.setItems(items) + ov.cur = max(slices.IndexFunc(items, func(it pickItem) bool { return it.id == cur }), 0) + m.open(ov) + return m.sendLogos() +} + +// pickGuideAgent makes the agent of item it of the picker the agent of +// the guide, and writes the guide with it. +func (m *model) pickGuideAgent(it pickItem) tea.Cmd { + command := it.id + switch { + case it.off != "": + m.flash(it.off) + return nil + case m.guide.running: + m.flash("wait for " + agentName(m.guide.agent) + " to finish") + return nil + } + m.guidePick = command + return m.writeGuide() +} + // guideCommits returns the subjects of the commits of the branch, which // tell the agent the intent and the language of the changes. func (m *model) guideCommits() []string { diff --git a/tui/keys.go b/tui/keys.go index 7c3053d..c634202 100644 --- a/tui/keys.go +++ b/tui/keys.go @@ -28,6 +28,8 @@ type keyMap struct { Search, Find, GotoLine, Rendered, Split, Wrap key.Binding NavPosition, NavHide, NavGrow, NavShrink key.Binding OpenPR, Refresh, Keys, Quit, QuitDiscard key.Binding + // GuideAgent picks the agent that writes the guide, in the Guide tab. + GuideAgent key.Binding // Upgrade installs a newer release. It works only while the footer // tells about a newer release. Upgrade key.Binding @@ -106,6 +108,7 @@ func defaultKeys() keyMap { NavShrink: bind([]string{">"}, ">", "narrow list"), OpenPR: bind([]string{"o"}, "o", "open PR in browser"), Refresh: bind([]string{"r"}, "r", "refresh"), + GuideAgent: bind([]string{"a"}, "a", "pick guide agent"), Upgrade: bind([]string{"U"}, "U", "update rexdiff"), Keys: bind([]string{"?"}, "?", "all keys"), Quit: bind([]string{"q", "ctrl+c"}, "q", "quit"), @@ -210,6 +213,7 @@ func (k *keyMap) bindings(c keybindings) []binding { {"navigator-shrink", c.NavigatorShrink, &k.NavShrink}, {"open-pr", c.OpenPR, &k.OpenPR}, {"refresh", c.Refresh, &k.Refresh}, + {"guide-agent", c.GuideAgent, &k.GuideAgent}, {"keys", c.Keys, &k.Keys}, {"quit", c.Quit, &k.Quit}, {"quit-discard", c.QuitDiscard, &k.QuitDiscard}, @@ -273,7 +277,7 @@ func (h helpKeys) ShortHelp() []key.Binding { return []key.Binding{k.Down, k.Refresh, k.TabOverview, k.Keys, k.Quit} case h.tab == tabGuide: return []key.Binding{ - k.Comment, k.Send, k.NextFile, hint(k.Refresh, "r", "rewrite guide"), k.Split, k.Keys, k.Quit, + k.Comment, k.Send, k.NextFile, hint(k.Refresh, "r", "rewrite guide"), k.GuideAgent, k.Split, k.Keys, k.Quit, } } return []key.Binding{k.Comment, k.Send, k.NextHunk, k.NextFile, k.Split, k.Keys, k.Quit} @@ -295,7 +299,7 @@ func (h helpKeys) FullHelp() [][]key.Binding { view := []key.Binding{ k.Search, k.Find, k.Rendered, k.Split, k.Wrap, k.NavPosition, k.NavHide, k.NavGrow, } - other := []key.Binding{k.OpenPR, k.Refresh, k.Keys, k.Quit, k.QuitDiscard} + other := []key.Binding{k.OpenPR, k.Refresh, k.GuideAgent, k.Keys, k.Quit, k.QuitDiscard} return [][]key.Binding{move, scopes, comments, view, other} } diff --git a/tui/logo.go b/tui/logo.go new file mode 100644 index 0000000..c06ebd2 --- /dev/null +++ b/tui/logo.go @@ -0,0 +1,201 @@ +package tui + +// The logos of the agent CLIs show in a terminal that has the kitty +// graphics protocol. rexdiff sends each image once, then draws it with +// Unicode placeholders: plain cells that the renderer moves, clips, and +// redraws as text, and that the terminal paints with the image. The kitty +// renderer covers the cells with its pictures, so it paints the logos in +// its pictures itself. +// +// The logos are masks: black shapes on nothing. They take the colour of +// the text, so they follow the theme of the terminal. + +import ( + "bytes" + "embed" + "fmt" + "image" + "image/color" + "image/draw" + "image/png" + "os" + "strings" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + uv "github.com/charmbracelet/ultraviolet" + "github.com/charmbracelet/x/ansi/kitty" + xdraw "golang.org/x/image/draw" +) + +//go:embed logos/*.png +var logoFiles embed.FS + +// logoCols is the width of a logo, in cells. Two cells are about square. +const logoCols = 2 + +// logoImageID returns the kitty image ID of the logo of agent i of guideAgents. +// The ID is the 24-bit colour of the placeholder cells, so it is high +// enough to stay clear of the small IDs that other programs pick. +func logoImageID(i int) int { return 0x524400 + i + 1 } + +// kittyImages reports whether the terminal shows images with Unicode +// placeholders. tmux, zellij, and screen keep the variables of the outer +// terminal but drop the images, so they have no logos. +// +// ponytail: guesses from the environment; query the terminal (a=q) if a +// terminal that it misses asks for logos. +func kittyImages() bool { + for _, mux := range []string{"TMUX", "ZELLIJ", "STY"} { + if os.Getenv(mux) != "" { + return false + } + } + switch os.Getenv("TERM_PROGRAM") { + case "rex", "ghostty": + return true + } + return os.Getenv("KITTY_WINDOW_ID") != "" || os.Getenv("TERM") == "xterm-kitty" +} + +// sendLogos returns the command that sends the logos to the terminal in +// the colour of the text, or nil if the terminal has them, shows no +// images, or the kitty renderer paints them. +func (m *model) sendLogos() tea.Cmd { + if !m.logos || m.logosSent || m.kitty != nil { + return nil + } + m.logosSent = true + ink := m.fg + if ink == nil { // the terminal did not tell yet: a grey that reads on both themes + ink = color.Gray{0x99} + } + var b bytes.Buffer + for i, a := range guideAgents { + mask := logoImage(a.name) + if mask == nil { + continue + } + img := image.NewRGBA(mask.Bounds()) + draw.DrawMask(img, img.Rect, image.NewUniform(ink), image.Point{}, mask, mask.Bounds().Min, draw.Src) + _ = kitty.EncodeGraphics(&b, img, &kitty.Options{ // a bytes.Buffer does not fail + Action: kitty.TransmitAndPut, + Format: kitty.PNG, + ID: logoImageID(i), + VirtualPlacement: true, + Columns: logoCols, + Rows: 1, + Quiet: 2, // no reply on the input + Chunk: true, + }) + } + return tea.Raw(b.String()) +} + +// recolorLogos sends the logos again after the colour of the text changed. +// An image with the same ID takes the place of the old one. +func (m *model) recolorLogos() tea.Cmd { + if !m.logosSent { + return nil + } + m.logosSent = false + return m.sendLogos() +} + +// agentLogo returns the cells of the logo of the agent CLI name, or "" if the +// terminal shows no images or the agent has no logo. +func (m *model) agentLogo(name string) string { + if id := m.agentLogoID(name); id != 0 { + return logoCells(id, lipgloss.NewStyle()) + } + return "" +} + +// agentLogoID returns the image ID of the logo of the agent CLI name, or 0 if +// the terminal shows no images or the agent has no logo. +func (m *model) agentLogoID(name string) int { + if !m.logos { + return 0 + } + for i, a := range guideAgents { + if a.name == name { + return logoImageID(i) + } + } + return 0 +} + +// logoCells returns the placeholder cells of the image id in style st: +// one row of logoCols cells, each with the diacritics of its row and +// column. The foreground of the cells is the ID. +func logoCells(id int, st lipgloss.Style) string { + var b strings.Builder + for col := range logoCols { + b.WriteRune(kitty.Placeholder) + b.WriteRune(kitty.Diacritic(0)) + b.WriteRune(kitty.Diacritic(col)) + } + return st.Foreground(lipgloss.Color(fmt.Sprintf("#%06x", id))).Render(b.String()) +} + +// logoImage returns the logo of the agent CLI name, or nil. +func logoImage(name string) image.Image { + data, err := logoFiles.ReadFile("logos/" + name + ".png") + if err != nil { + return nil + } + img, err := png.Decode(bytes.NewReader(data)) + if err != nil { + return nil + } + return img +} + +// logoCell paints cell c in rect of img, in the colour ink, if it is a +// placeholder of a logo, and reports whether it was one. The colour of the +// cell is the image ID, and its third rune is the diacritic of its column. +func (r *raster) logoCell(img *image.RGBA, rect image.Rectangle, c uv.Cell, ink color.RGBA) bool { + rs := []rune(c.Content) + if len(rs) == 0 || rs[0] != kitty.Placeholder { + return false + } + col := 0 + for i := range logoCols { + if len(rs) >= 3 && kitty.Diacritic(i) == rs[2] { + col = i + } + } + if c.Style.Fg == nil { + return true + } + cr, cg, cb, _ := c.Style.Fg.RGBA() + id := int(cr>>8)<<16 | int(cg>>8)<<8 | int(cb>>8) + if mask := r.logoMask(id); mask != nil { + draw.DrawMask(img, rect, image.NewUniform(ink), image.Point{}, mask, image.Pt(col*r.cw, 0), draw.Over) + } + return true +} + +// logoMask returns the mask of the logo of image id, logoCols cells by one, or +// nil. The logo is a square in the middle. +func (r *raster) logoMask(id int) *image.RGBA { + r.mu.Lock() + defer r.mu.Unlock() + if m, ok := r.logos[id]; ok { + return m + } + var m *image.RGBA + if i := id - logoImageID(0); 0 <= i && i < len(guideAgents) { + if src := logoImage(guideAgents[i].name); src != nil { + w, side := logoCols*r.cw, min(logoCols*r.cw, r.ch) + m = image.NewRGBA(image.Rect(0, 0, w, r.ch)) + at := image.Rect((w-side)/2, (r.ch-side)/2, (w+side)/2, (r.ch+side)/2) + xdraw.CatmullRom.Scale(m, at, src, src.Bounds(), xdraw.Src, nil) + } + } + if r.logos == nil { + r.logos = map[int]*image.RGBA{} + } + r.logos[id] = m + return m +} diff --git a/tui/logo_test.go b/tui/logo_test.go new file mode 100644 index 0000000..20dd225 --- /dev/null +++ b/tui/logo_test.go @@ -0,0 +1,307 @@ +package tui + +import ( + "bytes" + "image" + "image/color" + "image/png" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + uv "github.com/charmbracelet/ultraviolet" + "github.com/charmbracelet/x/ansi" + "github.com/charmbracelet/x/ansi/kitty" +) + +// TestLogos checks that each agent CLI has a logo, and that the cells of +// a logo take logoCols columns, so that the rows around it line up. +func TestLogos(t *testing.T) { + for _, a := range guideAgents { + b, err := logoFiles.ReadFile("logos/" + a.name + ".png") + if err != nil { + t.Errorf("%s: %v", a.name, err) + continue + } + if _, err := png.Decode(bytes.NewReader(b)); err != nil { + t.Errorf("%s: %v", a.name, err) + } + } + if w := lipgloss.Width(logoCells(logoImageID(0), lipgloss.NewStyle()) + " claude"); w != logoCols+7 { + t.Errorf("width of a logo and its name = %d, want %d", w, logoCols+7) + } +} + +// TestGuideAgentPicker checks that a in the Guide tab lists the agent +// CLIs, that an agent that is not installed is not picked, and that an +// installed one writes the guide. +func TestGuideAgentPicker(t *testing.T) { + t.Setenv("HOME", t.TempDir()) // the cache of the guides + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + m, _ := newTestModel(t) + + // The PATH has git and a fake agy, and no other agent. + bin := t.TempDir() + git, err := exec.LookPath("git") + if err != nil { + t.Fatal(err) + } + if err := os.Symlink(git, filepath.Join(bin, "git")); err != nil { + t.Fatal(err) + } + write(t, bin, "agy", `#!/bin/sh +echo '{"sections":[{"title":"Written by agy","summary":"S.","files":["a.go"]}]}' +`) + if err := os.Chmod(filepath.Join(bin, "agy"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", bin+":/bin") + + m.cfg.GuideAgent = "codex" // a name stands for its command + if got := m.guideAgent(0); got != "codex exec -" { + t.Fatalf("guideAgent = %q", got) + } + m.tab = tabGuide + m = press(t, m, "a") + if m.overlay == nil || m.overlay.kind != overlayGuideAgent || + !shows(m, "claude", "opencode", "cursor-agent", "agy", "not installed") { + t.Fatalf("a: no picker of agents:\n%s", view(m)) + } + + m = press(t, m, "enter") // the cursor starts on codex, the current agent + if m.guide.running || m.guidePick != "" { + t.Fatal("the picker ran codex, which is not installed") + } + + m = press(t, m, "r") // write the guide with codex + if m.guide.running || m.guide.err != `agent "codex" not found in PATH` { + t.Fatalf("r with codex, which is not installed: %+v", m.guide) + } + + m = press(t, m, "a", "j", "j", "j") // codex, opencode, cursor-agent, agy + next, cmd := m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + m = *next.(*model) + if cmd == nil || !m.guide.running || agentName(m.guide.agent) != "agy" { + t.Fatalf("picking agy did not run it: %+v", m.guide) + } + m = press(t, m, "a", "enter") // another pick while agy writes + if !strings.Contains(m.status, "wait for agy to finish") { + t.Errorf("a pick during a run: status %q", m.status) + } + for _, c := range cmd().(tea.BatchMsg) { + if c == nil { + continue + } + if msg, ok := c().(guideMsg); ok { + m = step(t, m, msg) + } + } + if !shows(m, "Written by agy") { + t.Errorf("Guide tab after agy:\n%s", view(m)) + } +} + +// TestRasterLogo checks that the kitty renderer paints a logo in its +// picture of the line, where the terminal would paint it under the +// picture, in the colour of the text. +func TestRasterLogo(t *testing.T) { + r := newRaster(16, 34) + scr := uv.NewScreenBuffer(4, 1) + uv.NewStyledString(logoCells(logoImageID(0), lipgloss.NewStyle())+" ").Draw(scr, scr.Bounds()) + pal := &palette{fg: color.RGBA{0xdd, 0xdd, 0xdd, 0xff}, bg: color.RGBA{0, 0, 0, 0xff}} + img := image.NewRGBA(image.Rect(0, 0, 4*16, 34)) + r.draw(img, scr.Line(0), pal, -1) + if c := img.RGBAAt(16, 17); c != pal.fg { // the middle of the logo of claude + t.Errorf("the middle of the logo is %v, not the colour of the text", c) + } + if c := img.RGBAAt(3*16+8, 17); c != pal.bg { + t.Errorf("the cell after the logo is %v, not the background", c) + } +} + +// TestRecolorLogos checks that the logos go to the terminal once, and +// again when the colour of the text changes with the theme. +func TestRecolorLogos(t *testing.T) { + m, _ := newTestModel(t) + m.logos = true + if m.sendLogos() == nil || m.sendLogos() != nil { + t.Fatal("sendLogos does not send the logos once") + } + if _, cmd := m.Update(tea.ForegroundColorMsg{Color: color.RGBA{0x22, 0x22, 0x22, 0xff}}); cmd == nil { + t.Error("a new colour of the text does not send the logos again") + } +} + +// TestGuideAgentPickerSelection checks that the name of the selected agent +// has the background of the selection after its logo, and that the list +// does not show the commands of the agents. +func TestGuideAgentPickerSelection(t *testing.T) { + m, _ := newTestModel(t) + m.logos, m.bg, m.dark = true, color.RGBA{0x10, 0x10, 0x10, 0xff}, true + m.tab = tabGuide + m.openGuideAgentPicker() + m.overlay.cur = 0 // claude + rows, _ := m.overlayRows(40) + scr := uv.NewScreenBuffer(40, 1) + uv.NewStyledString(rows[0]).Draw(scr, scr.Bounds()) + line := scr.Line(0) + if got := ansi.Strip(rows[0]); strings.Contains(got, "-p") { + t.Errorf("the row shows the command: %q", got) + } + x := 2 + logoCols + 1 // "▶ ", the logo, a space + if c := line[x]; c.Content != "c" || c.Style.Bg == nil { + t.Errorf("the cell of the name is %q with background %v", c.Content, c.Style.Bg) + } +} + +// TestGuideAgentPickerCommand checks that the picker lists the command of +// the setting, with its text, when it is not one of the agent CLIs. +func TestGuideAgentPickerCommand(t *testing.T) { + m, _ := newTestModel(t) + m.cfg.GuideAgent = "my-agent --fast" + m.tab = tabGuide + m = press(t, m, "a") + if !shows(m, "guide_agent", "my-agent --fast", "current") { + t.Errorf("the picker has no row for the command of the setting:\n%s", view(m)) + } +} + +// TestCheckAgent checks the errors of an agent that cannot run: none at +// all, and an agent CLI that the PATH does not have. A command of the +// setting is left to the shell. +func TestCheckAgent(t *testing.T) { + m, _ := newTestModel(t) + t.Setenv("PATH", t.TempDir()) + cases := []struct{ command, want string }{ + {m.guideAgent(0), "no agent found"}, + {"codex exec -", `agent "codex" not found in PATH`}, + {"FOO=1 codex exec -", ""}, + } + for _, c := range cases { + if got := checkAgent(c.command, 0); got != c.want { + t.Errorf("checkAgent(%q) = %q, want %q", c.command, got, c.want) + } + } +} + +// TestKittyImages checks the guess of a terminal that shows images. +func TestKittyImages(t *testing.T) { + cases := []struct { + tmux, zellij, sty, program, kittyWindow, term string + want bool + }{ + {program: "rex", want: true}, + {program: "ghostty", want: true}, + {kittyWindow: "1", want: true}, + {term: "xterm-kitty", want: true}, + {tmux: "/tmp/tmux", program: "ghostty", kittyWindow: "1", term: "xterm-kitty"}, + {program: "Apple_Terminal", term: "xterm-256color"}, + {zellij: "0", program: "ghostty"}, + {sty: "1.tty.host", program: "rex"}, + } + for _, c := range cases { + t.Setenv("TMUX", c.tmux) + t.Setenv("ZELLIJ", c.zellij) + t.Setenv("STY", c.sty) + t.Setenv("TERM_PROGRAM", c.program) + t.Setenv("KITTY_WINDOW_ID", c.kittyWindow) + t.Setenv("TERM", c.term) + if got := kittyImages(); got != c.want { + t.Errorf("kittyImages() with %+v = %v", c, got) + } + } +} + +// TestGuideProgressLogo checks the line of a run in the guide column: the +// logo of the agent before its first line, and the next lines in line with +// the text. +func TestGuideProgressLogo(t *testing.T) { + m, _ := newTestModel(t) + m.logos = true + m.guide = guideState{ + sections: []guideSection{{Title: "T", Summary: "S", Files: []string{"a.go"}}}, + running: true, + started: time.Now(), + agent: "cursor-agent -p", + } + lines, _, _ := m.guideLines(40) + i := slices.IndexFunc(lines, func(l string) bool { return strings.ContainsRune(l, kitty.Placeholder) }) + if i < 0 || i+1 >= len(lines) { + t.Fatalf("no logo in the guide column:\n%s", strings.Join(lines, "\n")) + } + first, next := ansi.Strip(lines[i]), ansi.Strip(lines[i+1]) + if !strings.Contains(first, "cursor-agent is") || !strings.HasPrefix(next, strings.Repeat(" ", 1+logoCols+1)) || strings.TrimSpace(next) == "" { + t.Errorf("progress lines:\n%q\n%q", first, next) + } +} + +// TestGuideBigDiff checks a diff too big for an argument: the agents that +// take the prompt as one are off, the others carry a warning, and the +// first agent that is installed is one that reads its standard input. +func TestGuideBigDiff(t *testing.T) { + t.Setenv("HOME", t.TempDir()) // the cache of the guides + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + m, _ := newTestModel(t) + bin := t.TempDir() + git, err := exec.LookPath("git") + if err != nil { + t.Fatal(err) + } + if err := os.Symlink(git, filepath.Join(bin, "git")); err != nil { + t.Fatal(err) + } + for _, name := range []string{"agy", "claude"} { + write(t, bin, name, "#!/bin/sh\ncat >/dev/null\n") + if err := os.Chmod(filepath.Join(bin, name), 0o755); err != nil { + t.Fatal(err) + } + } + t.Setenv("PATH", bin+":/bin") + defer func(n int) { maxArg = n }(maxArg) + maxArg = 10 + + if got := m.guideAgent(100); got != "claude -p" { + t.Errorf("first agent for a big diff = %q, want claude -p", got) + } + m.cfg.GuideAgent = "agy" + m.tab = tabGuide + m = press(t, m, "r") + if m.guide.running || !strings.HasPrefix(m.guide.err, "the diff is too big for agy") { + t.Fatalf("r with agy and a big diff: %+v", m.guide) + } + m = press(t, m, "a") + if !shows(m, "diff too big", "big diff, slow") { + t.Fatalf("picker for a big diff:\n%s", view(m)) + } + m = press(t, m, "j", "j", "j", "j", "j", "enter") // agy + if m.guide.running || !strings.Contains(m.status, "too big for agy") { + t.Errorf("picking agy for a big diff: running %v, status %q", m.guide.running, m.status) + } + m.cfg.GuideAgent = "claude" // reads its standard input: it runs, with a warning + m = press(t, m, "r") + if !m.guide.running || !strings.Contains(m.status, "the diff is big") { + t.Errorf("r with claude and a big diff: running %v, status %q", m.guide.running, m.status) + } +} + +// TestLogosAfterEditor checks that the logos go again after the editor, +// which takes the terminal off the alternate screen and its images. +func TestLogosAfterEditor(t *testing.T) { + m, _ := newTestModel(t) + m.logos, m.logosSent = true, true + m = step(t, m, editorDoneMsg{}) + if m.logosSent { + t.Fatal("the logos count as sent after the editor") + } + m.guide.running, m.guide.started = true, time.Now() + m = step(t, m, frameMsg(m.guide.started)) + if !m.logosSent { + t.Error("a frame of a run does not send the logos") + } +} diff --git a/tui/logos/agy.png b/tui/logos/agy.png new file mode 100644 index 0000000..4b78bb0 Binary files /dev/null and b/tui/logos/agy.png differ diff --git a/tui/logos/claude.png b/tui/logos/claude.png new file mode 100644 index 0000000..258b7b0 Binary files /dev/null and b/tui/logos/claude.png differ diff --git a/tui/logos/codex.png b/tui/logos/codex.png new file mode 100644 index 0000000..9399cc6 Binary files /dev/null and b/tui/logos/codex.png differ diff --git a/tui/logos/cursor-agent.png b/tui/logos/cursor-agent.png new file mode 100644 index 0000000..ebda949 Binary files /dev/null and b/tui/logos/cursor-agent.png differ diff --git a/tui/logos/opencode.png b/tui/logos/opencode.png new file mode 100644 index 0000000..4cf0490 Binary files /dev/null and b/tui/logos/opencode.png differ diff --git a/tui/logos/pi.png b/tui/logos/pi.png new file mode 100644 index 0000000..0f5967d Binary files /dev/null and b/tui/logos/pi.png differ diff --git a/tui/model.go b/tui/model.go index cd3b361..f93cca7 100644 --- a/tui/model.go +++ b/tui/model.go @@ -265,7 +265,11 @@ type model struct { overPane pane guide guideState guidePane pane - guideSel int // the file of the guide, in the order of guideFiles + guideSel int // the file of the guide, in the order of guideFiles + guidePick string // the agent that the user picked in the Guide tab, or "" + + logos bool // the terminal shows the logos of the agents + logosSent bool // the terminal has the logos split bool // show the diff side by side wrap bool @@ -343,6 +347,7 @@ func newModel(ctx context.Context, o Options, cfg config) model { m.findBar.Prompt = "/ " m.findBar.SetVirtualCursor(false) m.cfg = cfg + m.logos = cfg.Renderer == rendererKitty || kittyImages() m.keys = defaultKeys() m.keys.applyConfig(cfg.Keybindings) m.listLeft = cfg.FileList == positionLeft @@ -620,6 +625,7 @@ func (m *model) handle(msg tea.Msg) tea.Cmd { if !sameColor(m.fg, msg.Color) { m.fg = msg.Color m.rerender() + cmd = m.recolorLogos() } case uv.UnknownOscEvent: m.onPalette(string(msg)) @@ -639,7 +645,7 @@ func (m *model) handle(msg tea.Msg) tea.Cmd { } case frameMsg: if m.guide.running && m.guide.started.Equal(time.Time(msg)) { // one chain per run - cmd = frame(m.guide.started) + cmd = tea.Batch(frame(m.guide.started), m.sendLogos()) } case grepMsg: m.onGrep(msg) @@ -651,6 +657,7 @@ func (m *model) handle(msg tea.Msg) tea.Cmd { if msg.err != nil { m.flash("editor: " + msg.err.Error()) } + m.logosSent = false // the terminal drops the images when the editor leaves the alternate screen m.rerender() case tea.MouseClickMsg: return m.onClick(msg.Mouse()) diff --git a/tui/nav.go b/tui/nav.go index 8cb1ba9..602825a 100644 --- a/tui/nav.go +++ b/tui/nav.go @@ -255,6 +255,8 @@ func (m *model) viewKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { m.openPR() case key.Matches(msg, k.Refresh): return m.refresh(), true + case m.tab == tabGuide && key.Matches(msg, k.GuideAgent): + return m.openGuideAgentPicker(), true case m.release != nil && key.Matches(msg, k.Upgrade): return m.install(), true default: diff --git a/tui/overlay.go b/tui/overlay.go index 7a01389..5bb925c 100644 --- a/tui/overlay.go +++ b/tui/overlay.go @@ -21,6 +21,7 @@ type overlayKind int const ( overlayAgents overlayKind = iota + overlayGuideAgent overlayBase overlayCommits overlayComments @@ -40,8 +41,10 @@ const ( // pickItem is one row of the list of an overlay. type pickItem struct { label string + logo int // the guide agent picker: the image ID of a logo before the label, or 0 detail string // the dim text after the label tag string // a short mark at the end, for example "current" + off string // the guide agent picker: why the row cannot be picked, or "" // id is what the row picks: a path, a ref, a commit, or a block. id string line int // the search: the line of a code match @@ -78,7 +81,7 @@ func newOverlay(kind overlayKind, title string) *overlay { // agents and comments, and the prompt before a quit, have none. func (o *overlay) hasInput() bool { switch o.kind { - case overlayAgents, overlayComments, overlayQuit: + case overlayAgents, overlayGuideAgent, overlayComments, overlayQuit: return false } return true @@ -372,7 +375,7 @@ func (m *model) inputChanged() tea.Cmd { hits, _ := repo.Grep(ctx, q, maxCodeHits) return grepMsg{q, hits} } - case overlayBase, overlayCommits, overlayComments, overlayAgents: + case overlayBase, overlayCommits, overlayComments, overlayAgents, overlayGuideAgent: ov.filter() } return nil @@ -420,6 +423,11 @@ func (m *model) chooseOverlay() tea.Cmd { if a, ok := ov.agent(it); ok { return m.deliver(a) } + case overlayGuideAgent: + m.closeOverlay() + if it != nil { + return m.pickGuideAgent(*it) + } } m.ensureVisible() return nil @@ -501,15 +509,35 @@ func (m *model) overlayRows(inner int) (rows []string, start int) { start = ov.top for i := start; i < len(ov.shown) && i < start+maxRows; i++ { it := ov.items[ov.shown[i]] - tag := "" + // Each part has the background of the selection: the reset at the + // end of a part would end a background from around the row. + style := func(s lipgloss.Style) lipgloss.Style { + if i == ov.cur { + return s.Inherit(m.selStyle()) + } + return s + } + plain := style(lipgloss.NewStyle()) + var b strings.Builder + if m.logos && ov.kind == overlayGuideAgent { + if it.logo != 0 { + b.WriteString(logoCells(it.logo, plain)) + } else { + b.WriteString(plain.Render(strings.Repeat(" ", logoCols))) // in line with the logos + } + b.WriteString(plain.Render(" ")) + } + b.WriteString(plain.Render(diff.Quote(it.label))) + if it.detail != "" { + b.WriteString(plain.Render(" ") + style(dimStyle).Render(diff.Quote(it.detail))) + } if it.tag != "" { - tag = " " + cursorStyle.Render(it.tag) + b.WriteString(plain.Render(" ") + style(cursorStyle).Render(it.tag)) } if ov.kind == overlayCommits && ov.mark == ov.shown[i] { - tag += " " + cursorStyle.Render("range start") + b.WriteString(plain.Render(" ") + style(cursorStyle).Render("range start")) } - text := diff.Quote(it.label) + " " + dimStyle.Render(diff.Quote(it.detail)) + tag - row := truncate(text, inner-2) + row := truncate(b.String(), inner-2) if i == ov.cur { row = m.selStyle().Width(inner).Render("▶ " + row) } else { diff --git a/tui/raster.go b/tui/raster.go index db9017d..8d24bb9 100644 --- a/tui/raster.go +++ b/tui/raster.go @@ -121,9 +121,10 @@ type raster struct { faces [4][]font.Face buf sfnt.Buffer - mu sync.Mutex // guards the faces and glyphs, which rows share + mu sync.Mutex // guards the faces, the glyphs, and the logos, which rows share glyphs map[glyphKey]*image.Alpha - lines sync.Pool // *image.RGBA of a line, for the next line + logos map[int]*image.RGBA // the mask of the logo of each image ID, logoCols cells wide + lines sync.Pool // *image.RGBA of a line, for the next line } // newRaster makes a raster for cells of cw by ch pixels. The font size @@ -214,7 +215,7 @@ func (r *raster) draw(img *image.RGBA, cells uv.Line, p *palette, cursor int) { fg, bg := p.colors(c.Style) rect := image.Rect(x*r.cw, 0, min(x+w, len(cells))*r.cw, r.ch) draw.Draw(img, rect, image.NewUniform(bg), image.Point{}, draw.Src) - if c.Style.Attrs&uv.AttrConceal == 0 { + if c.Style.Attrs&uv.AttrConceal == 0 && !r.logoCell(img, rect, c, p.fg) { r.cell(img, rect, c, fg) } x += w