diff --git a/README.md b/README.md index 9b0ea1d..a8bce6c 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,7 @@ the arrows keep working inside `claude`. | `e` | rename the focused project or session | | `x` | end session — close and keep the worktree, or delete both. In the session view, `x` on a running agent only stops it, and a second `x` ends the session | | `c` | connect this session to one on another project | +| `K` / `J`, or `⇧↑` / `⇧↓` | move the selected session up / down its project's list | | `t` | theme picker | | `?` | help | | `q` | quit | @@ -147,11 +148,18 @@ 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 `↓`. +Sessions keep the order you give them. Drag a session row, in the sidebar or +the dashboard's session list, onto another row of the same project, or use the +keys above. The new order is saved as it changes. A new session still starts at +the top of its project, and a session never moves to another project, because +its worktree belongs to that project's repository. + | Command — press `ctrl+g` first | | |---|---| | `^g d` | dashboard | | `^g s` | sessions | | `^g j` / `^g k` | down / up the session list (stays attached if it is live) | +| `^g K` / `^g J` | move this session up / down its project's list | | `^g` and a number | jump straight to that session | | `^g n` | new session | | `^g e` | rename this session | diff --git a/docs/architecture.md b/docs/architecture.md index e9fffca..65d808e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -773,10 +773,11 @@ A click on a project or a session puts the cursor and the focus there. A second press in a row on that same row, with no key between, opens it, as `↵` does. Having the cursor is not enough on its own: at launch the first project already has it, and opening on a first click would start an agent from a click meant to -select. No double-click timing is involved. Only presses act — a drag and a release are -events of their own — and a press cancels an armed `^g`. A modal takes no mouse -input at all, because it replaces the frame, and a click would act on rows the -user cannot see. +select. No double-click timing is involved. Presses act, and a press cancels an +armed `^g`. Motion and a release act only to carry a drag that a press on a +session row started — see **Sessions keep the order they are given** — so they +never count as clicks. A modal takes no mouse input at all, because it replaces +the frame, and a click would act on rows the user cannot see. The session sidebar is built the same way (`sidebarLines`, `hitRow`) and follows the same rules. `Model.sidebarTop` keeps it still between frames, as @@ -813,6 +814,28 @@ The tests aim at the rendered frame: `cellOf` finds a label in the frame as the terminal shows it and clicks that cell. A click placed with the hit map's own arithmetic would test the hit map against itself. +### Sessions keep the order they are given (`store.MoveSession`, `ui/reorder.go`) + +Each session holds an `Order`, lowest first. A new one takes its negated +creation time (`orderFor`), which is below the value of every session created +before it by the clock, so it lands at the top as newest-first always did. A +move only reassigns the values a project's sessions already hold, in their new +sequence, so a later session still sorts above all of them. A clock set back +breaks that: the new session then sorts below the ones it is older than by the +clock. A file written before `Order` existed is filled in from the same rule on +`Load`, which opens it in the order it was shown in. A Deck binary older than +`Order` drops the field when it saves, and the arrangement with it. + +The keys and the drag both go through `moveSession`, which saves and puts both +cursors back on the sessions they were on rather than on the row index they +held: the session under an index changes when the order does. A drag starts on +a press over a session row, follows motion with the left button held, and is +saved at every step rather than at the release, because a button let go +outside the window may send no release. Any press or key ends it. Once the +session has moved, the starting press stops counting toward a double click, +because the row it was recorded against now holds another session. A drop lands +only on a session of the same project. + ### Failures are reported, never absorbed A failed worktree is never quietly downgraded to running in the project diff --git a/internal/store/query.go b/internal/store/query.go index 2480401..2240449 100644 --- a/internal/store/query.go +++ b/internal/store/query.go @@ -3,6 +3,7 @@ package store // Reading and mutating the loaded document. import ( + "slices" "sort" "time" ) @@ -41,6 +42,19 @@ type Session struct { Isolated bool `json:"isolated"` Agent string `json:"agent"` CreatedAt time.Time `json:"created_at"` + // Order places the session in its project's list, lowest first. A new + // session takes its negated creation time (orderFor), which is below the + // value of every session created before it by the clock, so it lands first + // as newest-first always did. Moving one only permutes the values a + // project's sessions already hold, raising equal ones apart. + Order int64 `json:"order,omitempty"` +} + +// orderFor is the Order a session starts with. Zero is "not set", which is +// what a state file written before Order existed holds, and Load fills it in +// from the same rule, so such a file keeps the order it was shown in. +func orderFor(created time.Time) int64 { + return -created.UnixNano() } // Project returns the project with the given id, or nil. @@ -73,7 +87,8 @@ func (s *State) ProjectByPath(path string) *Project { return nil } -// SessionsFor returns a project's sessions, newest first. +// SessionsFor returns a project's sessions in their Order: as the user +// arranged them, with any session opened since at the top. func (s *State) SessionsFor(projectID string) []Session { var out []Session for _, sess := range s.Sessions { @@ -81,10 +96,45 @@ func (s *State) SessionsFor(projectID string) []Session { out = append(out, sess) } } - sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt.After(out[j].CreatedAt) }) + sort.SliceStable(out, func(i, j int) bool { return out[i].Order < out[j].Order }) return out } +// MoveSession puts a session at position to in its project's list, clamped +// to the list, and reports whether its position changed. +// +// The values the project's sessions hold are reassigned in their new order +// rather than recomputed, so a session opened later by the clock still takes +// a value below all of them. Equal values — a hand-edited file with no creation times — are +// raised to be distinct first, upwards only for the same reason; reassigning +// equal values would move nothing and still report a move. +func (s *State) MoveSession(id string, to int) bool { + sess := s.Session(id) + if sess == nil { + return false + } + list := s.SessionsFor(sess.ProjectID) + from := slices.IndexFunc(list, func(x Session) bool { return x.ID == id }) + to = max(0, min(to, len(list)-1)) + if from == to { + return false + } + orders := make([]int64, len(list)) + for i := range list { + orders[i] = list[i].Order + if i > 0 && orders[i] <= orders[i-1] { + orders[i] = orders[i-1] + 1 + } + } + moved := list[from] + list = slices.Delete(list, from, from+1) + list = slices.Insert(list, to, moved) + for i := range list { + s.Session(list[i].ID).Order = orders[i] + } + return true +} + // AddProject appends a project and returns it. func (s *State) AddProject(p Project) *Project { if p.ID == "" { @@ -105,6 +155,9 @@ func (s *State) AddSession(sess Session) *Session { if sess.CreatedAt.IsZero() { sess.CreatedAt = time.Now() } + if sess.Order == 0 { + sess.Order = orderFor(sess.CreatedAt) + } s.Sessions = append(s.Sessions, sess) return &s.Sessions[len(s.Sessions)-1] } diff --git a/internal/store/store.go b/internal/store/store.go index eb5ee77..7055156 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -45,10 +45,15 @@ func Load() (*State, error) { // Sessions recorded before Agent existed name no program. Filling them in // here, once, is what lets every reader treat the field as always set // instead of guessing at the point of use. + // + // Order is filled in the same way, for the same reason. for i := range s.Sessions { if s.Sessions[i].Agent == "" { s.Sessions[i].Agent = DefaultAgent } + if s.Sessions[i].Order == 0 { + s.Sessions[i].Order = orderFor(s.Sessions[i].CreatedAt) + } } return &s, nil } diff --git a/internal/store/store_test.go b/internal/store/store_test.go index 445b933..0e106a3 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "path/filepath" + "strings" "testing" "time" ) @@ -104,3 +105,109 @@ func TestSessionsForIsNewestFirst(t *testing.T) { t.Errorf("first session = %q, want newer", got[0].Name) } } + +// names lists a project's sessions by name, in the order SessionsFor gives. +func names(s *State, projectID string) string { + var out []string + for _, sess := range s.SessionsFor(projectID) { + out = append(out, sess.Name) + } + return strings.Join(out, ",") +} + +// TestMoveSessionReorders covers a move in each direction, one that changes +// nothing, and one past the end, which clamps rather than refusing. +func TestMoveSessionReorders(t *testing.T) { + s := &State{} + p := s.AddProject(Project{Name: "demo", Path: "/demo"}) + now := time.Now() + for i, name := range []string{"a", "b", "c"} { + s.AddSession(Session{ProjectID: p.ID, Name: name, CreatedAt: now.Add(-time.Duration(i) * time.Minute)}) + } + other := s.AddSession(Session{ProjectID: "other", Name: "elsewhere", CreatedAt: now}) + id := func(name string) string { return s.SessionsFor(p.ID)[strings.Index("abc", name)].ID } + c, a := id("c"), id("a") + + if !s.MoveSession(c, 0) || names(s, p.ID) != "c,a,b" { + t.Errorf("moving c to the top gave %s", names(s, p.ID)) + } + if s.MoveSession(c, 0) { + t.Error("a move to where the session already is reported a move") + } + if !s.MoveSession(a, 99) || names(s, p.ID) != "c,b,a" { + t.Errorf("moving a past the end gave %s, want it clamped to the bottom", names(s, p.ID)) + } + if got := s.Session(other.ID).Order; got != orderFor(now) { + t.Errorf("a session of another project changed order: %d", got) + } +} + +// TestANewSessionLandsFirstAfterAMove keeps the newest-first rule once the +// user has arranged the list: a move only permutes the values given out. +func TestANewSessionLandsFirstAfterAMove(t *testing.T) { + s := &State{} + p := s.AddProject(Project{Name: "demo", Path: "/demo"}) + old := time.Now().Add(-time.Hour) + s.AddSession(Session{ProjectID: p.ID, Name: "a", CreatedAt: old}) + b := s.AddSession(Session{ProjectID: p.ID, Name: "b", CreatedAt: old.Add(-time.Minute)}) + s.MoveSession(b.ID, 0) + + s.AddSession(Session{ProjectID: p.ID, Name: "new"}) + if got := names(s, p.ID); got != "new,b,a" { + t.Errorf("order = %s, want the new session first and the move kept", got) + } +} + +// TestMoveSessionWithEqualOrders is a hand-edited file whose sessions share a +// value. Reassigning equal values would move nothing and still say it moved. +func TestMoveSessionWithEqualOrders(t *testing.T) { + s := &State{Sessions: []Session{ + {ID: "1", ProjectID: "p", Name: "a", Order: 5}, + {ID: "2", ProjectID: "p", Name: "b", Order: 5}, + }} + if !s.MoveSession("2", 0) || names(s, "p") != "b,a" { + t.Errorf("order = %s, want b moved first", names(s, "p")) + } +} + +// TestLoadKeepsTheOrderOfAnOlderFile: a file written before Order existed +// opens newest first, as it always did, and a move then survives a reload. +func TestLoadKeepsTheOrderOfAnOlderFile(t *testing.T) { + t.Setenv("XDG_STATE_HOME", t.TempDir()) + dir, err := Dir() + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + old := `{"projects":[{"id":"p","name":"demo","path":"/demo"}],"sessions":[ + {"id":"1","project_id":"p","name":"older","created_at":"2026-01-01T10:00:00Z"}, + {"id":"2","project_id":"p","name":"newer","created_at":"2026-01-02T10:00:00Z"}]}` + path, err := statePath() + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(old), 0o600); err != nil { + t.Fatal(err) + } + + s, err := Load() + if err != nil { + t.Fatal(err) + } + if got := names(s, "p"); got != "newer,older" { + t.Fatalf("an older file opened as %s, want newest first", got) + } + s.MoveSession("1", 0) + if err := s.Save(); err != nil { + t.Fatal(err) + } + again, err := Load() + if err != nil { + t.Fatal(err) + } + if got := names(again, "p"); got != "older,newer" { + t.Errorf("after a move and a reload the order is %s, want older,newer", got) + } +} diff --git a/internal/ui/chrome.go b/internal/ui/chrome.go index b8b5570..04d0299 100644 --- a/internal/ui/chrome.go +++ b/internal/ui/chrome.go @@ -93,7 +93,7 @@ func (m Model) commandHint() string { return truncateStyled(line, m.width) } pairs := [][2]string{ - {"d", "dashboard"}, {"j/k", "switch"}, {"1…", "jump"}, {"n", "new"}, {"e", "rename"}, + {"d", "dashboard"}, {"j/k", "switch"}, {"K/J", "move"}, {"1…", "jump"}, {"n", "new"}, {"e", "rename"}, {"x", "stop/end"}, {"↵", "attach"}, {"esc", "detach"}, {"?", "help"}, {"q", "quit"}, {"^g", "literal"}, } diff --git a/internal/ui/dashmouse.go b/internal/ui/dashmouse.go index ed7fd68..98413ed 100644 --- a/internal/ui/dashmouse.go +++ b/internal/ui/dashmouse.go @@ -77,6 +77,9 @@ func (m Model) click(t target, again bool) (tea.Model, tea.Cmd) { return m.openFromDashboard() } m.focus, m.listIx = colContent, t.index + if sess := m.dashboardSession(); sess != nil { + m.dragging = sess.ID + } case hitTab: if m.tabIx != t.index { m.selectTab(t.index) diff --git a/internal/ui/input.go b/internal/ui/input.go index e410729..aec29eb 100644 --- a/internal/ui/input.go +++ b/internal/ui/input.go @@ -13,8 +13,10 @@ import ( ) func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { - // A key between two clicks makes them two first clicks, not a pair. - m.lastPress = target{} + // A key between two clicks makes them two first clicks, not a pair. It + // ends a drag too: a key can open a modal, end the session being dragged or + // change screens, and the rows the drag was moving between may be gone. + m.lastPress, m.dragging = target{}, "" // A modal owns every key while it is up. if m.picker != nil { @@ -114,6 +116,10 @@ func (m Model) command(msg tea.KeyMsg) (tea.Model, tea.Cmd) { m.moveRow(-1) case "x": return m.stopOrEnd() + case "K", "shift+up": + return m.moveSelected(-1) + case "J", "shift+down": + return m.moveSelected(1) case "esc", " ": m.attached = false case "enter", "i": diff --git a/internal/ui/keyroutes.go b/internal/ui/keyroutes.go index 638e91c..32ec2d2 100644 --- a/internal/ui/keyroutes.go +++ b/internal/ui/keyroutes.go @@ -40,6 +40,10 @@ func (m Model) dashboardKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { return m.openThemePicker() case key.Matches(msg, m.keys.Delete): return m.endSelectedFromDashboard() + case key.Matches(msg, m.keys.MoveUp): + return m.moveSelected(-1) + case key.Matches(msg, m.keys.MoveDown): + return m.moveSelected(1) case key.Matches(msg, m.keys.Enter): return m.openFromDashboard() } @@ -64,6 +68,10 @@ func (m Model) sessionKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { return m.openSessionRename() case key.Matches(msg, m.keys.Delete): return m.stopOrEnd() + case key.Matches(msg, m.keys.MoveUp): + return m.moveSelected(-1) + case key.Matches(msg, m.keys.MoveDown): + return m.moveSelected(1) case key.Matches(msg, m.keys.Connect): return m.openConnectPicker(m.currentSession()) case key.Matches(msg, m.keys.Theme): diff --git a/internal/ui/keys.go b/internal/ui/keys.go index c117cf1..7fa8b06 100644 --- a/internal/ui/keys.go +++ b/internal/ui/keys.go @@ -34,6 +34,8 @@ type keyMap struct { Delete key.Binding Connect key.Binding Theme key.Binding + MoveUp key.Binding + MoveDown key.Binding // Command mode, reached through the prefix. Dashboard key.Binding @@ -45,6 +47,7 @@ type keyMap struct { HelpCmd key.Binding QuitCmd key.Binding NextSess key.Binding + MoveSessCmd key.Binding JumpSess key.Binding Attach key.Binding Detach key.Binding @@ -68,6 +71,8 @@ func defaultKeys() keyMap { Delete: key.NewBinding(key.WithKeys("x"), key.WithHelp("x", "end session")), Connect: key.NewBinding(key.WithKeys("c"), key.WithHelp("c", "connect to a session elsewhere")), Theme: key.NewBinding(key.WithKeys("t"), key.WithHelp("t", "theme")), + MoveUp: key.NewBinding(key.WithKeys("shift+up", "K"), key.WithHelp("⇧↑/K", "move the session up its project's list")), + MoveDown: key.NewBinding(key.WithKeys("shift+down", "J"), key.WithHelp("⇧↓/J", "move the session down its project's list")), Dashboard: key.NewBinding(key.WithKeys("d"), key.WithHelp("^g d", "dashboard")), Sessions: key.NewBinding(key.WithKeys("s"), key.WithHelp("^g s", "sessions")), @@ -78,6 +83,8 @@ func defaultKeys() keyMap { HelpCmd: key.NewBinding(key.WithKeys("?"), key.WithHelp("^g ?", "this help")), QuitCmd: key.NewBinding(key.WithKeys("q"), key.WithHelp("^g q", "quit")), NextSess: key.NewBinding(key.WithKeys("j", "down"), key.WithHelp("^g j/k", "down / up the session list")), + MoveSessCmd: key.NewBinding(key.WithKeys("K", "J", "shift+up", "shift+down"), + key.WithHelp("^g K/J", "move this session up / down its project's list")), JumpSess: key.NewBinding( key.WithKeys("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"), key.WithHelp("^g 1…", "jump to that session")), @@ -109,10 +116,11 @@ func (k keyMap) helpGroups() []helpGroup { return []helpGroup{ {"CHROME", []key.Binding{ k.Up, k.Down, k.Left, k.Right, k.SwitchCol, k.Enter, - k.NewSession, k.AddProject, k.Rename, k.Delete, k.Connect, k.Theme, k.Help, k.Quit, + k.NewSession, k.AddProject, k.Rename, k.Delete, k.Connect, k.MoveUp, k.MoveDown, + k.Theme, k.Help, k.Quit, }}, {"COMMAND — press " + PrefixKey + " first", []key.Binding{ - k.Dashboard, k.Sessions, k.NextSess, k.JumpSess, k.NewSessCmd, k.RenameCmd, k.StopSessCmd, + k.Dashboard, k.Sessions, k.NextSess, k.MoveSessCmd, k.JumpSess, k.NewSessCmd, k.RenameCmd, k.StopSessCmd, k.Detach, k.Attach, k.ThemeCmd, k.HelpCmd, k.QuitCmd, }}, } diff --git a/internal/ui/model.go b/internal/ui/model.go index dbcd082..a0021f6 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -45,6 +45,9 @@ type Model struct { // lastPress is what the previous mouse press landed on, cleared by any key. // A click opens a row only when the press before it landed on that row. lastPress target + // dragging is the id of the session a held left button is moving, or "" + // when no drag is in progress. See dragMouse. + dragging string // Session view. rows []sidebarRow diff --git a/internal/ui/mouse.go b/internal/ui/mouse.go index 48be77f..d4c5c6f 100644 --- a/internal/ui/mouse.go +++ b/internal/ui/mouse.go @@ -14,9 +14,11 @@ import ( // handleMouse routes a mouse event. // -// Only presses act. A drag and a release arrive as events of their own, and -// acting on them too would take one click as two. A wheel notch arrives as a -// press. +// Presses act, and a wheel notch arrives as one. Motion and a release act only +// to carry a drag that a press on a session row started (dragMouse), and then +// only to move that session: acting on them otherwise would take one click as +// two. Any press or key ends a drag, so one whose release never arrived — the +// button let go outside the window — cannot outlive the next click. // // A press cancels an armed prefix, and any number pending behind it. The // prefix arms the next key, and a click that left it armed would hand whatever @@ -27,8 +29,9 @@ import ( // not showing. func (m Model) handleMouse(msg tea.MouseMsg) (tea.Model, tea.Cmd) { if msg.Action != tea.MouseActionPress { - return m, nil + return m.dragMouse(msg), nil } + m.dragging = "" m.armed, m.jumpDigits = false, 0 if m.picker != nil || m.browser != nil || m.form != nil || m.showHelp { return m, nil @@ -64,6 +67,7 @@ func (m Model) sessionMouse(msg tea.MouseMsg) (tea.Model, tea.Cmd) { return m.attach() } m.landOn(t.index) + m.dragging = m.rows[t.index].session.ID case tea.MouseButtonWheelUp: m.moveRow(-1) case tea.MouseButtonWheelDown: diff --git a/internal/ui/reorder.go b/internal/ui/reorder.go new file mode 100644 index 0000000..06e6f86 --- /dev/null +++ b/internal/ui/reorder.go @@ -0,0 +1,145 @@ +package ui + +// Reordering sessions within their project: the keys that move the selected +// one a step, and dragging one with the mouse. The order itself is the store's +// (store.State.MoveSession); this file decides which session moves where, +// saves, and keeps the cursors on the sessions they were on. + +import ( + "slices" + + tea "github.com/charmbracelet/bubbletea" + "github.com/tripledownab/deck/internal/store" +) + +// moveSelected is K and J, and shift+↑ and shift+↓: it moves the selected +// session one step within its project. On the dashboard that is the session +// under the list's cursor, and in the session view the sidebar's. +func (m Model) moveSelected(delta int) (tea.Model, tea.Cmd) { + var sess *store.Session + if m.screen == screenDashboard { + sess = m.focusedSession() + } else { + sess = m.currentSession() + } + if sess == nil { + return m, nil + } + name := sess.Name + if !m.moveSession(sess.ID, positionOf(m.state, sess.ID)+delta) { + end := "top" + if delta > 0 { + end = "bottom" + } + m.notice = name + " is already at the " + end + " of " + projectLabel(m.state, sess.ProjectID) + } + return m, nil +} + +// moveSession puts a session at position to in its project's list, saves, and +// reports whether it moved. +// +// Both cursors stay on the sessions they were on, rather than on the row index +// they held: the rows under an index change when the order does, and a cursor +// that stayed put would now select a different session. +// +// A failed save is reported and the move stays on screen. The list in front of +// the user is the one in memory, and the next save writes it. +func (m *Model) moveSession(id string, to int) bool { + onRow, onList := idOf(m.currentSession()), idOf(m.dashboardSession()) + if !m.state.MoveSession(id, to) { + return false + } + if err := m.state.Save(); err != nil { + m.fault = err + } + m.rebuildRows() + if i := slices.IndexFunc(m.rows, func(r sidebarRow) bool { + return r.session != nil && r.session.ID == onRow + }); i >= 0 { + m.rowIx = i + } + if onList != "" { + m.listIx = positionOf(m.state, onList) + } + return true +} + +// dragMouse carries a drag that a press on a session row started. Motion with +// the left button held moves the session to the row under the pointer, if that +// row is in the same project; a release ends the drag. +// +// Every step is saved as it happens rather than once at the release, because +// a release is not guaranteed to arrive: a button let go outside the window +// may send none. Any key or press ends a drag (handleKey, handleMouse), so +// nothing that changes the rows on screen leaves one running. +// +// The press that started the drag no longer counts toward a double click once +// the session moves. It was recorded against a row index, and that index now +// holds another session, which a second press would otherwise open. +func (m Model) dragMouse(msg tea.MouseMsg) Model { + if m.dragging == "" { + return m + } + if msg.Action == tea.MouseActionRelease { + m.dragging = "" + return m + } + if msg.Action != tea.MouseActionMotion || msg.Button != tea.MouseButtonLeft { + return m + } + if to, ok := m.dropTarget(msg.X, msg.Y); ok && m.moveSession(m.dragging, to) { + m.lastPress = target{} + } + return m +} + +// dropTarget is the position in the dragged session's project list that the +// cell at x, y stands for. ok is false over anything but a session of that +// project: a session never moves between projects, because its worktree +// belongs to the repository it was opened in. +// +// The dragged session can be gone: a key that ends it also ends the drag, but +// the store is the authority on whether it still exists, so it is asked. +func (m Model) dropTarget(x, y int) (to int, ok bool) { + sess := m.state.Session(m.dragging) + if sess == nil { + return 0, false + } + if m.screen == screenSession { + t, over := m.sidebarHit(x, y) + if !over || t.kind != hitRow { + return 0, false + } + under := m.rows[t.index].session + if under == nil || under.ProjectID != sess.ProjectID { + return 0, false + } + return positionOf(m.state, under.ID), true + } + _, t, hit := m.dashboardHit(x, y) + p := m.currentProject() + if !hit || t.kind != hitSession || p == nil || p.ID != sess.ProjectID { + return 0, false + } + return t.index, true +} + +// positionOf is a session's index in its project's list, or -1. +func positionOf(state *store.State, id string) int { + sess := state.Session(id) + if sess == nil { + return -1 + } + return slices.IndexFunc(state.SessionsFor(sess.ProjectID), func(s store.Session) bool { + return s.ID == id + }) +} + +// idOf is a session's id, or "" for none. +func idOf(sess *store.Session) string { + if sess == nil { + return "" + } + return sess.ID +} diff --git a/internal/ui/reorder_test.go b/internal/ui/reorder_test.go new file mode 100644 index 0000000..993c175 --- /dev/null +++ b/internal/ui/reorder_test.go @@ -0,0 +1,306 @@ +package ui + +// Moving a session within its project, by key and by dragging it, aimed at the +// frame as drawn like the other mouse tests. + +import ( + "os" + "path/filepath" + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" + "github.com/tripledownab/deck/internal/store" +) + +// titles lists the first project's sessions by title, in list order. +func titles(m Model) string { + var out []string + for _, s := range m.state.SessionsFor(m.state.Projects[0].ID) { + out = append(out, s.Title) + } + return strings.Join(out, ",") +} + +func motion(m Model, x, y int) Model { + next, _ := m.Update(tea.MouseMsg{X: x, Y: y, Button: tea.MouseButtonLeft, Action: tea.MouseActionMotion}) + return next.(Model) +} + +func release(m Model, x, y int) Model { + next, _ := m.Update(tea.MouseMsg{X: x, Y: y, Button: tea.MouseButtonNone, Action: tea.MouseActionRelease}) + return next.(Model) +} + +func sendKey(m Model, msg tea.KeyMsg) Model { + next, _ := m.Update(msg) + return next.(Model) +} + +// TestKeysMoveTheFocusedSessionOnTheDashboard: both spellings of each +// direction, the cursor staying on the session it moved, the order surviving +// a reload, and the end of the list saying so instead of doing nothing. +func TestKeysMoveTheFocusedSessionOnTheDashboard(t *testing.T) { + t.Setenv("XDG_STATE_HOME", t.TempDir()) + m := sized(New(mouseState(1, 3), "bash", nil), 120, 30) + m.focusContent() + + m = sendKey(m, typed("J")) + if got := titles(m); got != "title-01,title-00,title-02" { + t.Fatalf("J gave %s", got) + } + m = sendKey(m, tea.KeyMsg{Type: tea.KeyShiftDown}) + if got := titles(m); got != "title-01,title-02,title-00" { + t.Fatalf("shift+down gave %s", got) + } + if s := m.dashboardSession(); s == nil || s.Title != "title-00" { + t.Errorf("the cursor is on %v, want it to follow title-00", s) + } + saved, err := store.Load() + if err != nil { + t.Fatal(err) + } + if got := titles(Model{state: saved}); got != "title-01,title-02,title-00" { + t.Errorf("the saved order is %s", got) + } + + m = sendKey(m, typed("J")) + if !strings.Contains(m.notice, "bottom") { + t.Errorf("J at the bottom said %q", m.notice) + } + m = sendKey(m, tea.KeyMsg{Type: tea.KeyShiftUp}) + m = sendKey(m, typed("K")) + if got := titles(m); got != "title-00,title-01,title-02" { + t.Errorf("shift+up then K gave %s", got) + } + m = sendKey(m, typed("K")) + if !strings.Contains(m.notice, "top") { + t.Errorf("K at the top said %q", m.notice) + } +} + +// TestTheSidebarDrawsTheNewOrder reads the order off the frame. The store's +// order and the cursor can both be right while the sidebar still draws the +// rows it built before the move. +func TestTheSidebarDrawsTheNewOrder(t *testing.T) { + t.Setenv("XDG_STATE_HOME", t.TempDir()) + m := sessionView(t, 3, 120, 30) + sidebarW, _ := m.layout() + + m = sendKey(m, typed("J")) + _, y0 := cellOf(t, m, "title-00", 0, sidebarW) + _, y1 := cellOf(t, m, "title-01", 0, sidebarW) + if y1 >= y0 { + t.Errorf("after J, title-00 is drawn on line %d and title-01 on %d; want title-01 above", y0, y1) + } +} + +// TestAFailedSaveIsReportedAndTheMoveKept: the list on screen is the one in +// memory, so a move whose save failed stays, and says why it is not on disk. +func TestAFailedSaveIsReportedAndTheMoveKept(t *testing.T) { + blocker := filepath.Join(t.TempDir(), "not-a-dir") + if err := os.WriteFile(blocker, nil, 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("XDG_STATE_HOME", blocker) + m := sized(New(mouseState(1, 2), "bash", nil), 120, 30) + m.focusContent() + + m = sendKey(m, typed("J")) + if m.fault == nil { + t.Error("a failed save said nothing") + } + if got := titles(m); got != "title-01,title-00" { + t.Errorf("the move was undone by its failed save: %s", got) + } +} + +// TestEndingTheDraggedSessionEndsTheDrag holds the button on a card and ends +// that session from the keyboard. Motion after it must find nothing to move, +// not a session that is no longer in the store. +func TestEndingTheDraggedSessionEndsTheDrag(t *testing.T) { + t.Setenv("XDG_STATE_HOME", t.TempDir()) + m := sessionView(t, 3, 120, 30) + sidebarW, _ := m.layout() + fromX, fromY := cellOf(t, m, "title-00", 0, sidebarW) + toX, toY := cellOf(t, m, "title-02", 0, sidebarW) + + m = press(m, tea.MouseButtonLeft, fromX, fromY) + m = sendKey(m, typed("x")) // not isolated: closes outright, no modal + if len(m.state.Sessions) != 2 { + t.Fatalf("x did not end the session; %d remain", len(m.state.Sessions)) + } + m = motion(m, toX, toY) + if m.dragging != "" { + t.Error("a drag outlived the session it was moving") + } + + // The store is still asked, for a drag whose session went another way. + // Aimed afresh: the close moved every card below the one it ended. + toX, toY = cellOf(t, m, "title-02", 0, sidebarW) + m.dragging = "gone" + if got := titles(motion(m, toX, toY)); got != "title-01,title-02" { + t.Errorf("motion for a session no longer in the store gave %s", got) + } +} + +// TestKeysMoveTheSidebarSession covers the session view, detached with the bare +// key and attached through the prefix, where the bare key would go to the agent. +func TestKeysMoveTheSidebarSession(t *testing.T) { + t.Setenv("XDG_STATE_HOME", t.TempDir()) + m := sessionView(t, 3, 120, 30) + + m = sendKey(m, typed("J")) + if got := titles(m); got != "title-01,title-00,title-02" { + t.Fatalf("J gave %s", got) + } + if s := m.currentSession(); s == nil || s.Title != "title-00" { + t.Errorf("the sidebar cursor is on %v, want it to follow title-00", s) + } + m.attached = true + m = sendKey(m, tea.KeyMsg{Type: tea.KeyCtrlG}) + m = sendKey(m, typed("J")) + if got := titles(m); got != "title-01,title-02,title-00" { + t.Errorf("^g J gave %s", got) + } +} + +// TestDragMovesASidebarSession presses a card, drags it over another, and +// lets go. The press that started it must not then pair with the next press: +// it was made on a row that now holds another session. +func TestDragMovesASidebarSession(t *testing.T) { + t.Setenv("XDG_STATE_HOME", t.TempDir()) + m := sessionView(t, 4, 120, 30) + sidebarW, _ := m.layout() + fromX, fromY := cellOf(t, m, "title-00", 0, sidebarW) + toX, toY := cellOf(t, m, "title-02", 0, sidebarW) + + m = press(m, tea.MouseButtonLeft, fromX, fromY) + m = motion(m, toX, toY) + if got := titles(m); got != "title-01,title-02,title-00,title-03" { + t.Fatalf("dragging title-00 onto title-02 gave %s", got) + } + m = release(m, toX, toY) + if m.dragging != "" { + t.Error("the release did not end the drag") + } + + m = press(m, tea.MouseButtonLeft, fromX, fromY) + if m.attached || len(m.runners) != 0 { + t.Error("the press after a drag paired with the one that started it and opened a session") + } +} + +// TestDragMovesADashboardSession is the same in the dashboard's session list. +func TestDragMovesADashboardSession(t *testing.T) { + t.Setenv("XDG_STATE_HOME", t.TempDir()) + m := sized(New(mouseState(1, 4), "bash", nil), 120, 30) + navW := m.dashboardLayout().navW + fromX, fromY := cellOf(t, m, "title-03", navW, m.width) + toX, toY := cellOf(t, m, "title-00", navW, m.width) + + m = press(m, tea.MouseButtonLeft, fromX, fromY) + m = motion(m, toX, toY) + if got := titles(m); got != "title-03,title-00,title-01,title-02" { + t.Fatalf("dragging title-03 onto title-00 gave %s", got) + } + if s := m.dashboardSession(); s == nil || s.Title != "title-03" { + t.Errorf("the cursor is on %v, want it on the dragged session", s) + } +} + +// TestDragOnlyMovesWithinAProjectAndAPress: a session never moves to another +// project, motion with no press behind it moves nothing, and neither does +// motion after the release or after a key, here one that opens a modal. +func TestDragOnlyMovesWithinAProjectAndAPress(t *testing.T) { + t.Setenv("XDG_STATE_HOME", t.TempDir()) + st := mouseState(2, 3) + st.AddSession(store.Session{ProjectID: st.Projects[1].ID, Name: "name-other", + Title: "other-title", Agent: "bash", Dir: t.TempDir()}) + for i := range st.Sessions { + st.Sessions[i].Dir = t.TempDir() + } + m := New(st, "bash", nil) + m.screen = screenSession + m = sized(m, 120, 30) + t.Cleanup(func() { m.Close() }) + sidebarW, _ := m.layout() + // From the bottom of its list, so a drop wrongly taken as "the other + // project's first row" would move it to the top and show. + fromX, fromY := cellOf(t, m, "title-02", 0, sidebarW) + otherX, otherY := cellOf(t, m, "other-title", 0, sidebarW) + toX, toY := cellOf(t, m, "title-00", 0, sidebarW) + want := titles(m) + + if got := titles(motion(m, toX, toY)); got != want { + t.Errorf("motion with no press moved the list to %s", got) + } + m = press(m, tea.MouseButtonLeft, fromX, fromY) + if got := titles(motion(m, otherX, otherY)); got != want { + t.Errorf("dragging onto another project's session gave %s", got) + } + if got := titles(motion(release(m, fromX, fromY), toX, toY)); got != want { + t.Errorf("motion after the release moved the list to %s", got) + } + helped := sendKey(m, typed("?")) + if !helped.showHelp { + t.Fatal("? did not open the help; the check below proves nothing") + } + if got := titles(motion(helped, toX, toY)); got != want { + t.Errorf("motion after a key opened a modal moved the list to %s", got) + } +} + +// TestAPressEndsADragWhoseReleaseNeverCame: a button let go outside the window +// sends no release, so the next press has to end the drag, or motion from a +// later click elsewhere would still drag the old session. +func TestAPressEndsADragWhoseReleaseNeverCame(t *testing.T) { + t.Setenv("XDG_STATE_HOME", t.TempDir()) + m := sessionView(t, 3, 120, 30) + sidebarW, _ := m.layout() + fromX, fromY := cellOf(t, m, "title-00", 0, sidebarW) + toX, toY := cellOf(t, m, "title-02", 0, sidebarW) + want := titles(m) + + m = press(m, tea.MouseButtonLeft, fromX, fromY) + m = press(m, tea.MouseButtonLeft, sidebarW+10, toY) // over the pane + if got := titles(motion(m, toX, toY)); got != want { + t.Errorf("motion after a press elsewhere still dragged: %s", got) + } +} + +// TestMotionWithoutTheButtonDoesNotDrag: only a held left button drags. +func TestMotionWithoutTheButtonDoesNotDrag(t *testing.T) { + t.Setenv("XDG_STATE_HOME", t.TempDir()) + m := sessionView(t, 3, 120, 30) + sidebarW, _ := m.layout() + fromX, fromY := cellOf(t, m, "title-00", 0, sidebarW) + toX, toY := cellOf(t, m, "title-02", 0, sidebarW) + want := titles(m) + + m = press(m, tea.MouseButtonLeft, fromX, fromY) + next, _ := m.Update(tea.MouseMsg{X: toX, Y: toY, Button: tea.MouseButtonNone, Action: tea.MouseActionMotion}) + if got := titles(next.(Model)); got != want { + t.Errorf("motion with no button held moved the list to %s", got) + } +} + +// TestADashboardDragStaysInItsProject: the dashboard shows one project's +// sessions, and a key can change which while the button is held. A drop on the +// project now shown must not move a session of the project it left. +func TestADashboardDragStaysInItsProject(t *testing.T) { + t.Setenv("XDG_STATE_HOME", t.TempDir()) + st := mouseState(2, 3) + st.AddSession(store.Session{ProjectID: st.Projects[1].ID, Name: "name-other", Title: "other-title", Agent: "bash"}) + m := sized(New(st, "bash", nil), 120, 30) + navW := m.dashboardLayout().navW + fromX, fromY := cellOf(t, m, "title-02", navW, m.width) + want := titles(m) + + m = press(m, tea.MouseButtonLeft, fromX, fromY) + m.selectProject(1) + toX, toY := cellOf(t, m, "other-title", navW, m.width) + if got := titles(motion(m, toX, toY)); got != want { + t.Errorf("a drop on another project's list moved the dragged session: %s", got) + } +}