diff --git a/internal/terminalpet/builtin.go b/internal/terminalpet/builtin.go index 5d4117067..d271e720d 100644 --- a/internal/terminalpet/builtin.go +++ b/internal/terminalpet/builtin.go @@ -18,11 +18,40 @@ import ( // list of companions, even when a community pet has the same name. const builtinSlugPrefix = "zero:" -// Dance and Lunge are extra states that only built-in companions have. They -// play when the companion is clicked. +// Extra states the built-in companions have. Dance and Lunge play when the +// companion is clicked. Thinking and Sleeping are agent states: pets without +// those animations show Running and Idle instead (see Animation.Has), and a +// community pet whose pet.json defines them gets them too. const ( - Dance State = "dance" - Lunge State = "lunge" + Dance State = "dance" + Lunge State = "lunge" + Thinking State = "thinking" + Sleeping State = "sleeping" +) + +const ( + // TextColumns and TextRows are the terminal cells a built-in companion + // fills when it is drawn as text, for terminals that cannot show images. + TextColumns = 18 + TextRows = 8 + + // textScale draws the 48x40 design at 18x15 pixels. Half-block cells + // stack two pixels each, and one empty pixel row on top leaves room for + // a hop: 18x16 pixels in 18x8 cells. + textScale = 0.375 + textHeadroom = 1 +) + +// TextColors is the colour depth text frames are drawn for. +type TextColors uint8 + +const ( + // TextTrueColor draws with the art's exact 24-bit colours. + TextTrueColor TextColors = iota + // Text256 draws with a fixed 256-colour palette, the nearest colour to + // each art colour by CIEDE2000, which keeps hues a generic conversion + // would lose. + Text256 ) const ( @@ -114,6 +143,8 @@ var ( Idle: {mood: petart.Idle, start: builtinBlinkSkip, length: 5750 * time.Millisecond, loop: true}, Running: {mood: petart.Working, length: 3100 * time.Millisecond, loop: true}, Waiting: {mood: petart.Waiting, start: builtinBlinkSkip, length: 2900 * time.Millisecond, loop: true}, + Thinking: {mood: petart.Thinking, length: 6400 * time.Millisecond, loop: true}, + Sleeping: {mood: petart.Sleeping, length: 5200 * time.Millisecond, loop: true}, Review: {mood: petart.Happy, length: 1900 * time.Millisecond}, Failed: {mood: petart.Sad, length: 1800 * time.Millisecond}, Waving: {mood: petart.Hello, length: 2400 * time.Millisecond}, @@ -197,6 +228,7 @@ type builtinFrame struct { mu sync.Mutex pixels *image.NRGBA + text [2][]string } // draw paints the frame and keeps nothing. Callers cache what they make from @@ -220,6 +252,30 @@ func (f *builtinFrame) rendered() *image.NRGBA { return f.pixels } +// textLines draws the frame as terminal text, once per colour depth, and +// keeps it: a frame of text is a few kilobytes, and text frames are redrawn +// on every repaint. +func (f *builtinFrame) textLines(colors TextColors) []string { + slot := 0 + if colors == Text256 { + slot = 1 + } + f.mu.Lock() + defer f.mu.Unlock() + if f.text[slot] == nil { + frame := petart.RenderWithHeadroom(f.form, f.mood, f.seconds, textScale, textHeadroom) + if f.mirror { + frame.Mirror() + } + if slot == 1 { + f.text[slot] = petart.HalfBlockLines256(frame) + } else { + f.text[slot] = petart.HalfBlockLines(frame) + } + } + return f.text[slot] +} + // drawnFrame returns a picture an encoder can read directly: built-in frames // are drawn now, and every other frame is returned as it is. func drawnFrame(frame image.Image) image.Image { diff --git a/internal/terminalpet/builtin_test.go b/internal/terminalpet/builtin_test.go index bfa936805..332804326 100644 --- a/internal/terminalpet/builtin_test.go +++ b/internal/terminalpet/builtin_test.go @@ -9,7 +9,9 @@ import ( "net/http/httptest" "os" "path/filepath" + "regexp" "slices" + "strings" "testing" "time" @@ -215,7 +217,7 @@ func TestBuiltinAnimationCoversEveryState(t *testing.T) { t.Fatal("BuiltinAnimation returned an animation for an unknown form") } frameSize := image.Rect(0, 0, 192, 208) - for _, state := range []State{Idle, MoveRight, MoveLeft, Waving, Jumping, Running, Waiting, Review, Failed, Dance, Lunge} { + for _, state := range []State{Idle, MoveRight, MoveLeft, Waving, Jumping, Running, Waiting, Review, Failed, Dance, Lunge, Thinking, Sleeping} { frame := animation.Frame(state, 0) // The frame must match a pet atlas frame, which the layout assumes. if frame == nil || frame.Bounds() != frameSize { @@ -226,7 +228,7 @@ func TestBuiltinAnimationCoversEveryState(t *testing.T) { } } // Loops never settle; one-shot states play for their length and then idle. - for _, state := range []State{Idle, Running, Waiting, MoveLeft, MoveRight} { + for _, state := range []State{Idle, Running, Waiting, MoveLeft, MoveRight, Thinking, Sleeping} { if got := animation.PrimaryDuration(state); got != 0 { t.Errorf("%s should loop, PrimaryDuration = %v", state, got) } @@ -318,3 +320,107 @@ func TestBuiltinFramesDrawTheCharacterWithHeadroom(t *testing.T) { } } } + +func TestBuiltinTextFramesFitTheTextSlot(t *testing.T) { + sgr := regexp.MustCompile(`\x1b\[[0-9;]*m`) + states := []State{Idle, MoveRight, MoveLeft, Waving, Jumping, Running, Waiting, Review, Failed, Dance, Lunge, Thinking, Sleeping} + for _, form := range petart.Forms() { + animation := BuiltinAnimation(form) + if !animation.HasText() { + t.Fatalf("%s has no text form", form) + } + for _, state := range states { + for _, phase := range []int{0, 3, 17} { + for _, colors := range []TextColors{TextTrueColor, Text256} { + lines, ok := animation.TextFrame(state, phase, colors) + if !ok || len(lines) != TextRows { + t.Fatalf("%s/%s phase %d: %d text lines, ok=%v", form, state, phase, len(lines), ok) + } + drawn := 0 + for index, line := range lines { + cells := []rune(sgr.ReplaceAllString(line, "")) + if len(cells) != TextColumns { + t.Fatalf("%s/%s line %d is %d cells wide, want %d", form, state, index, len(cells), TextColumns) + } + for _, cell := range cells { + if cell != ' ' { + drawn++ + } + } + } + if drawn < 40 { + t.Errorf("%s/%s phase %d: only %d cells drawn", form, state, phase, drawn) + } + } + } + } + } + + // Each colour depth uses its own codes, for the same picture. + truecolor, _ := BuiltinAnimation(petart.Twig).TextFrame(Idle, 0, TextTrueColor) + limited, _ := BuiltinAnimation(petart.Twig).TextFrame(Idle, 0, Text256) + if !strings.Contains(strings.Join(truecolor, ""), ";2;") || strings.Contains(strings.Join(limited, ""), ";2;") || + !strings.Contains(strings.Join(limited, ""), "38;5;") { + t.Error("text frames do not use the colour codes of their depth") + } + if sgr.ReplaceAllString(strings.Join(truecolor, "\n"), "") != sgr.ReplaceAllString(strings.Join(limited, "\n"), "") { + t.Error("the 256-colour frame draws a different picture") + } + + animation := BuiltinAnimation(petart.Twig) + first, _ := animation.TextFrame(Running, 2, TextTrueColor) + again, _ := animation.TextFrame(Running, 2, TextTrueColor) + if &first[0] != &again[0] { + t.Error("a text frame was drawn twice") + } + // The top pixel row is headroom: tall parts such as Robin's feather reach + // it, and a hop rises into it instead of being cut off. A cell whose top + // pixel is drawn is an upper half block, so Merlin standing has none on + // the first line and has some at the top of a hop. + if standing, _ := BuiltinAnimation(petart.Merlin).TextFrame(Idle, 0, TextTrueColor); strings.Contains(sgr.ReplaceAllString(standing[0], ""), "▀") { + t.Errorf("Merlin standing fills the headroom: %q", sgr.ReplaceAllString(standing[0], "")) + } + hopped := false + for phase := 0; phase < 23 && !hopped; phase++ { + frame, _ := BuiltinAnimation(petart.Merlin).TextFrame(Jumping, phase, TextTrueColor) + hopped = strings.Contains(sgr.ReplaceAllString(frame[0], ""), "▀") + } + if !hopped { + t.Error("Merlin never rises into the headroom while celebrating") + } + // Dragging right shows the mirror image of dragging left. + left, _ := animation.TextFrame(MoveLeft, 3, TextTrueColor) + right, _ := animation.TextFrame(MoveRight, 3, TextTrueColor) + if strings.Join(left, "\n") == strings.Join(right, "\n") { + t.Error("MoveRight text is not mirrored") + } +} + +func TestPictureAnimationsHaveNoTextOrExtraStates(t *testing.T) { + sheet, err := png.Decode(bytes.NewReader(encodedPNG(t, 24*atlasColumns, 26*9))) + if err != nil { + t.Fatal(err) + } + atlas, err := AtlasAnimation(sheet, 1) + if err != nil { + t.Fatal(err) + } + if atlas.HasText() { + t.Error("an atlas pet reports a text form") + } + if lines, ok := atlas.TextFrame(Idle, 0, TextTrueColor); ok || lines != nil { + t.Errorf("TextFrame for an atlas pet = %v, %v", lines, ok) + } + // Agents fall back to Running and Idle for pets without these states. + if atlas.Has(Thinking) || atlas.Has(Sleeping) || !atlas.Has(Running) || !atlas.Has(Idle) { + t.Errorf("atlas Has: thinking=%v sleeping=%v running=%v idle=%v", + atlas.Has(Thinking), atlas.Has(Sleeping), atlas.Has(Running), atlas.Has(Idle)) + } + var none *Animation + if none.Has(Idle) || none.HasText() { + t.Error("a nil animation reports frames") + } + if !BuiltinAnimation(petart.Ember).Has(Thinking) || !BuiltinAnimation(petart.Ember).Has(Sleeping) { + t.Error("built-in companions lack the thinking and sleeping states") + } +} diff --git a/internal/terminalpet/image_renderer.go b/internal/terminalpet/image_renderer.go index 47d55b981..e08c80b3d 100644 --- a/internal/terminalpet/image_renderer.go +++ b/internal/terminalpet/image_renderer.go @@ -39,10 +39,10 @@ func (s ImageSupport) Supported() bool { func DetectImageSupport(getenv func(string) string) ImageSupport { if strings.TrimSpace(getenv("TMUX")) != "" || strings.TrimSpace(getenv("TMUX_PANE")) != "" { - return ImageSupport{Reason: "Terminal companions are disabled in tmux because terminal images are not reliably pane-local."} + return ImageSupport{Reason: "tmux does not pass terminal images through reliably."} } if strings.TrimSpace(getenv("ZELLIJ")) != "" || strings.TrimSpace(getenv("ZELLIJ_SESSION_NAME")) != "" || strings.TrimSpace(getenv("ZELLIJ_VERSION")) != "" { - return ImageSupport{Reason: "Terminal companions are disabled in Zellij because terminal images are not reliably pane-local."} + return ImageSupport{Reason: "Zellij does not pass terminal images through reliably."} } if strings.TrimSpace(getenv("KITTY_WINDOW_ID")) != "" || strings.TrimSpace(getenv("WEZTERM_EXECUTABLE")) != "" || strings.TrimSpace(getenv("WEZTERM_VERSION")) != "" { return ImageSupport{Protocol: ImageProtocolKitty} @@ -53,7 +53,7 @@ func DetectImageSupport(getenv func(string) string) ImageSupport { if dottedVersionAtLeast(getenv("TERM_PROGRAM_VERSION"), 3, 6, 0) { return ImageSupport{Protocol: ImageProtocolKittyLocalFile} } - return ImageSupport{Reason: "Terminal companions require iTerm2 3.6 or newer."} + return ImageSupport{Reason: "Terminal images need iTerm2 3.6 or newer."} } if strings.Contains(term, "ghostty") || strings.Contains(program, "ghostty") || strings.TrimSpace(getenv("GHOSTTY_RESOURCES_DIR")) != "" || strings.Contains(term, "kitty") || strings.Contains(program, "kitty") || strings.Contains(term, "wezterm") || strings.Contains(program, "wezterm") { @@ -62,7 +62,7 @@ func DetectImageSupport(getenv func(string) string) ImageSupport { if strings.TrimSpace(getenv("WT_SESSION")) != "" || strings.Contains(term, "sixel") || strings.Contains(term, "mlterm") || strings.Contains(term, "foot") { return ImageSupport{Protocol: ImageProtocolSixel} } - return ImageSupport{Reason: "Terminal companions need Kitty graphics or Sixel image support."} + return ImageSupport{Reason: "This terminal does not show Kitty or Sixel images."} } type ImageDraw struct { diff --git a/internal/terminalpet/model.go b/internal/terminalpet/model.go index cbf583a5c..2cafdcc17 100644 --- a/internal/terminalpet/model.go +++ b/internal/terminalpet/model.go @@ -83,6 +83,32 @@ func (a *Animation) Frame(state State, phase int) image.Image { return frame } +// Has reports whether the animation has frames of its own for state. Frame +// shows the idle loop for any state the animation lacks. +func (a *Animation) Has(state State) bool { + return a != nil && len(a.frames[state]) > 0 +} + +// HasText reports whether the animation can be drawn as text, for terminals +// that cannot show images. Only built-in companions can. +func (a *Animation) HasText() bool { + frame, _ := a.frame(Idle, 0) + _, ok := frame.(*builtinFrame) + return ok +} + +// TextFrame returns one frame as TextRows lines of styled text, TextColumns +// cells wide, in the given colour depth. The boolean is false for animations +// made from pictures, which have no text form. +func (a *Animation) TextFrame(state State, phase int, colors TextColors) ([]string, bool) { + frame, _ := a.frame(state, phase) + builtin, ok := frame.(*builtinFrame) + if !ok { + return nil, false + } + return builtin.textLines(colors), true +} + func (a *Animation) FrameDelay(state State, phase int) time.Duration { if a == nil { return 0 diff --git a/internal/terminalpet/petart/petart_test.go b/internal/terminalpet/petart/petart_test.go index 7e5b8ba2e..890e9ab6f 100644 --- a/internal/terminalpet/petart/petart_test.go +++ b/internal/terminalpet/petart/petart_test.go @@ -2,6 +2,8 @@ package petart import ( "bytes" + "math" + "regexp" "strings" "testing" ) @@ -151,3 +153,223 @@ func TestImageKeepsShapeAndTransparency(t *testing.T) { } } } + +var sgrPattern = regexp.MustCompile(`\x1b\[[0-9;]*m`) + +func TestHalfBlockLines(t *testing.T) { + frame := Frame{Width: 4, Height: 3, Pixels: []byte( + "K.K." + + "KK.." + + "..R.", + )} + lines := HalfBlockLines(frame) + if len(lines) != 2 { + t.Fatalf("got %d lines, want 2", len(lines)) + } + // Cell by cell: both pixels, bottom only, top only, neither. + if got := sgrPattern.ReplaceAllString(lines[0], ""); got != "▀▄▀ " { + t.Errorf("first line glyphs = %q", got) + } + // The odd last row has no pixel beneath it. + if got := sgrPattern.ReplaceAllString(lines[1], ""); got != " ▀ " { + t.Errorf("second line glyphs = %q", got) + } + const ink, red = "35;24;21", "216;66;60" + want := "\x1b[0;38;2;" + ink + ";48;2;" + ink + "m▀" + + "\x1b[0;38;2;" + ink + "m▄▀" + + "\x1b[0m " + if lines[0] != want { + t.Errorf("first line = %q, want %q", lines[0], want) + } + // Leading blanks carry no styling, and a styled line ends reset so the + // colour cannot leak into whatever is drawn after it. + if want := " \x1b[0;38;2;" + red + "m▀\x1b[0m "; lines[1] != want { + t.Errorf("second line = %q, want %q", lines[1], want) + } + + sprite := HalfBlockLines(Sprite(Twig, Idle, 0)) + if len(sprite) != SpriteRows { + t.Fatalf("sprite has %d lines, want %d", len(sprite), SpriteRows) + } + for index, line := range sprite { + glyphs := sgrPattern.ReplaceAllString(line, "") + if count := len([]rune(glyphs)); count != SpriteColumns { + t.Errorf("line %d is %d cells wide, want %d", index, count, SpriteColumns) + } + if strings.Contains(line, "\x1b[") && !strings.HasSuffix(strings.TrimRight(line, " "), "\x1b[0m") { + t.Errorf("line %d does not end reset: %q", index, line) + } + } +} + +func TestRenderWithHeadroomAddsEmptyRowsAndMirror(t *testing.T) { + plain := Render(Merlin, Celebrate, 0.3, 0.375) + roomy := RenderWithHeadroom(Merlin, Celebrate, 0.3, 0.375, 2) + if roomy.Width != plain.Width || roomy.Height != plain.Height+2 { + t.Fatalf("headroom frame is %dx%d, plain is %dx%d", roomy.Width, roomy.Height, plain.Width, plain.Height) + } + // Mid-hop the hat rises: without headroom it is cut at the top edge, with + // headroom it is drawn. + drawnAbove := func(f Frame, rows int) int { + count := 0 + for _, key := range f.Pixels[:rows*f.Width] { + if key != transparent { + count++ + } + } + return count + } + if drawnAbove(roomy, 2) == 0 { + t.Error("nothing was drawn in the headroom mid-hop") + } + if !bytes.Equal(roomy.Pixels[2*roomy.Width:], RenderWithHeadroom(Merlin, Celebrate, 0.3, 0.375, 2).Pixels[2*roomy.Width:]) { + t.Error("RenderWithHeadroom is not deterministic") + } + if got := RenderWithHeadroom(Twig, Idle, 1.3, 0.5, 0); !bytes.Equal(got.Pixels, Sprite(Twig, Idle, 1.3).Pixels) { + t.Error("zero headroom differs from Render") + } + + mirrored := Render(Twig, Idle, 1.3, 0.5) + mirrored.Mirror() + original := Render(Twig, Idle, 1.3, 0.5) + for y := 0; y < original.Height; y++ { + for x := 0; x < original.Width; x++ { + if mirrored.Pixels[y*original.Width+x] != original.Pixels[y*original.Width+original.Width-1-x] { + t.Fatalf("Mirror is not a left-right flip at %d,%d", x, y) + } + } + } +} + +func TestHalfBlockLines256MatchesTheTrueColourLayout(t *testing.T) { + frame := RenderWithHeadroom(Ember, Happy, 0.7, 0.375, 1) + full, limited := HalfBlockLines(frame), HalfBlockLines256(frame) + if len(full) != len(limited) { + t.Fatalf("%d lines in true colour, %d in 256", len(full), len(limited)) + } + for index := range full { + if got, want := sgrPattern.ReplaceAllString(limited[index], ""), sgrPattern.ReplaceAllString(full[index], ""); got != want { + t.Fatalf("line %d glyphs differ: %q, want %q", index, got, want) + } + if strings.Contains(limited[index], ";2;") { + t.Fatalf("line %d of the 256-colour frame uses 24-bit colour: %q", index, limited[index]) + } + } + if !strings.Contains(strings.Join(limited, ""), "38;5;") { + t.Fatal("no 256-colour codes in the frame") + } +} + +// TestPalette256IsTheNearestColourByEye recomputes each palette256 entry: the +// xterm colour from 16 to 255 with the smallest CIEDE2000 difference. +func TestPalette256IsTheNearestColourByEye(t *testing.T) { + if len(palette256) != len(palette) { + t.Fatalf("palette256 has %d colours, palette has %d", len(palette256), len(palette)) + } + for key, c := range palette { + got, ok := palette256[key] + if !ok { + t.Fatalf("%q has no 256-colour value", key) + } + want, best := 0, math.Inf(1) + target := cieLab(float64(c.R), float64(c.G), float64(c.B)) + for index := 16; index < 256; index++ { + r, g, b := xterm256(index) + if d := ciede2000(target, cieLab(r, g, b)); d < best { + want, best = index, d + } + } + if int(got) != want { + t.Errorf("%q #%02x%02x%02x: palette256 has %d, nearest by CIEDE2000 is %d", key, c.R, c.G, c.B, got, want) + } + } +} + +func xterm256(index int) (float64, float64, float64) { + if index >= 232 { + v := float64(8 + (index-232)*10) + return v, v, v + } + index -= 16 + level := func(v int) float64 { + if v == 0 { + return 0 + } + return float64(55 + v*40) + } + return level(index / 36), level(index / 6 % 6), level(index % 6) +} + +type lab struct{ l, a, b float64 } + +func cieLab(r, g, b float64) lab { + linear := func(c float64) float64 { + c /= 255 + if c <= 0.04045 { + return c / 12.92 + } + return math.Pow((c+0.055)/1.055, 2.4) + } + r, g, b = linear(r), linear(g), linear(b) + x := (0.4124*r + 0.3576*g + 0.1805*b) / 0.95047 + y := 0.2126*r + 0.7152*g + 0.0722*b + z := (0.0193*r + 0.1192*g + 0.9505*b) / 1.08883 + f := func(t float64) float64 { + if t > 0.008856 { + return math.Cbrt(t) + } + return 7.787*t + 16.0/116 + } + fx, fy, fz := f(x), f(y), f(z) + return lab{116*fy - 16, 500 * (fx - fy), 200 * (fy - fz)} +} + +func ciede2000(c1, c2 lab) float64 { + rad := math.Pi / 180 + cAvg := (math.Hypot(c1.a, c1.b) + math.Hypot(c2.a, c2.b)) / 2 + g := 0.5 * (1 - math.Sqrt(math.Pow(cAvg, 7)/(math.Pow(cAvg, 7)+math.Pow(25, 7)))) + a1, a2 := (1+g)*c1.a, (1+g)*c2.a + cp1, cp2 := math.Hypot(a1, c1.b), math.Hypot(a2, c2.b) + hue := func(b, a float64) float64 { + h := math.Atan2(b, a) / rad + if h < 0 { + h += 360 + } + return h + } + h1, h2 := hue(c1.b, a1), hue(c2.b, a2) + dh := 0.0 + if cp1*cp2 != 0 { + dh = h2 - h1 + if dh > 180 { + dh -= 360 + } else if dh < -180 { + dh += 360 + } + } + dL, dC := c2.l-c1.l, cp2-cp1 + dH := 2 * math.Sqrt(cp1*cp2) * math.Sin(dh/2*rad) + lAvg, cpAvg := (c1.l+c2.l)/2, (cp1+cp2)/2 + hAvg := h1 + h2 + if cp1*cp2 != 0 { + switch { + case math.Abs(h1-h2) <= 180: + hAvg = (h1 + h2) / 2 + case h1+h2 < 360: + hAvg = (h1 + h2 + 360) / 2 + default: + hAvg = (h1 + h2 - 360) / 2 + } + } + tt := 1 - 0.17*math.Cos((hAvg-30)*rad) + 0.24*math.Cos(2*hAvg*rad) + 0.32*math.Cos((3*hAvg+6)*rad) - 0.2*math.Cos((4*hAvg-63)*rad) + hueOffset := (hAvg - 275) / 25 + theta := 30 * math.Exp(-hueOffset*hueOffset) + rc := 2 * math.Sqrt(math.Pow(cpAvg, 7)/(math.Pow(cpAvg, 7)+math.Pow(25, 7))) + lightness := (lAvg - 50) * (lAvg - 50) + sl := 1 + 0.015*lightness/math.Sqrt(20+lightness) + sc := 1 + 0.045*cpAvg + sh := 1 + 0.015*cpAvg*tt + rt := -math.Sin(2*theta*rad) * rc + l, c, h := dL/sl, dC/sc, dH/sh + return math.Sqrt(l*l + c*c + h*h + rt*c*h) +} diff --git a/internal/terminalpet/petart/render.go b/internal/terminalpet/petart/render.go index 6a3f4d16b..bed1f1b90 100644 --- a/internal/terminalpet/petart/render.go +++ b/internal/terminalpet/petart/render.go @@ -3,6 +3,8 @@ package petart import ( "image" "math" + "strconv" + "strings" ) const ( @@ -76,6 +78,137 @@ func Sprite(form Form, mood Mood, seconds float64) Frame { return Render(form, mood, seconds, SpriteScale) } +// RenderWithHeadroom is Render with headroom empty rows above the character, +// so the frame is that many pixels taller. The design space has no room above +// the head, and a hopping character would otherwise lose its hat to the top +// edge. +func RenderWithHeadroom(form Form, mood Mood, seconds, scale float64, headroom int) Frame { + g := draw(form, mood, seconds, scale, max(0, headroom)) + pixels, _ := g.finish(max(1, int(jsRound(scale)))) + return Frame{Width: g.width, Height: g.height, Pixels: pixels} +} + +// Mirror flips the frame left to right in place. +func (f Frame) Mirror() { + for y := 0; y < f.Height; y++ { + line := f.Pixels[y*f.Width : (y+1)*f.Width] + for left, right := 0, len(line)-1; left < right; left, right = left+1, right-1 { + line[left], line[right] = line[right], line[left] + } + } +} + +// HalfBlockLines turns a frame into terminal lines of 24-bit colour. Each cell +// shows two stacked pixels with an upper or lower half block, and transparent +// pixels stay as spaces so the terminal background shows through. Every line +// ends with a style reset. +func HalfBlockLines(frame Frame) []string { + return halfBlockLines(frame, func(selector int, key byte) string { + c := palette[key] + return sgrColor(selector, c.R, c.G, c.B) + }) +} + +// HalfBlockLines256 is HalfBlockLines for terminals with 256 colours. Left to +// a generic conversion, several colours land on the wrong hue (Twig's brown +// fur turns mauve, Ember's red wings brown), so every palette colour has its +// own 256-colour value; see palette256. +func HalfBlockLines256(frame Frame) []string { + return halfBlockLines(frame, func(selector int, key byte) string { + return strconv.Itoa(selector) + ";5;" + strconv.Itoa(int(palette256[key])) + }) +} + +// palette256 is, for each palette colour, the closest xterm colour by +// CIEDE2000 colour difference, which follows how people see colour far better +// than distance in RGB. It chooses from colours 16 to 255 only: terminals +// theme 0 to 15 freely, so those could be anything. +var palette256 = map[byte]uint8{ + 'K': 234, + 'B': 130, + 'b': 137, + 'D': 52, + 'C': 222, + 'E': 233, + 'W': 231, + 'N': 236, + 'P': 210, + 'G': 22, + 'g': 71, + 'R': 167, + 'S': 223, + 'H': 94, + 'Y': 221, + 'X': 252, + 'p': 141, + 'Q': 92, + 'w': 255, + 'n': 237, + 'M': 59, + 'V': 25, + 'd': 209, + 'o': 209, + 'F': 160, + 'O': 215, + 'A': 221, + 'u': 117, + 'U': 68, + 'T': 37, + 't': 79, + 'L': 234, + 'l': 59, + 'h': 251, + 'a': 244, + 'c': 45, +} + +func halfBlockLines(frame Frame, color func(selector int, key byte) string) []string { + lines := make([]string, 0, (frame.Height+1)/2) + for y := 0; y < frame.Height; y += 2 { + var line strings.Builder + styled := false + lastStyle := "" + for x := 0; x < frame.Width; x++ { + top := frame.Pixels[y*frame.Width+x] + bottom := byte(transparent) + if y+1 < frame.Height { + bottom = frame.Pixels[(y+1)*frame.Width+x] + } + _, hasTop := Color(top) + _, hasBottom := Color(bottom) + style, glyph := "", " " + switch { + case hasTop && hasBottom: + style = "\x1b[0;" + color(38, top) + ";" + color(48, bottom) + "m" + glyph = "▀" + case hasTop: + style = "\x1b[0;" + color(38, top) + "m" + glyph = "▀" + case hasBottom: + style = "\x1b[0;" + color(38, bottom) + "m" + glyph = "▄" + default: + style = "\x1b[0m" + } + if style != lastStyle && (styled || style != "\x1b[0m") { + line.WriteString(style) + styled = true + } + lastStyle = style + line.WriteString(glyph) + } + if styled && lastStyle != "\x1b[0m" { + line.WriteString("\x1b[0m") + } + lines = append(lines, line.String()) + } + return lines +} + +func sgrColor(selector int, r, g, b uint8) string { + return strconv.Itoa(selector) + ";2;" + strconv.Itoa(int(r)) + ";" + strconv.Itoa(int(g)) + ";" + strconv.Itoa(int(b)) +} + // Image draws one frame as a picture height pixels tall (the width keeps the // 48:40 shape), for terminals that show images. Edges are anti-aliased, // outlines take a darker shade of the colour they wrap, and a soft shadow diff --git a/internal/tui/attachment_preview.go b/internal/tui/attachment_preview.go index 60ac42553..31324922f 100644 --- a/internal/tui/attachment_preview.go +++ b/internal/tui/attachment_preview.go @@ -37,7 +37,7 @@ func (m model) attachmentThumbnailVisible(width int) bool { } func (m model) attachmentThumbnailSlots(width int) int { - innerWidth := maxInt(1, width-m.petComposerReservedColumns(width)-4) + innerWidth := m.composerInnerWidth(width) slots := maxInt(1, innerWidth/(attachmentPreviewCols+1)) return min(attachmentPreviewMaxImages, min(slots, len(m.attachmentRenderers))) } diff --git a/internal/tui/composer.go b/internal/tui/composer.go index bbe55fad4..566ef547c 100644 --- a/internal/tui/composer.go +++ b/internal/tui/composer.go @@ -273,7 +273,7 @@ func (m model) composerPositionAtMouse(msg tea.MouseMsg) (int, bool) { if contentY < 0 { return 0, false } - return m.composerPositionAtVisualCell(localX-2, contentY, maxInt(1, width-4)) + return m.composerPositionAtVisualCell(localX-2, contentY, m.composerInnerWidth(width)) } func (m model) composerMouseSelectionBlocked() bool { diff --git a/internal/tui/model.go b/internal/tui/model.go index 95c2e1bd6..2ac1fddde 100644 --- a/internal/tui/model.go +++ b/internal/tui/model.go @@ -15,6 +15,7 @@ import ( "charm.land/bubbles/v2/textinput" tea "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" + "github.com/charmbracelet/colorprofile" uv "github.com/charmbracelet/ultraviolet" "github.com/charmbracelet/x/ansi" @@ -191,6 +192,8 @@ type model struct { petClickAnimationIndex int petOutcome terminalpet.State petOutcomeAt time.Time + petLastActiveAt time.Time + petColorProfile colorprofile.Profile petLayoutRendering bool petPositionSet bool petPositionX int @@ -1115,6 +1118,7 @@ func newModel(ctx context.Context, options Options) model { if entry, entryErr := m.petClient.InstalledEntry(m.petID); entryErr == nil { m.petName = entry.Label() } + m.greetWithPet() } } } @@ -1692,6 +1696,7 @@ func (m model) updateModel(msg tea.Msg) (tea.Model, tea.Cmd) { m.burstCount = 0 } m.lastKeyTime = now + m.petLastActiveAt = now if !keyIs(msg, tea.KeyEnter) { m.lastCharTime = now } @@ -2734,12 +2739,10 @@ func (m model) updateModel(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil } m.clearStreamingToolCall() // active run finished — drop any lingering "writing" block - if msg.err != nil { - m.petOutcome = terminalpet.Failed - } else { - m.petOutcome = terminalpet.Review - } - m.petOutcomeAt = m.now() + finishedAt := m.now() + m.petOutcome = m.petTurnOutcome(msg.err, finishedAt) + m.petOutcomeAt = finishedAt + m.petLastActiveAt = finishedAt m.pending = false m = m.disarmCancelConfirmation() // the run finished on its own — nothing left to confirm cancelling // A newline-triggered redraw deferred by the stream-clear throttle @@ -3212,6 +3215,9 @@ func (m model) updateModel(msg tea.Msg) (tea.Model, tea.Cmd) { return m.applySetupOAuthDeviceCode(msg) case modelPickerModelsDiscoveredMsg: return m.applyModelPickerModelsDiscovered(msg), nil + case tea.ColorProfileMsg: + m.petColorProfile = msg.Profile + return m, nil case petCatalogLoadedMsg: return m.applyPetCatalog(msg) case petPreviewDebounceMsg: @@ -3462,27 +3468,29 @@ func (m model) footerView(width int) string { // a faint idle affordance — discoverable key hints on the left, a jump-to-bottom // cue on the right when scrolled up. Always one line (blank when nothing shows), // so the footer height is unchanged. + // A docked text companion stands beside these rows, so they end before it. + lineWidth := width - m.petTextReservedColumns(width) if copyStatus := strings.TrimSpace(m.copyStatus); copyStatus != "" { - footer.WriteString(rightAlignedLine(zeroTheme.ink.Render(copyStatus), width)) - } else if notice := m.transientNoticeLine(width); notice != "" { + footer.WriteString(rightAlignedLine(zeroTheme.ink.Render(copyStatus), lineWidth)) + } else if notice := m.transientNoticeLine(lineWidth); notice != "" { footer.WriteString(notice) } else if recap := strings.TrimSpace(m.idleRecap); recap != "" { - footer.WriteString(fitStyledLine(" "+zeroTheme.faint.Render("※ "+recap), width)) + footer.WriteString(fitStyledLine(" "+zeroTheme.faint.Render("※ "+recap), lineWidth)) } else if left, right := m.composerIdleHint(), m.jumpToBottomHint(); left != "" || right != "" { - footer.WriteString(fitStyledLine(joinHeaderLine(" "+left, right, width), width)) + footer.WriteString(fitStyledLine(joinHeaderLine(" "+left, right, lineWidth), lineWidth)) } footer.WriteString("\n") // A message typed while a run is active is queued for the next turn; show its // preview directly ABOVE the input box (not below), so it reads as "waiting to // send" sitting on top of what you're currently typing. - if queued := renderQueuedMessagePreview(m.queuedMessage, width); queued != "" { + if queued := renderQueuedMessagePreview(m.queuedMessage, lineWidth); queued != "" { footer.WriteString(queued) footer.WriteString("\n") } footer.WriteString(m.composerBox(width)) footer.WriteString("\n") footer.WriteString(m.footerStatusLine(width)) - return footer.String() + return m.petTextShelf(footer.String()) } // composerIdleHint returns a faint one-line key-shortcut hint shown above the @@ -4538,7 +4546,7 @@ func (m model) moveComposerVisualCursor(direction int) (model, bool) { } previews := validComposerPastePreviews(state, m.composerPastePreviews) displayState := composerDisplayStateForPastePreviews(state, previews) - segments := composerWrappedVisualLines(input, displayState, maxInt(1, width-4)) + segments := composerWrappedVisualLines(input, displayState, m.composerInnerWidth(width)) if len(segments) <= 1 { return m, false } @@ -4633,13 +4641,21 @@ func commandArgumentHintForInput(value string) string { return commandRequiredInputHint(command.name) } +// composerInnerWidth is the width the composer wraps its text at: the box +// less its borders and padding, and less the columns a docked companion +// takes. Drawing, mouse hit-testing and Up/Down movement must all use it, or +// a click or arrow lands on a different wrapped row than the one drawn. +func (m model) composerInnerWidth(width int) int { + return maxInt(1, width-m.petComposerReservedColumns(width)-4) +} + func (m model) composerBox(width int) string { if width < 8 { return fitStyledLine(m.composerLine(width), width) } reserved := m.petComposerReservedColumns(width) boxWidth := width - reserved - innerWidth := maxInt(1, boxWidth-4) + innerWidth := m.composerInnerWidth(width) content := m.composerLine(innerWidth) lines := strings.Split(content, "\n") rightPad := strings.Repeat(" ", reserved) @@ -5631,6 +5647,7 @@ func (m model) beginRun(cancel context.CancelFunc) model { m.runDetailsOpen = false m.turnStartedAt = m.now() m.turnTimer = newActiveTurnTimer(m.turnStartedAt) + m.petLastActiveAt = m.turnStartedAt m.lastStreamActivity = m.turnStartedAt m.turnStreamedRunes = 0 m.spinnerTicking = true diff --git a/internal/tui/pets.go b/internal/tui/pets.go index 1cc77e49d..96018cc65 100644 --- a/internal/tui/pets.go +++ b/internal/tui/pets.go @@ -1,6 +1,7 @@ package tui import ( + "bytes" "context" "errors" "fmt" @@ -9,6 +10,7 @@ import ( tea "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" + "github.com/charmbracelet/colorprofile" "github.com/charmbracelet/x/ansi" "github.com/Twigpine/zero/internal/config" @@ -31,6 +33,19 @@ const ( petPickerMaxWidth = 58 petSidePreviewMin = 50 petPreviewPaneGap = 2 + // petTextMinWidth keeps the composer usable beside a text companion, + // which is twice as wide as an image one. + petTextMinWidth = 60 + // petSleepAfter is how long the companion waits, with no turn running, no + // key pressed and no reaction playing, before it falls asleep. + // model.petLastActiveAt records the last key press or turn boundary, from + // clock readings Zero already takes there, so the key and turn paths read + // the clock no more often than before. Paste and mouse wheel input do not + // count. + petSleepAfter = 5 * time.Minute + // petBigTurn is how long a turn has to run for the companion to celebrate + // when it succeeds, instead of the usual hop. + petBigTurn = time.Minute ) type petCatalogLoadedMsg struct { @@ -70,8 +85,9 @@ func (m model) handlePetsCommand(argument string) (tea.Model, tea.Cmd) { if m.petClient == nil { return m.appendSystemNotice("Pets are unavailable because the user config directory could not be resolved."), nil } - if m.petRenderer != nil && !m.petRenderer.Support().Supported() { - return m.appendSystemNotice(m.petRenderer.Support().Reason), nil + textOnly := m.petRenderer != nil && !m.petRenderer.Support().Supported() + if textOnly && !m.petTextMode() { + return m.appendSystemNotice(m.petRenderer.Support().Reason + " Text companions need 256 colours."), nil } argument = strings.ToLower(strings.TrimSpace(argument)) switch argument { @@ -97,6 +113,9 @@ func (m model) handlePetsCommand(argument string) (tea.Model, tea.Cmd) { return m.installPet(entry.Slug) } } + if textOnly { + return m.openTextPetPicker(argument) + } m.petRequestedSlug = argument m.petCatalogError = "" localEntries, _ := m.petClient.InstalledEntries() @@ -114,6 +133,30 @@ func (m model) handlePetsCommand(argument string) (tea.Model, tea.Cmd) { return m, batchCommands(previewCmd, catalogCmd) } +// openTextPetPicker offers the built-in companions on a terminal that cannot +// show images. Community pets are pictures, so they are not listed and the +// catalog is not fetched. +func (m model) openTextPetPicker(requested string) (tea.Model, tea.Cmd) { + if requested != "" { + return m.appendSystemNotice(fmt.Sprintf("%q needs terminal images. Run /pets for the built-in companions.", requested)), nil + } + var items []pickerItem + m.petEntries, items = petPickerItems(terminalpet.BuiltinEntries()) + m.petCatalogError = "Community pets need images" + selected := selectedPetPickerItem(items, m.petID) + if selected == 0 && m.petID != "" && m.petID != terminalpet.DisabledID { + // The current pet is a community pet, which this picker cannot list. + // Start on the first companion rather than "No companion", so Enter + // cannot switch the pet off by accident. + selected = minInt(1, len(items)-1) + } + m.picker = &commandPicker{ + kind: pickerPet, title: "Choose a companion", + items: items, allItems: append([]pickerItem{}, items...), selected: selected, + } + return m.schedulePetPreview() +} + func (m model) applyPetCatalog(msg petCatalogLoadedMsg) (tea.Model, tea.Cmd) { if m.picker == nil || m.picker.kind != pickerPet { return m, nil @@ -290,10 +333,13 @@ func (m model) applyPetInstall(msg petInstalledMsg) (tea.Model, tea.Cmd) { m.petAnimation = msg.animation m.petPhase = 0 m.petTickSeq++ - m.petPlaybackState = terminalpet.Idle m.petClickAnimationIndex = 0 - m.petOutcome = terminalpet.Idle - m = m.showTransientNoticeInline(msg.entry.Label()+" is now your terminal companion. Use /pets off to hide it.", transientNoticeSuccess) + m.greetWithPet() + notice := msg.entry.Label() + " is now your terminal companion. Use /pets off to hide it." + if m.petTextMode() && m.width < petTextMinWidth { + notice = fmt.Sprintf("%s shows once the window is %d+ columns wide.", msg.entry.Label(), petTextMinWidth) + } + m = m.showTransientNoticeInline(notice, transientNoticeSuccess) if m.reducedMotion { return m, nil } @@ -312,9 +358,16 @@ func (m model) petPickerOverlay(width int) string { item, hasItem := m.picker.current() hasPreviewTarget := hasItem && item.Value != terminalpet.DisabledID sidePreview := hasPreviewTarget && innerWidth >= petSidePreviewMin + previewColumns, previewRows := m.petSlotColumns(), m.petSlotRows() + // On a text-only terminal the preview is drawn into the overlay itself; + // otherwise the image is placed over the blank pane afterwards. + var previewText []string + if m.petTextMode() && m.petPreview != nil { + previewText, _ = m.petPreview.TextFrame(terminalpet.Idle, m.petPhase, m.petTextColors()) + } listWidth := innerWidth if sidePreview { - listWidth -= petImageColumns + petPreviewPaneGap + listWidth -= previewColumns + petPreviewPaneGap } previewDivider := zeroTheme.line.Render("│") + " " listLine := func(line string) string { @@ -322,7 +375,7 @@ func (m model) petPickerOverlay(width int) string { if !sidePreview { return line } - return padStyledLine(line, listWidth) + previewDivider + strings.Repeat(" ", petImageColumns) + return padStyledLine(line, listWidth) + previewDivider + strings.Repeat(" ", previewColumns) } listHeight := minInt(8, len(m.picker.items)) start := 0 @@ -361,14 +414,23 @@ func (m model) petPickerOverlay(width int) string { lines = append(lines, listLine(zeroTheme.faint.Render(" "+m.petCatalogError))) } if sidePreview && m.petPreview != nil { - for len(lines)-listStartRow < petImageRows { + // Images start on the title row; text starts on the row below it. + needed := previewRows + if previewText != nil { + needed = len(previewText) + 1 + } + for len(lines)-listStartRow < needed { lines = append(lines, listLine("")) } } if sidePreview && len(lines) > listStartRow { - previewTitle := centerRenderedBlock(zeroTheme.accent.Render("Preview"), petImageColumns) + previewTitle := centerRenderedBlock(zeroTheme.accent.Render("Preview"), previewColumns) lines[listStartRow] = padStyledLine(ansi.Cut(lines[listStartRow], 0, listWidth), listWidth) + previewDivider + previewTitle + for index, previewLine := range previewText { + row := listStartRow + 1 + index + lines[row] = padStyledLine(ansi.Cut(lines[row], 0, listWidth), listWidth) + previewDivider + previewLine + } } lines = append(lines, zeroTheme.line.Render(strings.Repeat("─", innerWidth))) switch { @@ -376,6 +438,8 @@ func (m model) petPickerOverlay(width int) string { lines = append(lines, zeroTheme.faint.Render("Loading preview…")) case m.petPreviewError != "": lines = append(lines, zeroTheme.faint.Render(m.petPreviewError)) + case m.petPreview != nil && !sidePreview && previewText != nil: + lines = append(lines, strings.Split(centerRenderedBlock(strings.Join(previewText, "\n"), innerWidth), "\n")...) case m.petPreview != nil && !sidePreview: for range petImageRows { lines = append(lines, "") @@ -420,10 +484,15 @@ func (m model) petLayoutActive() bool { return false } if m.petRenderer != nil && !m.petRenderer.Support().Supported() { - return false + // Without images, only a companion that can be drawn as text shows. + // A permission card is drawn in the transcript, where the companion + // would cover its options, so the companion steps aside for it. + if !m.petTextMode() || !m.petAnimation.HasText() || m.width < petTextMinWidth || m.pendingPermission != nil { + return false + } } layoutWidth := m.width - if !m.altScreen || layoutWidth < petImageColumns+4 || m.height < petImageRows+8 || m.subchat.active || m.transcriptDetailed { + if !m.altScreen || layoutWidth < m.petSlotColumns()+4 || m.height < m.petSlotRows()+8 || m.subchat.active || m.transcriptDetailed { return false } if m.petObscuringModalActive() || m.suggestionsActive() || m.setup.visible || m.helpOverlay || m.leaderHelpOverlay { @@ -448,10 +517,15 @@ func (m model) petComposerReservedColumns(width int) int { if m.petSupportsAlphaOverlay() && (m.petPositionSet || (m.petDragActive && !m.petDragStartedDocked)) { return 0 } - return minInt(petReservedColumns, maxInt(0, width-8)) + return minInt(m.petSlotReservedColumns(), maxInt(0, width-8)) } func (m model) footerStatusLine(width int) string { + // A text companion ends one row above the status line, so the line keeps + // its full width. + if m.petTextDocked() { + return m.statusLine(width) + } reserved := m.petComposerReservedColumns(width) return m.statusLine(width-reserved) + strings.Repeat(" ", reserved) } @@ -460,17 +534,124 @@ func (m model) floatingPetTranscriptView() string { chatModel := m chatModel.petLayoutRendering = true chat := m.reservePetImageSlot(viewLines(chatModel.transcriptView()), m.width) + if m.petTextMode() { + chat = m.paintPetText(chat, m.width) + } return strings.Join(chat, "\n") } +// petTextMode reports whether companions are drawn as text: the terminal +// cannot show images, but it has the colours the half-block art needs. +// model.petColorProfile is the profile Bubble Tea detected. +func (m model) petTextMode() bool { + return m.petRenderer != nil && !m.petRenderer.Support().Supported() && m.petColorProfile >= colorprofile.ANSI256 +} + +// petTextDocked reports whether a text companion stands in its slot in the +// view being drawn or measured. Like petComposerReservedColumns it holds both +// while the floating layout renders and for callers that measure the footer +// outside it, such as mouse hit-testing, so every measurement agrees. +func (m model) petTextDocked() bool { + return m.petTextMode() && (m.petLayoutRendering || m.petLayoutActive()) +} + +// petTextReservedColumns is how many columns at the right of the footer rows a +// docked text companion takes, or zero. +func (m model) petTextReservedColumns(width int) int { + if !m.petTextDocked() { + return 0 + } + return m.petComposerReservedColumns(width) +} + +// petTextShelf makes room for a docked text companion. It is taller than the +// composer, and the rows above the footer belong to the transcript, whose +// right-hand columns it would hide. Blank rows above the footer push the +// transcript up instead, so the companion stands only beside footer rows, +// which end before it. +func (m model) petTextShelf(footer string) string { + if !m.petTextDocked() { + return footer + } + // The companion's bottom row is one above the last line, the status line. + missing := m.petSlotRows() + 1 - (strings.Count(footer, "\n") + 1) + if missing <= 0 { + return footer + } + return strings.Repeat("\n", missing) + footer +} + +// petTextColors is the colour depth to draw text companions in. A +// 256-colour terminal gets the art's own 256-colour palette rather than +// Bubble Tea's generic conversion, which turns several of its hues. +func (m model) petTextColors() terminalpet.TextColors { + if m.petColorProfile == colorprofile.ANSI256 { + return terminalpet.Text256 + } + return terminalpet.TextTrueColor +} + +// petSlotColumns and petSlotRows are the cells the companion occupies. +func (m model) petSlotColumns() int { + if m.petTextMode() { + return terminalpet.TextColumns + } + return petImageColumns +} + +func (m model) petSlotRows() int { + if m.petTextMode() { + return terminalpet.TextRows + } + return petImageRows +} + +func (m model) petSlotReservedColumns() int { + return m.petSlotColumns() + petWrapGapColumns +} + +// paintPetText draws a text companion into the slot reservePetImageSlot +// cleared, where petHit looks for it. +func (m model) paintPetText(chat []string, width int) []string { + state, phase := m.petTextPlayback() + lines, ok := m.petAnimation.TextFrame(state, phase, m.petTextColors()) + if !ok { + return chat + } + x, y := m.ambientPetPosition(width, len(chat)) + for index, line := range lines { + row := y + index + if row < 0 || row >= len(chat) { + continue + } + left := padStyledLine(ansi.Cut(fitStyledLine(chat[row], width), 0, x), x) + // Reset first: the sprite's blank cells must not take a style left + // open by the text beside it. + chat[row] = left + "\x1b[0m" + line + strings.Repeat(" ", maxInt(0, width-x-terminalpet.TextColumns)) + } + return chat +} + +// petTextPlayback is the state and phase of the ambient companion's current +// frame, as petImageDraw computes them for images. +func (m model) petTextPlayback() (terminalpet.State, int) { + state := m.petState() + phase := m.petPhase + if state != m.petPlaybackState { + phase = 0 + } + return state, phase +} + func (m model) reservePetImageSlot(lines []string, width int) []string { chat := append([]string(nil), lines...) if m.petSupportsAlphaOverlay() { return chat } - start := maxInt(0, len(chat)-petImageRows-1) - rightStart := maxInt(0, width-petReservedColumns) - for row := start; row < minInt(len(chat)-1, start+petImageRows); row++ { + rows := m.petSlotRows() + start := maxInt(0, len(chat)-rows-1) + rightStart := maxInt(0, width-m.petSlotReservedColumns()) + for row := start; row < minInt(len(chat)-1, start+rows); row++ { line := fitStyledLine(chat[row], width) chat[row] = padStyledLine(ansi.Cut(line, 0, rightStart), rightStart) + strings.Repeat(" ", width-rightStart) } @@ -587,8 +768,8 @@ func (m model) petImageHeightPixels(animation *terminalpet.Animation, state term } func (m model) ambientPetPosition(width, height int) (int, int) { - maxX := maxInt(0, width-petImageColumns) - maxY := maxInt(0, height-petImageRows) + maxX := maxInt(0, width-m.petSlotColumns()) + maxY := maxInt(0, height-m.petSlotRows()) if m.petSupportsAlphaOverlay() { if m.petDragActive { return clampInt(m.petDragTargetX, 0, maxX), clampInt(m.petDragTargetY, 0, maxY) @@ -639,9 +820,10 @@ func resizePetCoordinate(value, oldMaximum, newMaximum, edgeThreshold int) int { } func (m model) petHomePosition(width, height int) (int, int) { - maxX := maxInt(0, width-petImageColumns) - maxY := maxInt(0, height-petImageRows) - return clampInt(width-petImageColumns-2, 0, maxX), clampInt(height-petImageRows-1, 0, maxY) + columns, rows := m.petSlotColumns(), m.petSlotRows() + maxX := maxInt(0, width-columns) + maxY := maxInt(0, height-rows) + return clampInt(width-columns-2, 0, maxX), clampInt(height-rows-1, 0, maxY) } func (m model) ambientPetOffset(x, y, width, height int) (int, int) { @@ -729,7 +911,7 @@ func (m model) petHit(x, y int) bool { return false } petX, petY := m.ambientPetPosition(m.width, m.height) - return x >= petX && x < petX+petImageColumns && y >= petY && y < petY+petImageRows + return x >= petX && x < petX+m.petSlotColumns() && y >= petY && y < petY+m.petSlotRows() } func (m model) handlePetMouse(msg tea.MouseMsg) (model, tea.Cmd, bool) { @@ -763,8 +945,9 @@ func (m model) handlePetMouse(msg tea.MouseMsg) (model, tea.Cmd, bool) { } return m, batchCommands(petImageFlushCmd(), animationCmd), true case mouseMotion(msg) && m.petDragActive && !m.petSupportsAlphaOverlay(): - // Sixel images are part of the terminal cell grid. Keep them in the - // dedicated dock so moving one can never overwrite cells Bubble Tea owns. + // Sixel images and text companions are part of the terminal cell grid. + // Keep them in the dedicated dock so moving one can never overwrite + // cells Bubble Tea owns. return m, nil, true case mouseMotion(msg) && m.petDragActive: oldX, oldY := m.petDragTargetX, m.petDragTargetY @@ -1047,8 +1230,17 @@ func (m model) petState() terminalpet.State { return terminalpet.Waiting } if m.pending { + if m.petAnimation.Has(terminalpet.Thinking) && m.petAgentThinking() { + return terminalpet.Thinking + } return terminalpet.Running } + sleeps := m.petAnimation.Has(terminalpet.Sleeping) + if m.petOutcome == "" && !sleeps { + return terminalpet.Idle + } + // One clock reading serves both checks below. + now := m.now() if m.petOutcome != "" { hold := petOutcomeHold if duration, customClick := m.petAnimation.ClickDuration(m.petOutcome); customClick && duration > 0 { @@ -1056,13 +1248,56 @@ func (m model) petState() terminalpet.State { } else if duration := m.petAnimation.PrimaryDuration(m.petOutcome); duration > hold { hold = duration } - if m.now().Sub(m.petOutcomeAt) < hold { + if now.Sub(m.petOutcomeAt) < hold { return m.petOutcome } } + if sleeps { + // A reaction, such as the one a click starts, counts as activity too. + lastActive := m.petLastActiveAt + if m.petOutcomeAt.After(lastActive) { + lastActive = m.petOutcomeAt + } + if !lastActive.IsZero() && now.Sub(lastActive) >= petSleepAfter { + return terminalpet.Sleeping + } + } return terminalpet.Idle } +// petAgentThinking reports whether a running turn is between visible actions: +// no tool call is streaming or running, and no answer text is arriving. It +// mirrors the "thinking" phase of the working status line. +func (m model) petAgentThinking() bool { + if m.streamCallName != "" || len(bytes.TrimSpace(m.streamingText)) > 0 { + return false + } + _, toolRunning := m.activeToolCall() + return !toolRunning +} + +// greetWithPet starts the companion's wave, as when it first appears. +func (m *model) greetWithPet() { + m.petOutcome = terminalpet.Waving + m.petOutcomeAt = m.now() + m.petPlaybackState = terminalpet.Waving + // The default waving row begins with the same neutral stance as idle. + m.petPhase = 1 +} + +// petTurnOutcome is the companion's reaction to a finished turn: a flinch for +// a failure, a celebration for a long success, a hop otherwise. +func (m model) petTurnOutcome(err error, finishedAt time.Time) terminalpet.State { + switch { + case err != nil: + return terminalpet.Failed + case !m.turnStartedAt.IsZero() && m.activeTurnElapsedAt(m.turnStartedAt, finishedAt) >= petBigTurn: + return terminalpet.Jumping + default: + return terminalpet.Review + } +} + func (m model) petPlayback() (*terminalpet.Animation, terminalpet.State) { if m.picker != nil && m.picker.kind == pickerPet && m.petPreview != nil { return m.petPreview, terminalpet.Idle diff --git a/internal/tui/pets_test.go b/internal/tui/pets_test.go index 06d65e45f..5a98a534b 100644 --- a/internal/tui/pets_test.go +++ b/internal/tui/pets_test.go @@ -3,6 +3,7 @@ package tui import ( "bytes" "context" + "errors" "fmt" "image" "image/color" @@ -14,7 +15,12 @@ import ( "time" tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" "github.com/Twigpine/zero/internal/terminalpet" + "github.com/Twigpine/zero/internal/terminalpet/petart" + "github.com/Twigpine/zero/internal/tools" + "github.com/Twigpine/zero/internal/zeroruntime" + "github.com/charmbracelet/colorprofile" uv "github.com/charmbracelet/ultraviolet" "github.com/charmbracelet/x/ansi" ) @@ -1542,3 +1548,521 @@ func TestPetCatalogGroupsBuiltinCompanionsAndReportsMissingCommunityCatalog(t *t t.Fatalf("stale catalog note:\n%s", plain) } } + +// textPetModel is a full-screen session on a terminal without image support +// but with true colour, showing built-in Twig. +func textPetModel(t *testing.T) model { + t.Helper() + m := newModel(context.Background(), Options{AltScreen: true, UserConfigPath: filepath.Join(t.TempDir(), "config.json")}) + m.width, m.height = 100, 30 + m.transcript = appendTranscriptRow(m.transcript, transcriptRow{kind: rowUser, text: "hello"}) + m.petRenderer = terminalpet.NewImageRenderer(terminalpet.ImageSupport{Reason: "tmux does not pass terminal images through reliably."}) + m.petColorProfile = colorprofile.TrueColor + m.petID, m.petName, m.petAnimation = "zero:twig", "Twig", terminalpet.BuiltinAnimation(petart.Twig) + m.petOutcome = "" + return m +} + +func TestColorProfileMessageIsRecorded(t *testing.T) { + m := newModel(context.Background(), Options{}) + updated, _ := m.Update(tea.ColorProfileMsg{Profile: colorprofile.ANSI256}) + if got := updated.(model).petColorProfile; got != colorprofile.ANSI256 { + t.Fatalf("petColorProfile = %v, want ANSI256", got) + } +} + +func TestTextPetDrawsInItsSlotWhereClicksLand(t *testing.T) { + m := textPetModel(t) + if !m.petTextMode() || !m.petLayoutActive() { + t.Fatalf("text companion inactive: textMode=%v layout=%v", m.petTextMode(), m.petLayoutActive()) + } + if m.petImageDraw("") != nil { + t.Fatal("a text companion must not send an image") + } + if got := m.petComposerReservedColumns(m.width); got != terminalpet.TextColumns+petWrapGapColumns { + t.Fatalf("composer reserves %d columns, want %d", got, terminalpet.TextColumns+petWrapGapColumns) + } + content := m.View().Content + lines := strings.Split(plainRender(t, content), "\n") + if len(lines) != m.height { + t.Fatalf("view has %d lines, want the terminal height %d", len(lines), m.height) + } + x, y := m.ambientPetPosition(m.width, m.height) + state, phase := m.petTextPlayback() + want, ok := m.petAnimation.TextFrame(state, phase, terminalpet.TextTrueColor) + if !ok { + t.Fatal("no text frame") + } + for index, spriteLine := range want { + row := []rune(lines[y+index]) + if len(row) < x+terminalpet.TextColumns { + t.Fatalf("row %d is %d cells, too short for the companion at column %d:\n%s", y+index, len(row), x, strings.Join(lines, "\n")) + } + got := string(row[x : x+terminalpet.TextColumns]) + if wantPlain := ansi.Strip(spriteLine); got != wantPlain { + t.Fatalf("row %d of the companion = %q, want %q:\n%s", index, got, wantPlain, strings.Join(lines, "\n")) + } + // Clicks on any of its cells reach it. + if !m.petHit(x, y+index) || !m.petHit(x+terminalpet.TextColumns-1, y+index) { + t.Fatalf("row %d of the companion does not take clicks", index) + } + } + if m.petHit(x-1, y) || m.petHit(x, y-1) { + t.Fatal("clicks outside the companion reach it") + } + if !strings.Contains(content, "\x1b[0;38;2;") { + t.Fatal("a true-colour terminal did not get the art's exact colours") + } + // A 256-colour terminal gets the art's own 256-colour palette. + m.petColorProfile = colorprofile.ANSI256 + if limited := m.View().Content; !strings.Contains(limited, "\x1b[0;38;5;") || strings.Contains(limited, "\x1b[0;38;2;") { + t.Fatal("a 256-colour terminal did not get the 256-colour palette") + } +} + +func TestTextPetNeedsColourRoomAndABuiltin(t *testing.T) { + sheet := image.NewNRGBA(image.Rect(0, 0, 12, 12)) + thumbnail, _ := terminalpet.ThumbnailAnimation(sheet) + cases := []struct { + name string + change func(*model) + text bool + active bool + }{ + {"true colour", func(*model) {}, true, true}, + {"256 colours", func(m *model) { m.petColorProfile = colorprofile.ANSI256 }, true, true}, + {"16 colours", func(m *model) { m.petColorProfile = colorprofile.ANSI }, false, false}, + {"no colour", func(m *model) { m.petColorProfile = colorprofile.ASCII }, false, false}, + {"profile not yet known", func(m *model) { m.petColorProfile = colorprofile.Unknown }, false, false}, + {"narrow terminal", func(m *model) { m.width = petTextMinWidth - 1 }, true, false}, + {"community pet", func(m *model) { m.petID, m.petAnimation = "boba", thumbnail }, true, false}, + {"image terminal", func(m *model) { + m.petRenderer = terminalpet.NewImageRenderer(terminalpet.ImageSupport{Protocol: terminalpet.ImageProtocolKitty}) + }, false, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + m := textPetModel(t) + tc.change(&m) + if got := m.petTextMode(); got != tc.text { + t.Errorf("petTextMode = %v, want %v", got, tc.text) + } + if got := m.petLayoutActive(); got != tc.active { + t.Errorf("petLayoutActive = %v, want %v", got, tc.active) + } + }) + } + // An image terminal keeps the image slot. + m := textPetModel(t) + m.petRenderer = terminalpet.NewImageRenderer(terminalpet.ImageSupport{Protocol: terminalpet.ImageProtocolSixel}) + if m.petSlotColumns() != petImageColumns || m.petSlotRows() != petImageRows { + t.Fatalf("image slot is %dx%d", m.petSlotColumns(), m.petSlotRows()) + } +} + +func TestPetsCommandOnTextTerminalOffersOnlyBuiltins(t *testing.T) { + m := textPetModel(t) + updated, _ := m.handlePetsCommand("") + next := updated.(model) + if next.picker == nil || next.picker.loading { + t.Fatalf("picker = %#v, want the built-ins without a catalog fetch", next.picker) + } + want := []pickerItem{{Label: "No companion", Value: terminalpet.DisabledID, Meta: "off"}} + for _, entry := range terminalpet.BuiltinEntries() { + want = append(want, pickerItem{Group: "Built in", Label: entry.Label(), Value: entry.Slug, Local: true}) + } + if !reflect.DeepEqual(next.picker.items, want) { + t.Fatalf("text picker items = %#v", next.picker.items) + } + if plain := plainRender(t, next.petPickerOverlay(next.width)); !strings.Contains(plain, "Community pets need images") { + t.Fatalf("text picker does not say why community pets are missing:\n%s", plain) + } + + // A built-in by name is chosen directly. + updated, cmd := m.handlePetsCommand("ember") + if next := updated.(model); next.picker != nil || cmd == nil { + t.Fatalf("/pets ember did not select the built-in: picker=%v", next.picker) + } + if installed := cmd().(petInstalledMsg); installed.entry.Slug != "zero:ember" || installed.err != nil { + t.Fatalf("installed %#v, %v", installed.entry, installed.err) + } + + // A community pet cannot be drawn here, and says so. + updated, cmd = m.handlePetsCommand("boba") + next = updated.(model) + if cmd != nil || next.picker != nil { + t.Fatal("/pets boba should not open a picker or fetch on a text terminal") + } + if plain := plainRender(t, next.View().Content); !strings.Contains(plain, `"boba" needs terminal images. Run /pets for the built-in companions.`) { + t.Fatalf("missing explanation for a community pet on a text terminal:\n%s", plain) + } +} + +func TestPetsCommandExplainsWhenNeitherImagesNorTextWork(t *testing.T) { + m := textPetModel(t) + m.petColorProfile = colorprofile.ANSI + updated, cmd := m.handlePetsCommand("") + next := updated.(model) + if cmd != nil || next.picker != nil { + t.Fatal("a 16-colour terminal without images should not open the picker") + } + plain := plainRender(t, next.View().Content) + if !strings.Contains(plain, "tmux does not pass terminal images through reliably. Text companions need 256 colours.") { + t.Fatalf("missing explanation:\n%s", plain) + } +} + +func TestTextPetPickerDrawsThePreview(t *testing.T) { + for _, width := range []int{100, 50} { + m := textPetModel(t) + m.width = width + m.petID = "zero:twig" // the picker opens with Twig selected + updated, debounce := m.handlePetsCommand("") + // Let the real preview load: the debounce, then the preview itself. + updated, load := updated.(model).Update(execCmd(debounce)) + updated, _ = updated.(model).Update(execCmd(load)) + next := updated.(model) + if next.petPreview == nil || next.petPreviewLoading { + t.Fatalf("width %d: preview did not load: preview=%v loading=%v", width, next.petPreview, next.petPreviewLoading) + } + plain := plainRender(t, next.petPickerOverlay(next.width)) + preview, _ := next.petPreview.TextFrame(terminalpet.Idle, next.petPhase, next.petTextColors()) + // Every row of the drawing appears whole, on consecutive lines, all + // starting in the same column. + plainLines := strings.Split(plain, "\n") + first, column := -1, -1 + for index, line := range preview { + want := ansi.Strip(line) + if first < 0 { + for row, candidate := range plainLines { + if at := strings.Index(candidate, want); at >= 0 && strings.TrimSpace(want) != "" { + first, column = row-index, len([]rune(candidate[:at])) + break + } + } + if first < 0 { + continue + } + } + row := []rune(plainLines[first+index]) + if len(row) < column+len([]rune(want)) || string(row[column:column+len([]rune(want))]) != want { + t.Fatalf("width %d: preview row %d %q is not in line with the rest:\n%s", width, index, want, plain) + } + } + if first < 0 { + t.Fatalf("width %d: preview not drawn:\n%s", width, plain) + } + } +} + +func TestPetMoodsFollowTheAgent(t *testing.T) { + thumbnail, _ := terminalpet.ThumbnailAnimation(image.NewNRGBA(image.Rect(0, 0, 12, 12))) + running := func(m model) model { + m.pending = true + m.petOutcome = "" + return m + } + m := running(textPetModel(t)) + if got := m.petState(); got != terminalpet.Thinking { + t.Fatalf("a turn with nothing streaming yet = %s, want thinking", got) + } + m.streamingText = []byte("Here is the plan") + if got := m.petState(); got != terminalpet.Running { + t.Fatalf("a turn writing its answer = %s, want running", got) + } + m.streamingText = []byte(" \n") + if got := m.petState(); got != terminalpet.Thinking { + t.Fatalf("whitespace is not an answer: %s, want thinking", got) + } + m.streamingText = nil + m.streamCallName = "bash" + if got := m.petState(); got != terminalpet.Running { + t.Fatalf("a turn streaming a tool call = %s, want running", got) + } + // A tool that was called and has no result yet is still running. + m.streamCallName = "" + m.activeRunID = 7 + m.transcript = append(m.transcript, transcriptRow{kind: rowToolCall, runID: 7, id: "call-1", tool: "bash"}) + if got := m.petState(); got != terminalpet.Running { + t.Fatalf("a turn running a tool = %s, want running", got) + } + m.transcript = append(m.transcript, transcriptRow{kind: rowToolResult, runID: 7, id: "call-1", tool: "bash"}) + if got := m.petState(); got != terminalpet.Thinking { + t.Fatalf("after the tool finished = %s, want thinking", got) + } + // Pets without a thinking animation keep the running one throughout. + m = running(textPetModel(t)) + m.petAnimation = thumbnail + if got := m.petState(); got != terminalpet.Running { + t.Fatalf("a community pet while thinking = %s, want running", got) + } +} + +func TestPetFallsAsleepWhenIdleAndWakesUp(t *testing.T) { + base := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC) + now := base + m := textPetModel(t) + m.now = func() time.Time { return now } + m.petLastActiveAt = base + now = base.Add(petSleepAfter - time.Second) + if got := m.petState(); got != terminalpet.Idle { + t.Fatalf("just before the timeout = %s, want idle", got) + } + now = base.Add(petSleepAfter) + if got := m.petState(); got != terminalpet.Sleeping { + t.Fatalf("after %s idle = %s, want sleeping", petSleepAfter, got) + } + // Pets without a sleeping animation stay idle. + community := m + community.petAnimation, _ = terminalpet.ThumbnailAnimation(image.NewNRGBA(image.Rect(0, 0, 12, 12))) + if got := community.petState(); got != terminalpet.Idle { + t.Fatalf("a community pet asleep = %s, want idle", got) + } + // A key press wakes it. + updated, _ := m.Update(testKey('a')) + if got := updated.(model).petState(); got != terminalpet.Idle { + t.Fatalf("after a key press = %s, want idle", got) + } + // So does a click on it: the reaction it starts counts as activity. + clicked := m + clicked.petOutcome, clicked.petOutcomeAt = terminalpet.Waving, now + now = now.Add(10 * time.Second) + if got := clicked.petState(); got != terminalpet.Idle { + t.Fatalf("after a click = %s, want idle", got) + } + // A running turn is never asleep. + busy := m + busy.pending = true + if got := busy.petState(); got == terminalpet.Sleeping { + t.Fatal("asleep during a turn") + } +} + +func TestPetCelebratesLongTurnsAndHopsAfterShortOnes(t *testing.T) { + m := newModel(context.Background(), Options{}) + start := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC) + m.turnStartedAt = start + m.turnTimer = newActiveTurnTimer(start) + if got := m.petTurnOutcome(nil, start.Add(petBigTurn)); got != terminalpet.Jumping { + t.Errorf("a %s turn = %s, want jumping", petBigTurn, got) + } + if got := m.petTurnOutcome(nil, start.Add(petBigTurn-time.Second)); got != terminalpet.Review { + t.Errorf("a short turn = %s, want review", got) + } + if got := m.petTurnOutcome(errors.New("boom"), start.Add(2*petBigTurn)); got != terminalpet.Failed { + t.Errorf("a failed long turn = %s, want failed", got) + } + m.turnStartedAt, m.turnTimer = time.Time{}, nil + if got := m.petTurnOutcome(nil, start.Add(time.Hour)); got != terminalpet.Review { + t.Errorf("a turn with no start time = %s, want review", got) + } +} + +func TestFinishedTurnSetsThePetReaction(t *testing.T) { + for _, tc := range []struct { + name string + duration time.Duration + want terminalpet.State + }{ + {"short", 5 * time.Second, terminalpet.Review}, + {"long", 90 * time.Second, terminalpet.Jumping}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("XDG_DATA_HOME", t.TempDir()) + provider := &fakeProvider{events: []zeroruntime.StreamEvent{ + {Type: zeroruntime.StreamEventText, Content: "done"}, + {Type: zeroruntime.StreamEventDone}, + }} + m := newModel(context.Background(), Options{ + Cwd: t.TempDir(), ProviderName: "tokenrouter", ModelName: "MiniMax-M3", + Provider: provider, Registry: tools.NewRegistry(), + }) + base := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC) + current := base + m.now = func() time.Time { return current } + m.input.SetValue("hello") + // The turn starts and runs at base; it finishes tc.duration later. + updated, cmd := m.Update(testKey(tea.KeyEnter)) + finished := execCmd(cmd) + current = base.Add(tc.duration) + updated, _ = updated.(model).Update(finished) + next := updated.(model) + if next.pending { + t.Fatal("the turn did not finish") + } + if next.petOutcome != tc.want { + t.Fatalf("pet reaction = %s, want %s", next.petOutcome, tc.want) + } + if !next.petLastActiveAt.Equal(base.Add(tc.duration)) { + t.Fatalf("petLastActiveAt = %s, want the turn's end", next.petLastActiveAt) + } + }) + } +} + +func TestPetGreetsWhenItAppears(t *testing.T) { + configPath := filepath.Join(t.TempDir(), "config.json") + started := newModel(context.Background(), Options{UserConfigPath: configPath, SavedPet: "zero:merlin"}) + // Look a moment after start, on a fixed clock, so the check cannot race + // the wave's end. + greetedAt := started.petOutcomeAt + started.now = func() time.Time { return greetedAt.Add(time.Second) } + if started.petAnimation == nil || started.petState() != terminalpet.Waving { + t.Fatalf("a saved companion should wave on start: state=%s", started.petState()) + } + if none := newModel(context.Background(), Options{UserConfigPath: configPath}); none.petOutcome != "" { + t.Fatalf("no companion, yet a reaction is set: %s", none.petOutcome) + } + + m := textPetModel(t) + updated, cmd := m.handlePetsCommand("kage") + updated, _ = updated.(model).applyPetInstall(cmd().(petInstalledMsg)) + chosen := updated.(model) + chosenAt := chosen.petOutcomeAt + chosen.now = func() time.Time { return chosenAt.Add(time.Second) } + if got := chosen.petState(); got != terminalpet.Waving { + t.Fatalf("a newly chosen companion = %s, want waving", got) + } +} + +func TestTextPetHidesNoTranscriptOrFooterText(t *testing.T) { + answer := "The last line of the answer runs nearly the width of the screen and ends with a word: lambda." + build := func(withPet bool) model { + m := textPetModel(t) + // Enough conversation to fill the screen, so the answer's last line + // sits at the bottom of the transcript, right above the footer. + for index := 0; index < 30; index++ { + m.transcript = appendTranscriptRow(m.transcript, transcriptRow{kind: rowUser, text: fmt.Sprintf("question %d", index)}) + } + m.transcript = appendTranscriptRow(m.transcript, transcriptRow{kind: rowAssistant, text: answer}) + m.copyStatus = "Copied 12 lines" + if !withPet { + m.petID, m.petAnimation = terminalpet.DisabledID, nil + } + return m + } + plain := plainRender(t, build(true).View().Content) + without := plainRender(t, build(false).View().Content) + for _, want := range []string{"ends with a word: lambda.", "Copied 12 lines"} { + if !strings.Contains(without, want) { + t.Fatalf("test setup: %q is not on screen even without a companion:\n%s", want, without) + } + if !strings.Contains(plain, want) { + t.Fatalf("the text companion hides %q:\n%s", want, plain) + } + } + + // The companion stands only beside footer rows: the footer grows to its + // height, for every caller that measures it, and the transcript ends above. + m := build(true) + footer := m.footerView(chatWidth(m.width)) + if got, want := strings.Count(footer, "\n")+1, terminalpet.TextRows+1; got != want { + t.Fatalf("footer with a docked text companion is %d rows, want %d", got, want) + } + plainFooter := strings.Split(ansi.Strip(footer), "\n") + reserved := m.petComposerReservedColumns(m.width) + for index, line := range plainFooter[:len(plainFooter)-1] { + if width := len([]rune(strings.TrimRight(line, " "))); width > m.width-reserved { + t.Fatalf("footer row %d runs under the companion (%d cells, %d free): %q", index, width, m.width-reserved, line) + } + } + // The status line is below the companion and keeps its full width. + if got := m.footerStatusLine(m.width); lipgloss.Width(got) != lipgloss.Width(m.statusLine(m.width)) || got != m.statusLine(m.width) { + t.Fatalf("status line was shortened beside a text companion: %q", ansi.Strip(got)) + } + plainBuild := build(false) + if got := strings.Count(plainBuild.footerView(chatWidth(plainBuild.width)), "\n") + 1; got >= terminalpet.TextRows+1 { + t.Fatalf("test setup: the footer is %d rows without a companion, so nothing was added", got) + } +} + +func TestTextPetStepsAsideForPermissionPrompts(t *testing.T) { + m := textPetModel(t) + m.pendingPermission = &pendingPermissionPrompt{} + if m.petLayoutActive() { + t.Fatal("a text companion would cover the permission card's options") + } + // Image companions are drawn over the grid by the terminal and keep their + // behaviour. + m.petRenderer = terminalpet.NewImageRenderer(terminalpet.ImageSupport{Protocol: terminalpet.ImageProtocolKitty}) + if !m.petLayoutActive() { + t.Fatal("an image companion should stay beside a permission prompt") + } +} + +func TestTextPetPickerDoesNotStartOnNoCompanion(t *testing.T) { + m := textPetModel(t) + m.petID = "boba" // a community pet, which this picker cannot list + updated, _ := m.handlePetsCommand("") + current, ok := updated.(model).picker.current() + if !ok || current.Value == terminalpet.DisabledID { + t.Fatalf("picker starts on %#v: Enter would switch the pet off", current) + } + m.petID = terminalpet.DisabledID + updated, _ = m.handlePetsCommand("") + if current, _ := updated.(model).picker.current(); current.Value != terminalpet.DisabledID { + t.Fatalf("with no pet, the picker starts on %#v, want No companion", current) + } +} + +func TestTextPetChosenInANarrowWindowSaysWhenItShows(t *testing.T) { + m := textPetModel(t) + m.width = petTextMinWidth - 5 + updated, cmd := m.handlePetsCommand("nova") + updated, _ = updated.(model).applyPetInstall(cmd().(petInstalledMsg)) + next := updated.(model) + if next.petLayoutActive() { + t.Fatal("test setup: the window is wide enough to show the companion") + } + if plain := plainRender(t, next.View().Content); !strings.Contains(plain, fmt.Sprintf("Nova shows once the window is %d+ columns wide.", petTextMinWidth)) { + t.Fatalf("no explanation for the missing companion:\n%s", plain) + } +} + +func TestComposerClicksAndArrowsFollowTheRowsBesideACompanion(t *testing.T) { + m := textPetModel(t) + m.width = 80 + words := make([]string, 0, 50) + for index := 0; index < 50; index++ { + words = append(words, fmt.Sprintf("w%02d", index)) + } + text := strings.Join(words, " ") + m.setComposerState(composerState{text: text, cursor: 0}) + if !m.petLayoutActive() || m.petComposerReservedColumns(m.width) == 0 { + t.Fatal("test setup: no docked companion beside the composer") + } + // The composer must wrap differently with and without the companion's + // columns, or a wrong width would map clicks the same way. + full := composerWrappedVisualLines(m.input, m.currentComposerState(), maxInt(1, m.width-4)) + narrow := composerWrappedVisualLines(m.input, m.currentComposerState(), m.composerInnerWidth(m.width)) + if len(full) == len(narrow) { + t.Fatalf("test setup: %d rows at both widths", len(full)) + } + + lines := strings.Split(plainRender(t, m.View().Content), "\n") + width := m.chatColumnWidth() + frame := m.scrollableTranscriptFrame(m.pinnedTitleBar(width), m.footerView(width)) + // The composer's second text row, below its top border and first row. It + // is drawn from the narrow wrap: it starts where that wrap's second + // segment starts. + row := frame.composerRect.y + 2 + start := narrow[1].start + opening := text[start : start+6] + column := strings.Index(lines[row], opening) + if column < 0 { + t.Fatalf("test setup: composer row %q does not start with %q", lines[row], opening) + } + column = len([]rune(lines[row][:column])) + + // A click on the row's first character puts the cursor there. + position, ok := m.composerPositionAtMouse(testMouseClick(tea.MouseLeft, column, row)) + if !ok || position != start { + t.Fatalf("click on %q at column %d gave cursor %d (%v), want %d", opening, column, position, ok, start) + } + + // Down from the start of the text moves to the start of the drawn second row. + moved, ok := m.moveComposerVisualCursor(1) + if !ok || moved.currentComposerState().cursor != start { + t.Fatalf("Down moved the cursor to %d (%v), want %d, the start of the second row", moved.currentComposerState().cursor, ok, start) + } +}