diff --git a/README.md b/README.md index 27d96ab..0116dc1 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ what differs. - **Markdown replies** — the agent's output is rendered with Glamour and reflows on resize. - **Clickable links** — `http(s)` URLs in the transcript are wrapped as OSC 8 terminal hyperlinks (Cmd/Ctrl-click, or a plain click with `/mouse` off). - **Extended thinking** — the model's reasoning renders dim above its reply; a hook that blocks or fails surfaces too (routine ones stay quiet). -- **Session resume** — `ctrl+r` (or `/sessions`) fuzzy-filters your session history for the running backend and re-execs into the one you pick. +- **Session resume** — `ctrl+r` (or `/sessions`) fuzzy-filters your session history for the running backend and re-execs into the one you pick. Rows are two lines: the name on top, the id, repo, model and age beneath. `/title ` names the live session so the picker shows that instead of your first prompt. - **Command palette** — `ctrl+t` (or `/commands`) browses every command — our in-process ones plus claude's built-ins, **skills**, and **plugin** commands (from the init handshake) — and runs or forwards the one you pick; `/agents` lists subagents. Any `/command` we don't own is forwarded to claude, so custom & plugin commands work. - **11 themes + header animations** — `/theme` and `/settings`, with live preview, persisted across launches (see [Themes](#themes)). - **Live status bar** — permission mode, session id, git branch, a context-pressure gauge that auto-grows 200K → 2M, output tokens, and running cost. diff --git a/claude_sessions.go b/claude_sessions.go index 8ab927d..5e2230a 100644 --- a/claude_sessions.go +++ b/claude_sessions.go @@ -124,11 +124,22 @@ func sessionItems(s *sessionStore, cwd, backend string) []pickerItem { if sessionBackend(e.Backend) != sessionBackend(backend) { continue } - title := short(e.ID) - if e.First != "" { - title = short(e.ID) + " " + e.First + // The label the row is read for, in order of usefulness: a name the user + // gave it, else the first thing they asked, else the id. The id moves to + // the second row either way — it identifies the session but nobody scans + // a list by it, and on a narrow terminal it was crowding out the part + // that is actually readable. + title, id := e.Title, short(e.ID) + if title == "" { + title = e.First + } + parts := []string{id, filepath.Base(e.Cwd)} + if title == "" { + // Nothing to label it with: an empty or malformed session file has + // no first prompt to read. Fall back to the id, and drop it from the + // detail row so it is not printed twice. + title, parts = id, parts[1:] } - parts := []string{filepath.Base(e.Cwd)} if e.Model != "" { parts = append(parts, e.Model) } @@ -152,12 +163,22 @@ func mergeWithStore(fs []sessionInfo, s *sessionStore, cwd string) []sessionInfo out := make([]sessionInfo, 0, len(fs)) for _, e := range fs { if cached, ok := stored[e.ID]; ok { - if e.Model == "" && cached.Model != "" { - e.Model = cached.Model + // Start from the stored record and let the filesystem override only + // what it is authoritative for. The reverse — copying named fields + // out of the store into the filesystem entry — silently drops every + // field nobody remembered to list, which is how session titles were + // lost the moment they were added: a claude session always has a + // JSONL on disk, so the filesystem entry always won. + merged := cached + merged.ID, merged.Cwd = e.ID, e.Cwd + merged.LastUsed = e.LastUsed // claude's mtime is always the fresher one + if e.Model != "" { + merged.Model = e.Model } - if e.First == "" && cached.First != "" { - e.First = cached.First + if e.First != "" { + merged.First = e.First } + e = merged } seen[e.ID] = true out = append(out, e) diff --git a/commandlist.go b/commandlist.go index dd4b3b5..d8a39fc 100644 --- a/commandlist.go +++ b/commandlist.go @@ -57,6 +57,13 @@ func slashCommands() []slashCmd { return *m, nil }, }, + { + name: "title", + desc: "name this session, so the resume picker shows it instead of the first prompt", + exec: func(m *model, arg string) (model, tea.Cmd) { + return *m, m.commitTitle(arg) + }, + }, { name: "backend", desc: "switch the agent CLI without restarting (claude|codex)", @@ -222,6 +229,7 @@ func slashCommands() []slashCmd { exec: func(m *model, _ string) (model, tea.Cmd) { cwd, _ := os.Getwd() m.picker = newPicker("sessions", "RESUME SESSION", sessionItems(m.sessions, cwd, m.backend), m.w, m.h) + m.picker.twoLine = true return *m, nil }, }, diff --git a/keys.go b/keys.go index 9a4b1a2..39c58b9 100644 --- a/keys.go +++ b/keys.go @@ -132,6 +132,7 @@ func (m model) handleKey(msg tea.KeyMsg) (model, tea.Cmd, bool) { case "ctrl+r": cwd, _ := os.Getwd() m.picker = newPicker("sessions", "RESUME SESSION", sessionItems(m.sessions, cwd, m.backend), m.w, m.h) + m.picker.twoLine = true return m, nil, true case "ctrl+t": m.picker = newPicker("slash", "COMMANDS", m.paletteItems(), m.w, m.h) diff --git a/model.go b/model.go index 3e41ca8..b6e5101 100644 --- a/model.go +++ b/model.go @@ -270,6 +270,13 @@ func newModel(cfg launchConfig) model { // transcript isn't empty after re-exec. claude itself loads the session // into context — this is purely a visual rehydrate. if cfg.ResumeID != "" { + // We already know which session this is, so say so now. claude does not + // emit its system/init line until the first turn of a process, so + // without this m.session stays empty on a resumed session — and + // everything keyed on it (/title, the status row, /sysprompt's restart) + // behaves as though there were no session at all until you send a turn. + m.session = cfg.ResumeID + // Skip the boot splash: the user already picked the session, so drop // them straight back into the transcript. m.splash = false diff --git a/picker.go b/picker.go index 5919c6e..077d9bd 100644 --- a/picker.go +++ b/picker.go @@ -76,6 +76,12 @@ type picker struct { cursor int // index into filtered w, h int + // twoLine puts the subtitle on its own row under the title, instead of + // trailing it on the same one. Half as many rows fit, which is the trade: + // a one-line row truncates the title away first on a narrow terminal, and + // the title is the part you are reading the list for. + twoLine bool + // Checklist mode — see pickermulti.go. multi bool marked map[int]bool // marked item indices @@ -193,6 +199,11 @@ func (p *picker) Update(msg tea.Msg) (*picker, string) { return p, "" } +// pickerMaxWidth clamps the dialog on a wide terminal, where a full-width modal +// would be a very long line to read. It also bounds how much of a row can ever +// be shown, which is why sessionLabelMax is set well past it (sessions.go). +const pickerMaxWidth = 100 + // View renders the picker as a CP437-bordered dialog. Width is clamped so it // looks reasonable even in tiny terminals. func (p *picker) View() string { @@ -200,8 +211,8 @@ func (p *picker) View() string { if w < 40 { w = 40 } - if w > 100 { - w = 100 + if w > pickerMaxWidth { + w = pickerMaxWidth } maxRows := p.h - 8 if maxRows < 4 { @@ -210,6 +221,16 @@ func (p *picker) View() string { if maxRows > 16 { maxRows = 16 } + // maxRows is screen rows; the window is measured in ITEMS. A two-line item + // takes two rows, so half as many fit — without this the list renders past + // the bottom of the box and the scrollbar no longer matches the text. + maxItems := maxRows + if p.twoLine { + maxItems = maxRows / 2 + if maxItems < 2 { + maxItems = 2 + } + } innerW := w - 2 // text area inside the box's 1-col padding listW := innerW - 1 // reserve the last column for the scrollbar gutter @@ -223,33 +244,69 @@ func (p *picker) View() string { section := cDim.Render(" (no matches)") if len(p.filtered) > 0 { start := 0 - if p.cursor >= maxRows { - start = p.cursor - maxRows + 1 + if p.cursor >= maxItems { + start = p.cursor - maxItems + 1 } - end := start + maxRows + end := start + maxItems if end > len(p.filtered) { end = len(p.filtered) } - rows := make([]string, 0, end-start) + // ANSI-aware truncate + space-pad to a fixed width so the scrollbar + // lands as a straight column regardless of styled content. + // "…" rather than a bare cut: a row trimmed to fit should say so, or a + // truncated title reads as the whole of a shorter one. + pad := func(line string, w int) string { + line = ansi.Truncate(line, w, "…") + if n := w - lipgloss.Width(line); n > 0 { + line += strings.Repeat(" ", n) + } + return line + } + fit := func(line string) string { return pad(line, listW) } + rows := make([]string, 0, (end-start)*2) for i := start; i < end; i++ { idx := p.filtered[i] it := p.items[idx] mk := p.mark(idx) - line := fmt.Sprintf(" %s%s %s", mk, it.title, cDim.Render(it.subtitle)) - if i == p.cursor { - line = approveBar.Render(" " + mk + it.title + " " + it.subtitle + " ") + sel := i == p.cursor + + if !p.twoLine { + line := fmt.Sprintf(" %s%s %s", mk, it.title, cDim.Render(it.subtitle)) + if sel { + line = approveBar.Render(" " + mk + it.title + " " + it.subtitle + " ") + } + rows = append(rows, fit(line)) + continue } - // ANSI-aware truncate + space-pad to a fixed width so the scrollbar - // lands as a straight column regardless of styled content. - line = ansi.Truncate(line, listW, "") - if pad := listW - lipgloss.Width(line); pad > 0 { - line += strings.Repeat(" ", pad) + + // Two rows per item. A selected one is padded to the same width + // BEFORE styling, so both lines highlight to the same length — style + // first and the lightbar is two ragged blocks, because a title and + // its detail line are never the same length. + head, sub := " "+mk+it.title, " "+it.subtitle + if sel { + // The lightbar style has horizontal padding, so content padded + // to the full list width renders wider than it, wraps, and + // desyncs the scrollbar gutter from the text beside it. Ask the + // style for its own inset rather than restating the number here: + // a theme that changes the padding would otherwise break this + // silently, and the symptom is a layout glitch nobody traces + // back to a style definition. + inner := listW - approveBar.GetHorizontalFrameSize() + if inner < 1 { + inner = 1 + } + rows = append(rows, approveBar.Render(pad(head, inner))) + rows = append(rows, approveBar.Render(pad(sub, inner))) + continue } - rows = append(rows, line) + rows = append(rows, fit(head), fit(cDim.Render(sub))) } // Themed BBS scrollbar gutter, mirroring the transcript's — replaces the // old "N more…" text so a long session/command list scrolls in-theme. - bar := bbsScrollbar(len(rows), len(p.filtered), len(rows), start, true) + // Measured in items, not rows: the thumb tracks position in the list, + // and its height is the gutter's, which is however many rows we drew. + bar := bbsScrollbar(len(rows), len(p.filtered), end-start, start, true) section = lipgloss.JoinHorizontal(lipgloss.Top, strings.Join(rows, "\n"), bar) } diff --git a/picker_test.go b/picker_test.go new file mode 100644 index 0000000..71fc89a --- /dev/null +++ b/picker_test.go @@ -0,0 +1,58 @@ +// Copyright 2026 Triple Down AB +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "strings" + "testing" +) + +// A styled row must not wrap. The lightbar style adds a column of padding on +// each side, so padding the content to the full list width renders two columns +// too wide; the row wraps, and the scrollbar gutter then interleaves with the +// text instead of sitting beside it. +// +// Counting lines, not widths: the surrounding box pads every line to the same +// width whatever happens inside it, so a width check passes even while the +// layout is broken. +func TestTwoLinePickerRowsDoNotWrap(t *testing.T) { + const items, h = 6, 24 + rows := make([]pickerItem, items) + for i := range rows { + rows[i] = pickerItem{ + id: string(rune('a' + i)), + title: strings.Repeat("title ", 6), + subtitle: strings.Repeat("detail ", 6), + } + } + p := newPicker("sessions", "RESUME SESSION", rows, 64, h) + p.twoLine = true + p.cursor = 1 // the selected row is the styled one, and the one that wrapped + + got := len(strings.Split(stripANSI(p.View()), "\n")) + // 2 border + title + filter input + 2 per item + footer. + want := 2 + 2 + items*2 + 1 + if got != want { + t.Errorf("rendered %d lines, want %d — a row wrapped:\n%s", + got, want, stripANSI(p.View())) + } +} + +// Half as many items fit when each takes two rows, or the list renders past the +// bottom of the box. +func TestTwoLinePickerShowsHalfAsManyItems(t *testing.T) { + items := make([]pickerItem, 40) + for i := range items { + items[i] = pickerItem{id: string(rune('a' + i%26)), title: "t", subtitle: "s"} + } + count := func(two bool) int { + p := newPicker("sessions", "T", items, 64, 40) + p.twoLine = two + body := stripANSI(p.View()) + return strings.Count(body, "\n") + } + if one, two := count(false), count(true); one != two { + t.Errorf("box height changed with the row style: %d vs %d lines", one, two) + } +} diff --git a/sessions.go b/sessions.go index 89dbc2f..33458ae 100644 --- a/sessions.go +++ b/sessions.go @@ -22,6 +22,11 @@ type sessionInfo struct { Cwd string `json:"cwd"` LastUsed time.Time `json:"last_used"` First string `json:"first,omitempty"` // truncated first user prompt, if known + // Title is a name the user gave this session (/title). It replaces First in + // the picker, because a first prompt is often a poor label for what the + // session turned into — and on a narrow terminal it is the row's only + // readable part. + Title string `json:"title,omitempty"` // Backend is which agent CLI owns this id. Empty means claude: every record // written before cathode had a second backend is one of its sessions, so the // zero value is the right default and no migration is needed. @@ -80,6 +85,25 @@ func (s *sessionStore) load() { // Touch upserts a session. Empty model/cwd/first don't overwrite existing // values (so a follow-up Touch carrying only LastUsed preserves prior // metadata). LastUsed is always bumped. +// SetTitle names a session. An empty title clears it, so the picker falls back +// to the first prompt — there is no separate "unset" verb to remember. +func (s *sessionStore) SetTitle(id, title string) { + if id == "" { + return + } + s.mu.Lock() + defer s.mu.Unlock() + cur, ok := s.entries[id] + if !ok { + // Titling a session the store has never seen would create a row with no + // cwd, model or timestamp, which then sorts and renders as a ghost. + return + } + cur.Title = title + s.entries[id] = cur + s.rewrite() // called with the lock held, the same as Touch +} + func (s *sessionStore) Touch(id, model, cwd, first, backend string, now time.Time) { if id == "" { return @@ -138,13 +162,23 @@ func (s *sessionStore) rewrite() { // ---- presentation helpers (display formatting) ---- -// truncFirst trims a first-prompt so the picker subtitle stays one line. +// sessionLabelMax bounds what a session record persists as its label, and is +// deliberately well past any width the picker can render (pickerMaxWidth). +// +// It is a *storage* bound, not a display one: it stops a pasted essay becoming +// a row's label and bloating the store, and nothing more. Truncating for the +// screen is the picker's job, because only it knows the terminal's width — when +// this number did that job instead, a 64-character cut left a third of the row +// empty on a wide terminal. +const sessionLabelMax = 200 + +// truncFirst normalises a first prompt into a one-line session label. It is the +// row's title when no /title was set, so it is the part the list is read for. func truncFirst(s string) string { - s = strings.TrimSpace(strings.ReplaceAll(s, "\n", " ")) - if len(s) > 64 { - return s[:61] + "…" - } - return s + // trunc, not a byte slice. s[:61] cuts a multi-byte rune in half and emits + // invalid UTF-8, and a first prompt is prose — the same bug sysPromptSummary + // was already fixed for. + return trunc(strings.TrimSpace(strings.ReplaceAll(s, "\n", " ")), sessionLabelMax) } // humanizeAge renders "5m ago" / "2h ago" / "3d ago" style relative times. diff --git a/sessiontitle.go b/sessiontitle.go new file mode 100644 index 0000000..bfe9560 --- /dev/null +++ b/sessiontitle.go @@ -0,0 +1,62 @@ +// Copyright 2026 Triple Down AB +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "os" + "strings" + "time" + + tea "github.com/charmbracelet/bubbletea" +) + +// ---- naming a session (`/title`) ---- +// +// The resume picker labelled every row with the first thing you asked. That is +// a poor label for what a long session turned into, and on a narrow terminal it +// is the only part of the row worth reading, so it is what gets truncated last +// and noticed first. A title you choose replaces it. +// +// Titles live in cathode's own session store, not the agent's transcript: +// neither backend has a place to put one, and a name is the user's note to +// themselves rather than anything the agent should see. + +// commitTitle names the live session, or clears the name when given no +// argument. Every path says what happened: a silent return reads as "saved". +func (m *model) commitTitle(arg string) tea.Cmd { + title := trimTitle(arg) + + if m.session == "" { + // A fresh session has no id until the agent reports one, and claude + // does not until the first turn. A resumed session is seeded from the + // id it was resumed with (model.go), so this is only the new-session + // case. + m.add(entError, "no session to name yet — send a turn first") + return nil + } + // Make sure there is a row to title. A session started outside cathode is + // listed from claude's own JSONL and may never have been written to our + // store, and SetTitle ignores an id it does not know — so without this the + // title is dropped while the confirmation below still prints. + cwd, _ := os.Getwd() + m.sessions.Touch(m.session, m.modelID, cwd, "", m.backend, time.Now()) + m.sessions.SetTitle(m.session, title) + if title == "" { + m.add(entInfo, "→ title cleared · the picker shows the first prompt again") + return nil + } + m.add(entInfo, "→ title: "+title) + return nil +} + +// trimTitle normalises what the user typed: one line, no surrounding space, +// capped. Newlines collapse to spaces because the picker row is one line and a +// stored newline would silently truncate the rest of the title. +// +// The cap goes through trunc rather than slicing here, so it counts runes and +// marks what it dropped. A title cut mid-word with no ellipsis reads as one the +// user typed that way. +func trimTitle(s string) string { + return trunc(strings.Join(strings.Fields(s), " "), sessionLabelMax) +} diff --git a/sessiontitle_test.go b/sessiontitle_test.go new file mode 100644 index 0000000..19e6206 --- /dev/null +++ b/sessiontitle_test.go @@ -0,0 +1,237 @@ +// Copyright 2026 Triple Down AB +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "strings" + "testing" + "time" + "unicode/utf8" +) + +// A title replaces the first prompt as the row's label, and clearing it brings +// the first prompt back — there is no separate "unset" verb to remember. +func TestTitleReplacesTheFirstPromptInThePicker(t *testing.T) { + s := newTestStore(t) + const cwd = "/work/repo" + t0 := time.Date(2026, 6, 14, 0, 0, 0, 0, time.UTC) + s.Touch("sess-1", "sonnet", cwd, "the first thing I asked", backendClaude, t0) + + label := func() string { + items := sessionItems(s, cwd, backendClaude) + if len(items) != 1 { + t.Fatalf("want one row, got %d", len(items)) + } + return items[0].title + } + if got := label(); got != "the first thing I asked" { + t.Errorf("untitled row = %q, want the first prompt", got) + } + + s.SetTitle("sess-1", "rewriting the parser") + if got := label(); got != "rewriting the parser" { + t.Errorf("titled row = %q, want the title", got) + } + + s.SetTitle("sess-1", "") + if got := label(); got != "the first thing I asked" { + t.Errorf("cleared row = %q, want the first prompt back", got) + } +} + +// The identifying detail moves to the second row. It is what the row is +// selected by, but not what it is scanned by. +func TestSessionRowPutsIdentityInTheSubtitle(t *testing.T) { + s := newTestStore(t) + const cwd = "/work/repo" + s.Touch("sess-abcdef", "sonnet", cwd, "p", backendClaude, time.Now()) + s.SetTitle("sess-abcdef", "a name") + + it := sessionItems(s, cwd, backendClaude)[0] + if it.title != "a name" { + t.Errorf("title row = %q, want only the name", it.title) + } + for _, want := range []string{short("sess-abcdef"), "repo", "sonnet"} { + if !strings.Contains(it.subtitle, want) { + t.Errorf("subtitle %q should carry %q", it.subtitle, want) + } + } +} + +// Titling a session the store has never seen would create a row with no cwd, +// model or timestamp, which then sorts and renders as a ghost. +func TestSetTitleIgnoresUnknownSessions(t *testing.T) { + s := newTestStore(t) + s.SetTitle("never-seen", "a name") + if n := len(s.All()); n != 0 { + t.Errorf("store gained %d rows from titling an unknown session", n) + } +} + +// A title is one line: the picker row is one line, and a stored newline would +// silently truncate the rest of it. +func TestTrimTitleNormalisesWhatWasTyped(t *testing.T) { + if got := trimTitle(" spaced out \n and wrapped "); got != "spaced out and wrapped" { + t.Errorf("got %q", got) + } + if got := trimTitle(" "); got != "" { + t.Errorf("whitespace-only should clear the title, got %q", got) + } + // Runes, not bytes: a title is prose, and a byte slice cuts a multi-byte + // rune in half and emits invalid UTF-8. + long := trimTitle(strings.Repeat("é", sessionLabelMax*2)) + if n := len([]rune(long)); n != sessionLabelMax { + t.Errorf("capped to %d runes, want %d", n, sessionLabelMax) + } + if !utf8.ValidString(long) { + t.Errorf("capped title is not valid UTF-8: %q", long) + } + if !strings.HasSuffix(long, "…") { + t.Errorf("a capped title should mark what it dropped, got %q", long) + } +} + +// The same rule for the first prompt, which used to be sliced by byte offset. +func TestTruncFirstIsRuneSafe(t *testing.T) { + got := truncFirst(strings.Repeat("é", sessionLabelMax*2)) + if !utf8.ValidString(got) { + t.Errorf("truncated prompt is not valid UTF-8: %q", got) + } + if n := len([]rune(got)); n != sessionLabelMax { + t.Errorf("capped to %d runes, want %d", n, sessionLabelMax) + } +} + +// The stored bound must never be the thing that limits what is shown: the +// picker knows the terminal's width and this does not. A label cut short by +// storage leaves the rest of a wide row empty, which is what a 64-rune cap did. +func TestStorageBoundIsWiderThanAnythingThePickerCanShow(t *testing.T) { + if sessionLabelMax <= pickerMaxWidth { + t.Errorf("sessionLabelMax (%d) must exceed pickerMaxWidth (%d), or storage truncates the display", + sessionLabelMax, pickerMaxWidth) + } +} + +// Naming before the agent has reported a session id has nothing to attach to, +// and saying so beats appearing to save. +func TestCommitTitleRefusesWithoutASession(t *testing.T) { + m, _ := newTestModel(t, "") + m.session = "" + + m.commitTitle("a name") + + last := m.entries[len(m.entries)-1] + if last.kind != entError || !strings.Contains(last.text, "no session") { + t.Errorf("entry = %+v, want an error explaining there is nothing to name", last) + } +} + +// With neither a title nor a first prompt there is nothing to label the row +// with, so it falls back to the id — and the id must then not also head the +// detail row underneath it. +func TestSessionRowDoesNotPrintTheIdTwice(t *testing.T) { + s := newTestStore(t) + const cwd = "/work/repo" + s.Touch("sess-abcdef", "sonnet", cwd, "", backendClaude, time.Now()) + + it := sessionItems(s, cwd, backendClaude)[0] + id := short("sess-abcdef") + if it.title != id { + t.Errorf("title = %q, want the id as the last-resort label", it.title) + } + if strings.Contains(it.subtitle, id) { + t.Errorf("subtitle %q repeats the id already used as the title", it.subtitle) + } + if !strings.Contains(it.subtitle, "repo") { + t.Errorf("subtitle %q lost the rest of the detail", it.subtitle) + } +} + +// A title has to survive the merge with claude's own session files. +// +// Every claude session has a JSONL on disk, so the filesystem entry always wins +// the merge. Copying named fields out of the store into it drops everything +// nobody remembered to list — which silently made /title a no-op on the backend +// most sessions run on, while still printing a confirmation. +func TestMergeKeepsStoreOnlyFieldsWhenTheFilesystemWins(t *testing.T) { + s := newTestStore(t) + const cwd = "/work/repo" + old := time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC) + s.Touch("sess-1", "sonnet", cwd, "the first thing I asked", backendClaude, old) + s.SetTitle("sess-1", "rewriting the parser") + + // What listClaudeSessions produces: id, cwd, mtime, and what it could parse. + fresh := time.Date(2026, 6, 20, 0, 0, 0, 0, time.UTC) + fs := []sessionInfo{{ID: "sess-1", Cwd: cwd, LastUsed: fresh, First: "the first thing I asked"}} + + merged := mergeWithStore(fs, s, cwd) + if len(merged) != 1 { + t.Fatalf("want one merged row, got %d", len(merged)) + } + got := merged[0] + if got.Title != "rewriting the parser" { + t.Errorf("Title = %q — a store-only field was dropped by the merge", got.Title) + } + if got.Backend != backendClaude { + t.Errorf("Backend = %q, want it carried from the store", got.Backend) + } + if !got.LastUsed.Equal(fresh) { + t.Errorf("LastUsed = %v, want the filesystem mtime to still win", got.LastUsed) + } + if got.Model != "sonnet" { + t.Errorf("Model = %q, want the cached one when the file did not name it", got.Model) + } +} + +// A resumed session already knows its id, so /title must work before the first +// turn. claude does not emit system/init until a turn runs, so without seeding +// this, m.session stays empty on resume and /title refuses with "send a turn +// first" — which is what live testing hit. +func TestResumedSessionKnowsItsIdBeforeTheFirstTurn(t *testing.T) { + t.Setenv("XDG_STATE_HOME", t.TempDir()) + m := newModel(launchConfig{ + Engine: &fakeEngine{}, Backend: backendClaude, + Mode: "ask", Spinner: "bar", ResumeID: "resumed-1", + }) + if m.session != "resumed-1" { + t.Errorf("session = %q, want the id it was resumed with", m.session) + } + + m.commitTitle("a name") + last := m.entries[len(m.entries)-1] + if last.kind == entError { + t.Errorf("titling a resumed session failed: %q", last.text) + } + if got := titleOf(t, m.sessions, "resumed-1"); got != "a name" { + t.Errorf("stored title = %q, want it saved", got) + } +} + +// A session started outside cathode is listed from claude's own JSONL and may +// never have been written to our store. SetTitle ignores an id it does not +// know, so the title would be dropped while the confirmation still printed. +func TestTitlingASessionTheStoreHasNeverSeen(t *testing.T) { + m, _ := newTestModel(t, "") + m.session = "started-elsewhere" + + m.commitTitle("named from cathode") + + if got := titleOf(t, m.sessions, "started-elsewhere"); got != "named from cathode" { + t.Errorf("stored title = %q, want the row created and titled", got) + } + last := m.entries[len(m.entries)-1] + if last.kind == entError { + t.Errorf("unexpected error: %q", last.text) + } +} + +func titleOf(t *testing.T, s *sessionStore, id string) string { + t.Helper() + for _, e := range s.All() { + if e.ID == id { + return e.Title + } + } + return "" +}