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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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
Expand Down
20 changes: 20 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions internal/coord/coord.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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")
},
Expand Down
51 changes: 50 additions & 1 deletion internal/coord/coord_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"sort"
"strings"
"testing"

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

func start(t *testing.T) *Coordinator {
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
Expand Down
7 changes: 7 additions & 0 deletions internal/coord/dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down
50 changes: 50 additions & 0 deletions internal/coord/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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 {
Expand Down
19 changes: 19 additions & 0 deletions internal/coord/tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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 " +
Expand Down
5 changes: 5 additions & 0 deletions internal/store/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down
1 change: 1 addition & 0 deletions internal/ui/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
4 changes: 2 additions & 2 deletions internal/ui/chrome.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
}
Expand All @@ -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
Expand Down
67 changes: 67 additions & 0 deletions internal/ui/form_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion internal/ui/formsession.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions internal/ui/input.go
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down
2 changes: 2 additions & 0 deletions internal/ui/keyroutes.go
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading
Loading