From ecce3be96f87b06acd061e08ea3773388fba091f Mon Sep 17 00:00:00 2001 From: Kenichiro Goto Date: Thu, 26 Nov 2026 18:14:53 +0900 Subject: [PATCH 1/2] tui: pick the agent of the guide, with its logo The Guide tab can now run opencode, cursor-agent, and agy, after claude, pi, and codex. The three take the prompt only as an argument, so their commands pass the standard input as one with "$(cat)". cursor-agent runs in ask mode, which does not edit, and with --trust, so it does not stop at the question of the workspace. a in the Guide tab lists the agents, and a pick writes the guide again with that agent. guide_agent takes the name of an agent as well as a command. An agent that the PATH does not have shows as not installed, and the guide says "agent "x" not found in PATH" for it, or "no agent found" when there is none. A command of the setting is left to the shell, since it can start with a variable. In a terminal with the kitty graphics protocol (Rex, Ghostty, kitty), the list and the line of a run show the logo of each agent. The logos are sent once and drawn with Unicode placeholders, so the renderer moves and clips them as text. They are masks in the colour of the text, and go again when the theme changes it. renderer = "kitty" covers the placeholders with its pictures, so it paints the logos in them itself. The rows of the overlays now give each part the background of the selection: the reset at the end of a styled part ended the background of the row, so a name after a logo, or a tag, showed off the highlight. On Linux one argument holds at most 128 KiB, under the 200 KB of diff that the prompt can have, so a big change can fail with the three new agents. --- README.md | 14 ++- cmd/rexdiff/install.go | 2 +- tui/config.go | 10 +- tui/guide.go | 135 ++++++++++++++++++--- tui/keys.go | 8 +- tui/logo.go | 199 +++++++++++++++++++++++++++++++ tui/logo_test.go | 238 +++++++++++++++++++++++++++++++++++++ tui/logos/agy.png | Bin 0 -> 1149 bytes tui/logos/claude.png | Bin 0 -> 2167 bytes tui/logos/codex.png | Bin 0 -> 2481 bytes tui/logos/cursor-agent.png | Bin 0 -> 1145 bytes tui/logos/opencode.png | Bin 0 -> 412 bytes tui/logos/pi.png | Bin 0 -> 583 bytes tui/model.go | 8 +- tui/nav.go | 2 + tui/overlay.go | 41 +++++-- tui/raster.go | 7 +- 17 files changed, 625 insertions(+), 39 deletions(-) create mode 100644 tui/logo.go create mode 100644 tui/logo_test.go create mode 100644 tui/logos/agy.png create mode 100644 tui/logos/claude.png create mode 100644 tui/logos/codex.png create mode 100644 tui/logos/cursor-agent.png create mode 100644 tui/logos/opencode.png create mode 100644 tui/logos/pi.png diff --git a/README.md b/README.md index dea8543..e8e364f 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,11 @@ 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. 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 +113,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..de41901 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 @@ -41,13 +41,24 @@ 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 }{ +// 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. +// +// ponytail: Linux caps one argument at 128 KiB (MAX_ARG_STRLEN), under +// guideMaxDiff; give these agents a smaller diff if a big change fails. +var guideAgents = []agentCLI{ {"claude", "claude -p"}, {"pi", "pi -p"}, {"codex", "codex exec -"}, + {"opencode", `opencode run "$(cat)"`}, + {"cursor-agent", `cursor-agent -p --mode ask --trust "$(cat)"`}, + {"agy", `agy -p "$(cat)"`}, } +// agentCLI is an agent CLI that can write the guide, and its command. +type agentCLI struct{ name, command string } + // guideSection is one part of the guide: the files of one change. type guideSection struct { Title string `json:"title"` @@ -161,18 +172,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 +212,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") @@ -277,8 +300,8 @@ func (m *model) writeGuide() tea.Cmd { return nil } agent := m.guideAgent() - if agent == "" { - m.guide.err = "no agent to write the guide: install claude or pi, or set guide_agent" + if err := checkAgent(agent); err != "" { + m.guide.err = err m.renderGuide() return nil } @@ -287,7 +310,7 @@ func (m *model) writeGuide() tea.Cmd { ctx, dir, trees := m.ctx, m.repo.Root(), m.shownTrees prompt := guidePrompt(m.guideCommits(), m.files) - return tea.Batch(frame(m.guide.started), func() tea.Msg { + return tea.Batch(m.sendLogos(), frame(m.guide.started), func() tea.Msg { out, err := runAgent(ctx, dir, agent, prompt) if err != nil { return guideMsg{trees: trees, err: err} @@ -350,20 +373,100 @@ 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 "". +// guideAgent returns the command that writes the guide: the agent that +// the user picked, or the setting, or the first agent CLI that is +// installed, or "". The pick and the setting are a name of guideAgents or +// a command. func (m *model) guideAgent() string { - if m.cfg.GuideAgent != "" { - return m.cfg.GuideAgent + 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) { return a.command } } return "" } +// checkAgent returns why the agent command cannot run, or "". It checks +// only the PATH for 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) string { + if command == "" { + return "no agent found" + } + for _, a := range guideAgents { + if a.command == command && !installed(a.name) { + return fmt.Sprintf("agent %q not found in PATH", a.name) + } + } + 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. +func (m *model) openGuideAgentPicker() tea.Cmd { + ov := newOverlay(overlayGuideAgent, "which agent writes the guide?") + cur := m.guideAgent() + var items []pickItem + for _, a := range guideAgents { + tag := "" + switch { + case !installed(a.name): + tag = notInstalled + case a.command == cur: + tag = "current" + } + items = append(items, pickItem{label: a.name, tag: tag, id: a.command, logo: m.agentLogoID(a.name)}) + } + 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() +} + +// notInstalled tags an agent CLI of the picker that the PATH does not have. +const notInstalled = "not installed" + +// 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.tag == notInstalled: + m.flash(it.label + " is not installed") + 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..97362b9 --- /dev/null +++ b/tui/logo.go @@ -0,0 +1,199 @@ +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 keeps the variables of the outer terminal but drops +// the images, so it has no logos. +// +// ponytail: guesses from the environment; query the terminal (a=q) if a +// terminal that it misses asks for logos. +func kittyImages() bool { + if os.Getenv("TMUX") != "" { + 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..15e5670 --- /dev/null +++ b/tui/logo_test.go @@ -0,0 +1,238 @@ +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(); 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(), "no agent found"}, + {"codex exec -", `agent "codex" not found in PATH`}, + {"FOO=1 codex exec -", ""}, + } + for _, c := range cases { + if got := checkAgent(c.command); 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, 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"}, + } + for _, c := range cases { + t.Setenv("TMUX", c.tmux) + 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) + } +} diff --git a/tui/logos/agy.png b/tui/logos/agy.png new file mode 100644 index 0000000000000000000000000000000000000000..4b78bb051a9725c09a927ce7066e2fc94d6e59d4 GIT binary patch literal 1149 zcmeAS@N?(olHy`uVBq!ia0vp^2_VeD1|%QND7Ro>U~%zuaSW-L^Jb2>M`@_Y@p|*K zCziBlraE41mJr`9I4g4{GuIzpPan9%a&+mL~HvMgPy?*Wgo4?=feQ)<&fk!i~LBiOf zM^fP!k3ce8havNk8H`D17!2_V`&{LbV4TOkkFAdVAM>_`&;-66k`@uVoBHN(?|Ccr zuG{s2*477BhJ1enZ~S>y;i9{T@6PmvAI};t)?0Au&ZhIvmVaEZYl2ph)Q4a{wm;l4 z>-1J+?U@(+`Emr~uB)!0t$UWud;4+2t_@ljSarlx4)7mn*mdB>&czFW`ey7pFe8&e zUM%N;)P>c0CSmI|cKporS;5^qRou%c!7($Cv((xE~0VUffuq^db8sn~LEQy*VDs76>kIpYYwv@f>rzhYbAe&DFXevR_>+5eWT;FZYz{3pn&@x1G0f2ott-dm&!Pf>oL^S~#u z?#{FKN=q4*G9I3|#%W1-#1ys|-7|O3Y?#e=yDKgs*5?26kKzT}Rtc^WERZW$qw&4W z>aNCw1x5(eT%>>2YoY7*KS%8j1B;dj21Aq9R%(0e=ID^aqdXSd?p%b!9HT6ryf*tT{3iToby^cN#s{G>8<7Q@T_ZbikTZ-o2<$LHMv}MD88w1%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4fIqe7f literal 0 HcmV?d00001 diff --git a/tui/logos/opencode.png b/tui/logos/opencode.png new file mode 100644 index 0000000000000000000000000000000000000000..4cf04908eadfa90ed17ed13ba447d5472d5af9a5 GIT binary patch literal 412 zcmeAS@N?(olHy`uVBq!ia0vp^2_VeD1|%QND7Ro>U`+OOaSW-L^XAUQP7y~Dhl|T4 zS~Gtn${gD)_$$$kJDbbc>uT+pdCb3~FBepX`kL>JZ=b?o$e6@*gr$R1Kv+S|!KYyc zs=%Au55L;;t*<{lJ(znox+GNf^7*W`ug{Z2O-^)!^n3oWy^C*%9bh@)!%&{foxuHQT`uDsM#E@< za+q6gY-7lCP6i@1g*2ul2+^>68|wzv!s!efa~Wk08KyIURd3U6aJG0R@C;}~j^oDf z;y-)a*ZzvjN~=42<~w)1=eojQ4pFA>{vX`0Qyq%Uw-1Vq8Sw{%Ps5G-z<~b$Khny~ U>1b_t6p+K<>FVdQ&MBb@00EhmQ2+n{ literal 0 HcmV?d00001 diff --git a/tui/logos/pi.png b/tui/logos/pi.png new file mode 100644 index 0000000000000000000000000000000000000000..0f5967db2fdc83f35ff34c06adc8fb284ef7b521 GIT binary patch literal 583 zcmeAS@N?(olHy`uVBq!ia0vp^2_VeD1|%QND7Ro>VB+(1aSW-L^XAU^Ea5;I_mBBa z4}wZ`f5_}>$bVG);#&EKN|y_B*RdWfJrMAV|I(C3%@)OOzdCcvy=Q+qc+4tG%X{YY zZo-ncMoy9pX$&(M6WAJXGW4a^JocYt?)gq?&Fc`c$6wo3>`ydq;V^jfC!F`1bH>LX z-cde|wz5C{`<~-A$!))M#l$DqE2<5PZ~9Iu_q->U7!w<*dQ-0AXV{%@%MWd9KmFV7 z_k#pKM+2(^cQT*fT*w?!D!<`7!(C&BGYlK;hZhQIgo`vyd<7!C(by} z07O?M7_L<_oM&A1(zZc85y*4 literal 0 HcmV?d00001 diff --git a/tui/model.go b/tui/model.go index cd3b361..e835b35 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)) 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..698fb8a 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,6 +41,7 @@ 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" // id is what the row picks: a path, a ref, a commit, or a block. @@ -78,7 +80,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 +374,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 +422,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 +508,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 From a1fbf5c6740d960934b42c563c3155c2e8cf89c3 Mon Sep 17 00:00:00 2001 From: Kenichiro Goto Date: Thu, 26 Nov 2026 18:41:33 +0900 Subject: [PATCH 2/2] tui: turn off the argument agents for a big diff opencode, cursor-agent, and agy take the prompt as one argument. macOS holds at most 1 MiB of arguments and environment, and Linux 128 KiB in one argument, while the prompt can pass 1 MiB with one big file. The guide now measures the prompt first. A prompt that does not fit turns these agents off: the picker marks them "diff too big", and a run with one of them says how big the diff is and the most that fits. claude, pi, and codex read their standard input and still run, with a warning that a big diff takes long. With no agent set, the first agent that is installed and takes the prompt writes the guide. The terminal drops its images when the editor takes it off the alternate screen, so the logos go again after the editor. They go with the first frame of a run, not at its start: a run that starts with the program could send them before Bubble Tea is on the alternate screen. opencode runs as its plan agent, which does not edit, since the diff can hold instructions. zellij and screen keep the variables of the outer terminal but drop the images, as tmux does, so they get no logos. --- README.md | 4 +- tui/guide.go | 122 ++++++++++++++++++++++++++++++++--------------- tui/logo.go | 10 ++-- tui/logo_test.go | 79 ++++++++++++++++++++++++++++-- tui/model.go | 3 +- tui/overlay.go | 1 + 6 files changed, 169 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index e8e364f..38db45e 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,9 @@ are gone, rexdiff marks the comment as stale. 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. It keeps each + 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. diff --git a/tui/guide.go b/tui/guide.go index de41901..7b45962 100644 --- a/tui/guide.go +++ b/tui/guide.go @@ -19,6 +19,7 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "slices" "strings" "time" @@ -43,21 +44,45 @@ const ( // guideAgents are the agent CLIs that can write the guide, in the order // 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. -// -// ponytail: Linux caps one argument at 128 KiB (MAX_ARG_STRLEN), under -// guideMaxDiff; give these agents a smaller diff if a big change fails. +// 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"}, - {"pi", "pi -p"}, - {"codex", "codex exec -"}, - {"opencode", `opencode run "$(cat)"`}, - {"cursor-agent", `cursor-agent -p --mode ask --trust "$(cat)"`}, - {"agy", `agy -p "$(cat)"`}, + {"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 } -// agentCLI is an agent CLI that can write the guide, and its command. -type agentCLI struct{ name, command string } +// 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 { @@ -299,18 +324,23 @@ func (m *model) writeGuide() tea.Cmd { m.renderGuide() return nil } - agent := m.guideAgent() - if err := checkAgent(agent); err != "" { + 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) - return tea.Batch(m.sendLogos(), frame(m.guide.started), func() tea.Msg { + // 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 { return guideMsg{trees: trees, err: err} @@ -373,11 +403,11 @@ func (m *model) onGuide(msg guideMsg) { } } -// guideAgent returns the command that writes the guide: the agent that -// the user picked, or the setting, or the first agent CLI that is -// installed, or "". The pick and the setting are a name of guideAgents or -// a command. -func (m *model) guideAgent() string { +// 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 { @@ -387,24 +417,28 @@ func (m *model) guideAgent() string { return pick } for _, a := range guideAgents { - if installed(a.name) { + if installed(a.name) && !(a.arg && bigPrompt(n)) { return a.command } } return "" } -// checkAgent returns why the agent command cannot run, or "". It checks -// only the PATH for 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) string { +// 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 { - if a.command == command && !installed(a.name) { + 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 "" @@ -419,19 +453,32 @@ func installed(program string) bool { // 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?") - cur := m.guideAgent() + n := len(guidePrompt(m.guideCommits(), m.files)) + cur := m.guideAgent(n) var items []pickItem for _, a := range guideAgents { - tag := "" + it := pickItem{label: a.name, id: a.command, logo: m.agentLogoID(a.name)} + var tags []string switch { case !installed(a.name): - tag = notInstalled - case a.command == cur: - tag = "current" + 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") + } } - items = append(items, pickItem{label: a.name, tag: tag, id: a.command, logo: m.agentLogoID(a.name)}) + 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 @@ -448,16 +495,13 @@ func (m *model) openGuideAgentPicker() tea.Cmd { return m.sendLogos() } -// notInstalled tags an agent CLI of the picker that the PATH does not have. -const notInstalled = "not installed" - // 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.tag == notInstalled: - m.flash(it.label + " is not installed") + case it.off != "": + m.flash(it.off) return nil case m.guide.running: m.flash("wait for " + agentName(m.guide.agent) + " to finish") diff --git a/tui/logo.go b/tui/logo.go index 97362b9..c06ebd2 100644 --- a/tui/logo.go +++ b/tui/logo.go @@ -40,14 +40,16 @@ const logoCols = 2 func logoImageID(i int) int { return 0x524400 + i + 1 } // kittyImages reports whether the terminal shows images with Unicode -// placeholders. tmux keeps the variables of the outer terminal but drops -// the images, so it has no logos. +// 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 { - if os.Getenv("TMUX") != "" { - return false + for _, mux := range []string{"TMUX", "ZELLIJ", "STY"} { + if os.Getenv(mux) != "" { + return false + } } switch os.Getenv("TERM_PROGRAM") { case "rex", "ghostty": diff --git a/tui/logo_test.go b/tui/logo_test.go index 15e5670..20dd225 100644 --- a/tui/logo_test.go +++ b/tui/logo_test.go @@ -64,7 +64,7 @@ echo '{"sections":[{"title":"Written by agy","summary":"S.","files":["a.go"]}]}' t.Setenv("PATH", bin+":/bin") m.cfg.GuideAgent = "codex" // a name stands for its command - if got := m.guideAgent(); got != "codex exec -" { + if got := m.guideAgent(0); got != "codex exec -" { t.Fatalf("guideAgent = %q", got) } m.tab = tabGuide @@ -179,12 +179,12 @@ func TestCheckAgent(t *testing.T) { m, _ := newTestModel(t) t.Setenv("PATH", t.TempDir()) cases := []struct{ command, want string }{ - {m.guideAgent(), "no agent found"}, + {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); got != c.want { + if got := checkAgent(c.command, 0); got != c.want { t.Errorf("checkAgent(%q) = %q, want %q", c.command, got, c.want) } } @@ -193,8 +193,8 @@ func TestCheckAgent(t *testing.T) { // TestKittyImages checks the guess of a terminal that shows images. func TestKittyImages(t *testing.T) { cases := []struct { - tmux, program, kittyWindow, term string - want bool + tmux, zellij, sty, program, kittyWindow, term string + want bool }{ {program: "rex", want: true}, {program: "ghostty", want: true}, @@ -202,9 +202,13 @@ func TestKittyImages(t *testing.T) { {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) @@ -236,3 +240,68 @@ func TestGuideProgressLogo(t *testing.T) { 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/model.go b/tui/model.go index e835b35..f93cca7 100644 --- a/tui/model.go +++ b/tui/model.go @@ -645,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) @@ -657,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/overlay.go b/tui/overlay.go index 698fb8a..5bb925c 100644 --- a/tui/overlay.go +++ b/tui/overlay.go @@ -44,6 +44,7 @@ type pickItem struct { 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