diff --git a/README.md b/README.md index b93092c..2ccde1f 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,7 @@ event. Any other agent gets `↑` and `↓`. | `^g j` / `^g k` | down / up the session list (stays attached if it is live) | | `^g` and a number | jump straight to that session | | `^g n` | new session | +| `^g e` | rename this session | | `^g x` | stop the agent | | `^g esc` | detach from the pane | | `^g ↵` | attach to the pane | @@ -260,6 +261,7 @@ status inferred from output and no sibling awareness. | `analysis` | Collect that review, with what it cost | | `message` | Send to one sibling by name, or to all of them | | `inbox` | Collect messages sent to you | +| `title` | Rename your own session in Deck, for example to the issue you just started | Claims are **advisory** — nothing stops another process writing the file. The value is answering "is anyone else in here", which no amount of written diff --git a/docs/architecture.md b/docs/architecture.md index 2e4a64c..e19da7d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -428,6 +428,26 @@ A result that crosses the boundary says so. `work` and the `sessions` rows carry a `project` only when the far session is on another one, so a row without it is on yours and its paths resolve against the tree you are looking at. +### An agent names its own session (`coord.SetOwnTitle`, `ui.applyAgentTitles`) + +A session's title is what tells cards apart, and a title typed when the +session opened goes stale as soon as the agent moves to its next task. The +`title` tool lets the agent keep it current. It renames only the caller's own +session: the caller is identified by its URL, as for every tool, and the tool +takes no session argument. + +The coordinator does not write the store. The store belongs to the UI's +goroutine, and a tool call arrives on the server's, so a write from there would +race every frame that reads it. `SetOwnTitle` updates the coordinator's own +copy at once, so siblings see the new title, and queues it. The frame tick +takes the queue and saves through `setTitle`, the same path the rename form +uses. A title queued for a session ended before the next frame is dropped: +it has nowhere to go, and nothing failed. + +Both ways in share one rule. `store.TitleLimit` caps the form's input and the +tool's argument alike, and the tool folds whitespace to single spaces because +the card has one line. + ### A spawned review (`coord.Analyse`, `agent.RunClaude`) `analyse` starts a **separate agent** to review a sibling's work. Four diff --git a/internal/coord/coord.go b/internal/coord/coord.go index 61d596d..9677de8 100644 --- a/internal/coord/coord.go +++ b/internal/coord/coord.go @@ -70,6 +70,10 @@ type Coordinator struct { jobs map[string]*Job spend map[string]float64 + // titles are the titles agents have set on their own sessions and the UI + // has not yet saved, by session id. See SetOwnTitle. + titles map[string]string + // spawn performs one headless turn. A field rather than a direct call // because otherwise `go test` invokes the paid CLI on every run, and CI — // where claude is not installed — reports green on a spawn that failed. @@ -119,6 +123,7 @@ func Start(notesDir string, opts ...Option) (*Coordinator, error) { peers: map[string]map[string]bool{}, jobs: map[string]*Job{}, spend: map[string]float64{}, + titles: map[string]string{}, spawn: func(ctx context.Context, dir, prompt string, onUsage func(agent.Tokens)) (agent.ClaudeRun, error) { return agent.RunClaude(ctx, dir, prompt, onUsage, "--permission-mode", "plan") }, diff --git a/internal/coord/coord_test.go b/internal/coord/coord_test.go index 77ad803..198e341 100644 --- a/internal/coord/coord_test.go +++ b/internal/coord/coord_test.go @@ -10,6 +10,8 @@ import ( "sort" "strings" "testing" + + "github.com/tripledownab/deck/internal/store" ) func start(t *testing.T) *Coordinator { @@ -220,7 +222,7 @@ func TestMCPHandshakeAndTools(t *testing.T) { list := rpc(t, c, "s1", "tools/list", nil) raw, _ := json.Marshal(list.Result) for _, want := range []string{"sessions", "claim", "release", "note", "notes", - "message", "inbox", "work", "analyse", "analysis"} { + "message", "inbox", "work", "analyse", "analysis", "title"} { if !strings.Contains(string(raw), `"`+want+`"`) { t.Errorf("tools/list is missing %q", want) } @@ -252,6 +254,53 @@ func TestMCPIdentifiesCallerByURL(t *testing.T) { } } +// TestTitleToolRenamesTheCallersSession: an agent renames its own session, +// never another. The title is folded to one line, siblings see it at once, and +// it waits for the UI to save exactly once. One past store.TitleLimit is +// refused, counted in characters rather than bytes, and leaves nothing queued. +func TestTitleToolRenamesTheCallersSession(t *testing.T) { + c := start(t) + twoSessions(t, c) + title := func(text string) rpcResp { + return rpc(t, c, "s1", "tools/call", map[string]any{ + "name": "title", "arguments": map[string]any{"text": text}, + }) + } + refused := func(r rpcResp) bool { + raw, _ := json.Marshal(r.Result) + return strings.Contains(string(raw), `"isError":true`) + } + + if r := title(" ABC-123 retry\nbudget "); r.Error != nil || refused(r) { + t.Fatalf("title refused: %+v", r) + } + if got := c.TakeTitles(); len(got) != 1 || got["s1"] != "ABC-123 retry budget" { + t.Errorf("queued titles = %v, want s1's, folded to one line", got) + } + if got := c.TakeTitles(); got != nil { + t.Errorf("titles were handed over twice: %v", got) + } + if rows := c.Siblings("s2"); len(rows) != 1 || rows[0]["title"] != "ABC-123 retry budget" { + t.Errorf("sibling reads %v, want the new title", rows) + } + + if r := title(strings.Repeat("é", store.TitleLimit)); refused(r) { + t.Errorf("a title of exactly %d characters was refused", store.TitleLimit) + } + c.TakeTitles() + for name, text := range map[string]string{ + "empty": " \n ", + "one past limit": strings.Repeat("é", store.TitleLimit+1), + } { + if r := title(text); !refused(r) { + t.Errorf("%s: accepted", name) + } + if got := c.TakeTitles(); got != nil { + t.Errorf("%s: queued %v", name, got) + } + } +} + // TestMCPAcceptsSSE covers the framing current claude asks for. func TestMCPAcceptsSSE(t *testing.T) { c := start(t) diff --git a/internal/coord/dispatch.go b/internal/coord/dispatch.go index 88827b7..0be6d80 100644 --- a/internal/coord/dispatch.go +++ b/internal/coord/dispatch.go @@ -51,6 +51,13 @@ func (s *server) dispatch(sessionID string, p toolCall) map[string]any { } return jsonResult(map[string]any{"sessions": siblings}) + case "title": + title, err := s.c.SetOwnTitle(sessionID, p.Arguments.Text) + if err != nil { + return errorResult(err.Error()) + } + return textResult("Deck now shows this session as: " + title) + case "claim": granted, conflicts := s.c.Claim(sessionID, p.Arguments.Paths, p.Arguments.Reason) out := map[string]any{"claimed": granted} diff --git a/internal/coord/registry.go b/internal/coord/registry.go index 23cfaa9..7ed7ee7 100644 --- a/internal/coord/registry.go +++ b/internal/coord/registry.go @@ -3,6 +3,15 @@ package coord // Sessions arriving and leaving: what the coordinator knows about a live agent // and what it forgets when that agent goes. +import ( + "errors" + "fmt" + "strings" + "unicode/utf8" + + "github.com/tripledownab/deck/internal/store" +) + // Register adds or updates a live session. func (c *Coordinator) Register(s Session) { c.mu.Lock() @@ -27,6 +36,47 @@ func (c *Coordinator) Retitle(id, title string) { c.sessions[id] = s } +// SetOwnTitle is an agent renaming its own session, through the title tool. +// +// The title is folded to one line, and refused when empty or past +// store.TitleLimit, the rule the rename form applies by construction. The +// folded title is returned, so the caller reports what was saved. It takes +// effect here at once, for siblings, and is queued for the UI to save: the +// store belongs to the UI's goroutine, and writing it from a tool call would +// race every frame that reads it. +func (c *Coordinator) SetOwnTitle(id, title string) (string, error) { + title = strings.Join(strings.Fields(title), " ") + if title == "" { + return "", errors.New("the title is empty") + } + if n := utf8.RuneCountInString(title); n > store.TitleLimit { + return "", fmt.Errorf("the title is %d characters, and at most %d fit", n, store.TitleLimit) + } + c.mu.Lock() + defer c.mu.Unlock() + s, ok := c.sessions[id] + if !ok { + return "", errors.New("unknown session") + } + s.Title = title + c.sessions[id] = s + c.titles[id] = title + return title, nil +} + +// TakeTitles hands over the titles agents have set since the last call, by +// session id, and forgets them. A session that set two keeps the later. +func (c *Coordinator) TakeTitles() map[string]string { + c.mu.Lock() + defer c.mu.Unlock() + if len(c.titles) == 0 { + return nil + } + taken := c.titles + c.titles = map[string]string{} + return taken +} + // Registered lists the session ids the coordinator currently knows about, so // the caller can reconcile them against the processes that are actually alive. func (c *Coordinator) Registered() []string { diff --git a/internal/coord/tools.go b/internal/coord/tools.go index 44ad242..cdf533c 100644 --- a/internal/coord/tools.go +++ b/internal/coord/tools.go @@ -2,6 +2,12 @@ package coord // The tools agents see. Answering a call is in dispatch.go. +import ( + "fmt" + + "github.com/tripledownab/deck/internal/store" +) + func toolSchemas() []map[string]any { pathList := map[string]any{ "type": "array", @@ -15,6 +21,19 @@ func toolSchemas() []map[string]any { "with the files each has claimed. Call this before starting work.", "inputSchema": map[string]any{"type": "object", "properties": map[string]any{}}, }, + { + "name": "title", + "description": "Rename this session in Deck: the title on its sidebar card, which " + + "is how the person running Deck tells sessions apart. Call it whenever you start " + + "a new task, with the task's issue key first if it has one, then a few words " + + fmt.Sprintf("(\"ABC-123 retry budget for upstream calls\"). One line, at most %d characters.", + store.TitleLimit), + "inputSchema": map[string]any{ + "type": "object", + "properties": map[string]any{"text": map[string]any{"type": "string"}}, + "required": []string{"text"}, + }, + }, { "name": "claim", "description": "Announce that you are about to work on these paths. Returns any " + diff --git a/internal/store/query.go b/internal/store/query.go index 3dd6855..2480401 100644 --- a/internal/store/query.go +++ b/internal/store/query.go @@ -7,6 +7,11 @@ import ( "time" ) +// TitleLimit is the most characters a session title may hold. The rename form +// stops typing there and the title tool refuses a longer one, so a title set +// either way fits the same sidebar card. +const TitleLimit = 120 + // Project is a git repository Deck manages sessions for. type Project struct { ID string `json:"id"` diff --git a/internal/ui/app.go b/internal/ui/app.go index 2c43b69..aeba491 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -78,6 +78,7 @@ func (m Model) route(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil case frameMsg: + m.applyAgentTitles() m.resizePane() m.sweepExited() m.dropDeadAttachment() diff --git a/internal/ui/chrome.go b/internal/ui/chrome.go index 969f3b1..e6ca43d 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"}, + {"d", "dashboard"}, {"j/k", "switch"}, {"1…", "jump"}, {"n", "new"}, {"e", "rename"}, {"x", "stop"}, {"↵", "attach"}, {"esc", "detach"}, {"?", "help"}, {"q", "quit"}, {"^g", "literal"}, } @@ -120,7 +120,7 @@ func (m Model) sessionFooter() string { if m.attached { return s.Footer.Render(" ^g for commands · ^g d dashboard · ^g j/k switch session · ^g n new · ^g ? help") } - return s.Footer.Render(" ↑/↓ session · ↵ attach · n new · x stop · d dashboard · ? help · q quit") + return s.Footer.Render(" ↑/↓ session · ↵ attach · n new · e rename · x stop · d dashboard · ? help · q quit") } // spread puts left and right on one line separated by padding, so the right diff --git a/internal/ui/form_test.go b/internal/ui/form_test.go index 8eb4b27..047c86b 100644 --- a/internal/ui/form_test.go +++ b/internal/ui/form_test.go @@ -464,6 +464,73 @@ func TestRenameFollowsTheFocusedColumn(t *testing.T) { }) } +// TestAgentTitlesReachTheStore: a title an agent sets through the coordinator +// is saved on the next frame, and a title for a session that has since been +// ended is dropped without reporting a fault. +func TestAgentTitlesReachTheStore(t *testing.T) { + c, err := coord.Start(t.TempDir()) + if err != nil { + t.Fatalf("coordinator: %v", err) + } + t.Cleanup(func() { _ = c.Close() }) + + st := &store.State{} + p := st.AddProject(store.Project{Name: "api-gateway", Path: "/code/api-gateway"}) + kept := st.AddSession(store.Session{ProjectID: p.ID, Name: "swift-otter-aaaa", Title: "old"}) + ended := st.AddSession(store.Session{ProjectID: p.ID, Name: "brave-heron-bbbb", Title: "old"}) + for _, s := range []*store.Session{kept, ended} { + c.Register(coord.Session{ID: s.ID, ProjectID: p.ID, Name: s.Name, Title: s.Title}) + } + keptID, endedID := kept.ID, ended.ID + for _, id := range []string{keptID, endedID} { + if _, err := c.SetOwnTitle(id, "ABC-123 retry budget"); err != nil { + t.Fatal(err) + } + } + st.Sessions = st.Sessions[:1] // the second session is ended before the frame + + next, _ := New(st, "bash", nil).WithCoordinator(c).Update(frameMsg{}) + got := next.(Model) + if title := got.state.Session(keptID).Title; title != "ABC-123 retry budget" { + t.Errorf("title = %q, want the agent's", title) + } + if got.fault != nil { + t.Errorf("fault = %v, want none for an ended session", got.fault) + } + if got.state.Session(endedID) != nil { + t.Error("the ended session came back") + } +} + +// TestRenameInTheSessionView: e renames the selected session from the session +// view, and ^g e does it from an attached pane, where a bare e belongs to the +// agent. Both act on the selected session rather than the first one. +func TestRenameInTheSessionView(t *testing.T) { + for name, keys := range map[string][]tea.KeyMsg{ + "e, detached": {typed("e")}, + "^g e, attached": {{Type: tea.KeyCtrlG}, typed("e")}, + } { + t.Run(name, func(t *testing.T) { + m := sized(New(mouseState(1, 2), "bash", nil), 120, 30) + m.screen, m.attached = screenSession, len(keys) == 2 + if !m.jumpToSession(2) { + t.Fatal("no second session to select") + } + var next tea.Model = m + for _, k := range keys { + next, _ = next.(Model).Update(k) + } + f := next.(Model).form + if f == nil || f.kind != formEditSession { + t.Fatalf("form = %+v, want the session rename form", f) + } + if want := m.currentSession().ID; f.subject != want { + t.Errorf("form is for %q, want the selected session %q", f.subject, want) + } + }) + } +} + // TestEditSessionFormPrefillsTheTitle pins the one field and the subject. The // heading carries the generated name because the title is the field being // replaced, so it cannot also be what says which session this is. diff --git a/internal/ui/formsession.go b/internal/ui/formsession.go index ad9f71f..36a42b4 100644 --- a/internal/ui/formsession.go +++ b/internal/ui/formsession.go @@ -70,7 +70,7 @@ func newSessionForm(projects []choice, selected int, canWorktree bool, agent str func titleField(value string) field { title := textinput.New() title.Placeholder = "what should this session do?" - title.CharLimit = 120 + title.CharLimit = store.TitleLimit title.Prompt = "" title.SetValue(value) return field{kind: fieldText, label: "Title", input: title, diff --git a/internal/ui/input.go b/internal/ui/input.go index 286ade2..417943c 100644 --- a/internal/ui/input.go +++ b/internal/ui/input.go @@ -106,6 +106,8 @@ func (m Model) command(msg tea.KeyMsg) (tea.Model, tea.Cmd) { } case "n": return m.openNewSessionForm() + case "e": + return m.openSessionRename() case "j", "down": m.moveRow(1) case "k", "up": diff --git a/internal/ui/keyroutes.go b/internal/ui/keyroutes.go index 2a35a4b..8498ec1 100644 --- a/internal/ui/keyroutes.go +++ b/internal/ui/keyroutes.go @@ -60,6 +60,8 @@ func (m Model) sessionKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { return m.attach() case key.Matches(msg, m.keys.NewSession): return m.openNewSessionForm() + case key.Matches(msg, m.keys.Rename): + return m.openSessionRename() case key.Matches(msg, m.keys.Delete): m.stopCurrent() case key.Matches(msg, m.keys.Connect): diff --git a/internal/ui/keys.go b/internal/ui/keys.go index 1eec767..2c33992 100644 --- a/internal/ui/keys.go +++ b/internal/ui/keys.go @@ -39,6 +39,7 @@ type keyMap struct { Dashboard key.Binding Sessions key.Binding NewSessCmd key.Binding + RenameCmd key.Binding StopSessCmd key.Binding ThemeCmd key.Binding HelpCmd key.Binding @@ -71,6 +72,7 @@ func defaultKeys() keyMap { Dashboard: key.NewBinding(key.WithKeys("d"), key.WithHelp("^g d", "dashboard")), Sessions: key.NewBinding(key.WithKeys("s"), key.WithHelp("^g s", "sessions")), NewSessCmd: key.NewBinding(key.WithKeys("n"), key.WithHelp("^g n", "new session")), + RenameCmd: key.NewBinding(key.WithKeys("e"), key.WithHelp("^g e", "rename this session")), StopSessCmd: key.NewBinding(key.WithKeys("x"), key.WithHelp("^g x", "stop the agent")), ThemeCmd: key.NewBinding(key.WithKeys("t"), key.WithHelp("^g t", "theme")), HelpCmd: key.NewBinding(key.WithKeys("?"), key.WithHelp("^g ?", "this help")), @@ -110,7 +112,7 @@ func (k keyMap) helpGroups() []helpGroup { k.NewSession, k.AddProject, k.Rename, k.Delete, k.Connect, k.Theme, k.Help, k.Quit, }}, {"COMMAND — press " + PrefixKey + " first", []key.Binding{ - k.Dashboard, k.Sessions, k.NextSess, k.JumpSess, k.NewSessCmd, k.StopSessCmd, + k.Dashboard, k.Sessions, k.NextSess, k.JumpSess, k.NewSessCmd, k.RenameCmd, k.StopSessCmd, k.Detach, k.Attach, k.ThemeCmd, k.HelpCmd, k.QuitCmd, }}, } diff --git a/internal/ui/rename.go b/internal/ui/rename.go index ca210b5..537a619 100644 --- a/internal/ui/rename.go +++ b/internal/ui/rename.go @@ -1,15 +1,22 @@ package ui -// Renaming what the dashboard lists. Registering a project is projects.go and -// creating a session is sessions.go; this is only the second name either gets. +// Renaming projects and sessions: from the dashboard, from the session view, +// and by a session's own agent through the title tool. +// Registering a project is projects.go and creating a session is sessions.go; +// this is only the second name either gets. import ( + "errors" "fmt" "path/filepath" tea "github.com/charmbracelet/bubbletea" ) +// errSessionGone is setTitle finding no session by that id. A form reports it, +// and applyAgentTitles skips it, so it is told apart from a failed save. +var errSessionGone = errors.New("that session is no longer open") + // openRenameForm is e on the dashboard. It renames whichever row the cursor is // on: the session when the sessions list has focus, the project otherwise. // @@ -31,6 +38,19 @@ func (m Model) openRenameForm() (tea.Model, tea.Cmd) { return m.openEditProjectForm() } +// openSessionRename is e in the session view, and ^g e from an attached pane. +// It renames the selected session, which in this view is the only one that +// can mean. +func (m Model) openSessionRename() (tea.Model, tea.Cmd) { + sess := m.currentSession() + if sess == nil { + m.notice = "no session to rename" + return m, nil + } + m.form = editSessionForm(sess) + return m, nil +} + // openEditProjectForm renames the project under the cursor. func (m Model) openEditProjectForm() (tea.Model, tea.Cmd) { p := m.currentProject() @@ -70,30 +90,55 @@ func (m Model) renameProject(id, name, description string) (tea.Model, tea.Cmd) // renameSession applies the session rename form. // -// By id rather than by cursor position, for the reason renameProject is. The -// sidebar needs no rebuild: its rows hold the store's own session, so the new -// title is on screen the next frame. +// By id rather than by cursor position, for the reason renameProject is. +func (m Model) renameSession(id, title string) (tea.Model, tea.Cmd) { + if err := m.setTitle(id, title); err != nil { + m.formProblem(err) + return m, nil + } + m.form = nil + m.notice = "renamed to " + title + return m, nil +} + +// setTitle saves a session's new title, whoever chose it. The sidebar needs no +// rebuild: its rows hold the store's own session, so the new title is on +// screen the next frame. // // The coordinator is told separately because it keeps its own copy of a // running session, taken when the agent started. Without this an agent asking // who its siblings are is answered with the old title for the rest of the run, // and the title is the only part of that answer that says what a sibling is // doing. -func (m Model) renameSession(id, title string) (tea.Model, tea.Cmd) { +func (m *Model) setTitle(id, title string) error { sess := m.state.Session(id) if sess == nil { - m.formProblem(fmt.Errorf("that session is no longer open")) - return m, nil + return errSessionGone } sess.Title = title if err := m.state.Save(); err != nil { - m.formProblem(err) - return m, nil + return err } if m.coord != nil { m.coord.Retitle(id, title) } - m.form = nil - m.notice = "renamed to " + title - return m, nil + return nil +} + +// applyAgentTitles saves the titles agents set with the title tool since the +// last frame. A session that has since been ended is skipped: its title has +// nowhere to go, and nothing failed. +func (m *Model) applyAgentTitles() { + if m.coord == nil { + return + } + for id, title := range m.coord.TakeTitles() { + switch err := m.setTitle(id, title); { + case errors.Is(err, errSessionGone): + case err != nil: + m.fault = fmt.Errorf("save the title an agent chose: %w", err) + default: + m.notice = "an agent renamed its session to " + title + } + } }