Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,9 @@ column under the pointer.
The session sidebar works the same way. A click on a card selects that
session, as `^g j` does, so moving from one running agent to another keeps
the keyboard attached. A second click opens it. The wheel over the sidebar
moves the cursor, and over the pane it goes to the agent.
moves the cursor, and over the pane it goes to the agent. An agent that
tracks the mouse, as cathode does with mouse capture on, gets it as a wheel
event. Any other agent gets `↑` and `↓`.

| Command — press `ctrl+g` first | |
|---|---|
Expand Down
23 changes: 21 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ internal/agent PTY + vt emulator per session <- the subtle package
agent.go Runner, Start, Stop
pty.go the two pumps, writes, resize, teardown
render.go the cell walk
mouse.go the agent's mouse modes, and the wheel
status.go working / idle / exited, and how quiet
env.go what a hosted agent must not inherit
headless.go one turn with no pane, and what it cost
Expand All @@ -87,7 +88,8 @@ internal/ui the Bubble Tea program, split by job:
app.go Update, View — the shell
input.go who receives a keystroke
mouse.go where a click or a wheel notch lands;
hittest.go records what each cell stands for
hittest.go records what each cell stands for,
dashmouse.go acts on the dashboard
keyroutes.go where a key goes once modals decline it
keys.go the binding table; ptykeys.go encodes to bytes
selection.go the sidebar's cursor
Expand Down Expand Up @@ -733,6 +735,23 @@ that fits is shown whole. A click selects through `landOn`, as `^g j` does, so
a click from one live agent to another stays attached. The wheel over the
sidebar moves its cursor, and over the pane it still goes to the agent.

The wheel reaches the agent in the form the agent asked for (`Runner.Wheel`).
The emulator reports each mode change through a callback, so the runner knows
when the agent has set a mouse-tracking mode. An agent that has set one gets
a wheel report at the pane cell under the pointer: SGR if the agent also set
mode 1006, X10 if not, including when it asked for another encoding. Any
other agent gets `↑` or `↓`. Sending the key to an agent that tracks the
mouse is wrong: cathode with mouse capture on reads `↑` as its previous
prompt, so the wheel recalled history instead of scrolling until `/mouse`
turned capture off.

`Runner.Wheel` encodes the report itself and writes it to the PTY as a key is
written. The emulator's `SendMouse` would be shorter and is not safe here. It
writes to the reply pipe while holding the emulator lock, so an agent that
stopped reading its input would block it, then the read pump, then every
render. Its X10 encoder also writes a coordinate of 95 or more as two UTF-8
bytes.

The session view is held to the terminal's height for the same reason the
dashboard is. The agent's terminal never drops under five rows (`paneSize`),
and the pane used to be drawn at that height, so a terminal shorter than eight
Expand All @@ -751,7 +770,7 @@ untouched. A corrupt `state.json` fails the launch rather than starting empty,
because starting empty invites duplicate worktrees over sessions we cannot see.
Closing a session leaves its worktree on disk and says where. `model.fault`
holds errors the user must see and is never auto-cleared. Every write into an
agent pane goes through `sendToAgent`, so no keystroke, literal `^g` or wheel
agent pane goes through `toAgent`, so no keystroke, literal `^g` or wheel
notch can drop a failed write.

Reporting is not the same as abandoning. `ui.formProblem` puts a failure *into*
Expand Down
4 changes: 4 additions & 0 deletions internal/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"sync"
"time"

"github.com/charmbracelet/x/ansi"
"github.com/charmbracelet/x/vt"
"github.com/creack/pty"
)
Expand Down Expand Up @@ -74,6 +75,7 @@ type Runner struct {
started time.Time
exited bool
exitErr error
mouse map[ansi.Mode]bool // mouse modes the agent has set; see trackModes
}

// Start launches the agent process attached to a new PTY.
Expand Down Expand Up @@ -114,7 +116,9 @@ func Start(cfg Config) (*Runner, error) {
ptmx: ptmx,
term: term,
started: time.Now(),
mouse: map[ansi.Mode]bool{},
}
r.trackModes()
go r.pump()
go r.respond()
return r, nil
Expand Down
81 changes: 81 additions & 0 deletions internal/agent/mouse.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package agent

// Mouse input to the agent: which mouse reports the agent has asked for, and
// the wheel notches Deck sends it in the form it asked for.

import (
"slices"

"github.com/charmbracelet/x/ansi"
"github.com/charmbracelet/x/vt"
)

// mouseTracking lists the modes in which a terminal reports wheel notches as
// mouse events. They are the modes the emulator's own SendMouse acts on.
var mouseTracking = []ansi.Mode{
ansi.ModeMouseX10,
ansi.ModeMouseNormal,
ansi.ModeMouseHighlight,
ansi.ModeMouseButtonEvent,
ansi.ModeMouseAnyEvent,
}

// x10Limit is the last 0-based cell an X10 report can carry: a coordinate is
// one byte, offset by 33, so 222 is the most that fits in 255.
const x10Limit = 255 - 33

// trackModes keeps r.mouse current from the emulator's mode changes: the
// tracking modes and SGR encoding (?1006). A full reset (RIS) sets every mode
// again through the same path, so the record cannot outlive a reset. It must
// be called before the read pump starts.
func (r *Runner) trackModes() {
set := func(on bool) func(ansi.Mode) {
return func(mode ansi.Mode) {
if mode == ansi.ModeMouseExtSgr || slices.Contains(mouseTracking, mode) {
r.mu.Lock()
r.mouse[mode] = on
r.mu.Unlock()
}
}
}
r.term.SetCallbacks(vt.Callbacks{EnableMode: set(true), DisableMode: set(false)})
}

// Wheel sends one wheel notch at cell (x, y) of the agent's screen.
//
// An agent that asked for mouse reports gets a wheel report, which it reads as
// a scroll. The report is SGR if the agent set ?1006 and X10 otherwise, even
// if it asked for another encoding (?1005, ?1015, ?1016) instead. Any other
// agent gets the ↑ or ↓ key, so a pane with no mouse tracking still moves
// under the wheel. Sending the key to an agent that tracks the mouse is wrong:
// cathode, with mouse capture on, reads ↑ as the previous prompt from its
// history, not as a scroll.
//
// The report is encoded here and written as a key is, not sent through the
// emulator's SendMouse. SendMouse writes to the reply pipe while holding the
// emulator lock, so an agent that stopped reading its input would block it,
// then the read pump, then every Render. Its X10 encoder also writes a
// coordinate of 95 or more as two UTF-8 bytes.
func (r *Runner) Wheel(up bool, x, y int) error {
r.mu.Lock()
tracking, sgr := false, r.mouse[ansi.ModeMouseExtSgr]
for _, t := range mouseTracking {
tracking = tracking || r.mouse[t]
}
r.mu.Unlock()

button, key := ansi.MouseWheelDown, "\x1b[B"
if up {
button, key = ansi.MouseWheelUp, "\x1b[A"
}
b := ansi.EncodeMouseButton(button, false, false, false, false)
switch {
case !tracking:
return r.Write([]byte(key))
case sgr:
return r.Write([]byte(ansi.MouseSgr(b, x, y, false)))
default:
x, y = min(x, x10Limit), min(y, x10Limit)
return r.Write([]byte{0x1b, '[', 'M', b + 32, byte(x + 33), byte(y + 33)})
}
}
79 changes: 79 additions & 0 deletions internal/agent/mouse_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package agent

import (
"fmt"
"strings"
"testing"
"time"
)

// TestWheelUsesTheFormTheAgentAskedFor: an agent that set a mouse-tracking
// mode gets the wheel as a mouse report at the cell given, SGR if it also set
// ?1006 and X10 if not. One that never set it, cleared it, or was reset gets
// the ↑ or ↓ key. cathode with mouse capture on reads ↑ as prompt history, so
// sending it the key would recall an old prompt instead of scrolling.
//
// The script prints the bytes it read as decimals, so the test compares bytes
// rather than what a screen makes of them, and then says whether anything
// followed: a report and a key together would still recall cathode's history.
// It reads with dd, one byte at a time, because BSD head reads ahead and would
// swallow whatever followed in the same write.
func TestWheelUsesTheFormTheAgentAskedFor(t *testing.T) {
const sgr = `\033[?1000h\033[?1006h`
for name, tc := range map[string]struct {
modes string // what the agent prints before it reads
up bool
x, y int
want string
}{
"sgr, up": {sgr, true, 3, 4, "\x1b[<64;4;5M"},
"x10 compatibility": {`\033[?9h\033[?1006h`, true, 3, 4, "\x1b[<64;4;5M"},
"highlight tracking": {`\033[?1001h\033[?1006h`, true, 3, 4, "\x1b[<64;4;5M"},
"button-event": {`\033[?1002h\033[?1006h`, true, 3, 4, "\x1b[<64;4;5M"},
"any-event": {`\033[?1003h\033[?1006h`, true, 3, 4, "\x1b[<64;4;5M"},
"sgr, down": {sgr, false, 3, 4, "\x1b[<65;4;5M"},
"x10": {`\033[?1000h`, true, 3, 4, "\x1b[M`$%"},
"x10 past its range": {`\033[?1000h`, true, 300, 4, "\x1b[M`\xff%"},
"x10 below its range": {`\033[?1000h`, true, 3, 300, "\x1b[M`$\xff"},
"tracking cleared": {sgr + `\033[?1000l`, true, 3, 4, "\x1b[A"},
"reset (RIS)": {sgr + `\033c`, false, 3, 4, "\x1b[B"},
"never on": {``, true, 3, 4, "\x1b[A"},
} {
t.Run(name, func(t *testing.T) {
t.Parallel()
script := fmt.Sprintf(`stty -echo -icanon; printf '%s'; echo READY; `+
`dd bs=1 count=%d 2>/dev/null | od -An -tu1 | tr -s ' \n' ' '; echo END; `+
`if IFS= read -r -t 1 -n 1 rest; then echo EXTRA; else echo CLEAN; fi; sleep 5`,
tc.modes, len(tc.want))
r, err := Start(Config{
Command: "bash",
Args: []string{"--norc", "--noprofile", "-c", script},
Dir: t.TempDir(),
Width: 80,
Height: 24,
})
if err != nil {
t.Fatalf("start: %v", err)
}
defer r.Stop()

if !screenContains(t, r, "READY", 5*time.Second) {
t.Fatal("the script never got ready")
}
if err := r.Wheel(tc.up, tc.x, tc.y); err != nil {
t.Fatalf("wheel: %v", err)
}
var want strings.Builder
for _, b := range []byte(tc.want) {
fmt.Fprintf(&want, " %d", b)
}
want.WriteString(" END")
if !screenContains(t, r, want.String(), 5*time.Second) {
t.Errorf("want%s on screen:\n%s", want.String(), strings.Join(r.Render(false, nil, nil), "\n"))
}
if !screenContains(t, r, "CLEAN", 5*time.Second) {
t.Errorf("the agent got more than the one form:\n%s", strings.Join(r.Render(false, nil, nil), "\n"))
}
})
}
}
102 changes: 102 additions & 0 deletions internal/ui/dashmouse.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package ui

// Mouse on the dashboard: which column and row a press lands on, and what a
// click or a wheel notch does there. mouse.go routes the press here.

import tea "github.com/charmbracelet/bubbletea"

// dashboardMouse acts on a press over the dashboard. Every press is recorded
// in lastPress, a wheel notch and a miss included, and handleKey clears it, so
// only two presses on one row with nothing between them count as a second
// click.
func (m Model) dashboardMouse(msg tea.MouseMsg) (tea.Model, tea.Cmd) {
col, t, ok := m.dashboardHit(msg.X, msg.Y)
again := t == m.lastPress
m.lastPress = target{}
if !ok {
return m, nil
}
switch msg.Button {
case tea.MouseButtonLeft:
m.lastPress = t
return m.click(t, again)
case tea.MouseButtonWheelUp:
m.wheel(col, -1)
case tea.MouseButtonWheelDown:
m.wheel(col, 1)
}
return m, nil
}

// dashboardHit resolves a cell of the dashboard to the column it is in and the
// target it stands for. The target is hitNone on a heading, a blank, a marker
// or a column's top border. ok is false outside both columns: on the header
// and the footer.
func (m Model) dashboardHit(x, y int) (col column, t target, ok bool) {
l := m.dashboardLayout()
row := y - l.top
if row < -columnBorderRows || row >= l.rows || x < 0 || x >= m.width {
return 0, target{}, false
}
if x < l.navW {
lines, rows, _ := m.projectListWindow(l.navW, l.rows)
if row >= 0 && rows[row] >= 0 {
t = lines[rows[row]].at(x)
}
return colProjects, t, true
}
lines := m.detailLines(l.detailW)
if row >= 0 && row < len(lines) {
t = lines[row].at(x - l.navW - detailIndent)
}
return colContent, t, true
}

// click acts on a left click. A click on a row puts the cursor and the focus
// there. A second press in a row on that same row opens it, as ↵ would: the
// first press already put the cursor and the focus on it, and nothing but a
// press or a key can move them in between, and each of those clears or
// replaces lastPress.
//
// Having the cursor is not enough on its own. At launch the first project
// already has the cursor and the focus, and opening it on a first click would
// start an agent from a click meant only to select. No double-click timing is
// involved, so there is none to get wrong.
func (m Model) click(t target, again bool) (tea.Model, tea.Cmd) {
switch t.kind {
case hitProject:
if again {
return m.openFromDashboard()
}
m.focus = colProjects
if m.projectIx != t.index {
m.selectProject(t.index)
}
case hitSession:
if again {
return m.openFromDashboard()
}
m.focus, m.listIx = colContent, t.index
case hitTab:
if m.tabIx != t.index {
m.selectTab(t.index)
}
m.focusContent()
}
return m, nil
}

// wheel moves the cursor in the column under the pointer, as ↑ and ↓ move it in
// the focused one, and focuses that column so the keys then drive the list that
// just moved.
//
// An empty sessions list has nothing to move, so it takes no focus, and says
// nothing either. Unlike a click, a notch is often not aimed, and a notice
// stays in the footer until another replaces it.
func (m *Model) wheel(col column, delta int) {
if col == colContent && !m.hasSessionList() {
return
}
m.focus = col
m.moveDashboard(delta)
}
15 changes: 11 additions & 4 deletions internal/ui/input.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"fmt"

tea "github.com/charmbracelet/bubbletea"

"github.com/tripledownab/deck/internal/agent"
)

func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
Expand Down Expand Up @@ -64,15 +66,20 @@ func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
return m.sessionKey(msg)
}

// sendToAgent writes to the attached agent. Every path that types into the
// pane comes through here, so none of them can drop a failed write: it is
// reported, and the attachment goes with it.
// sendToAgent writes bytes to the attached agent.
func (m *Model) sendToAgent(b []byte) {
m.toAgent(func(r *agent.Runner) error { return r.Write(b) })
}

// toAgent runs send against the attached agent. Every path that sends input
// to the pane comes through here, so none of them can drop a failed write: it
// is reported, and the attachment goes with it.
func (m *Model) toAgent(send func(*agent.Runner) error) {
r := m.currentRunner()
if r == nil || !m.attached {
return
}
if err := r.Write(b); err != nil {
if err := send(r); err != nil {
m.fault = fmt.Errorf("send to agent: %w", err)
m.attached = false
}
Expand Down
Loading
Loading