diff --git a/docs/tui.md b/docs/tui.md index 22045222..3a74441b 100644 --- a/docs/tui.md +++ b/docs/tui.md @@ -50,6 +50,7 @@ uppercase belongs to Labels: | `r` | reply | | `f` | forward | | `v` | move | +| `w` | bubble up now, schedule a return, or cancel a bubble-up | | `b` | manage labels | | `n` | add to or remove from a collection | | `e` / `u` | mark seen / unseen — every selected thread when any are selected (Imbox only, as in HEY's web app), otherwise the one under the cursor | @@ -82,6 +83,24 @@ Sending a reply or a forward from a thread closes the thread and returns you to While reading a thread, the From header shows the actual send-as address when HEY records one separately from the account user. +Press `w` from the mail list or an open thread for the **Bubble up** menu. Use the +arrow keys and Enter to choose Now, Later today, Tomorrow, This weekend, Next week, +or Choose a date. Presets show the scheduled time in your local zone. HEY schedules +on its UTC calendar: morning is 08:00 UTC and Later today is 18:00 UTC. The menu +omits Later today once that time has passed. A custom date uses 08:00 UTC, or +18:00 UTC if you choose today's UTC date; past slots are refused. In the date field, +type YYYY-MM-DD or use Up/Down to change the day. Escape returns to the menu; +Escape again closes it without changing the thread. + +For scheduled or already bubbled-up threads, the menu also offers Cancel bubble-up. +HEY returns a canceled thread to the Imbox, marked seen. A successful action closes +the open thread and refreshes its list. A failed action keeps the menu open for retry. +From search, the menu first checks whether the thread has a bubble-up to cancel. +Escape cancels the lookup; if it fails, Ctrl+R retries it. + +Bubble up acts on one thread at a time; clear a bulk selection in the visible list +first, and open a bundle to choose an individual thread. + While reading a thread, links can be selected without a mouse. Tab selects the next link in document order and Shift+Tab selects the previous one; both wrap at the ends. A fixed row above the shortcut bar shows the selected destination without moving the thread. A destination too long for one row wraps onto as many rows as it needs, so you always see all of it. Press Enter to open it; opening stays unavailable until the terminal is tall enough to show the whole destination. Press Escape once to clear the selection, and Escape again to leave the thread. A thread with no selectable links keeps the normal global Tab focus behavior. Existing OSC 8 mouse links remain available. Most of those keep working while you are reading a thread, the way the web app's topic diff --git a/internal/cmd/bubble_test.go b/internal/cmd/bubble_test.go index 56ca7a9b..caacab81 100644 --- a/internal/cmd/bubble_test.go +++ b/internal/cmd/bubble_test.go @@ -28,7 +28,7 @@ type recordedBubble struct { func bubbleServer(t *testing.T) (*httptest.Server, *recordedBubble) { t.Helper() - recorded := &recordedBubble{status: http.StatusNoContent} + recorded := &recordedBubble{status: http.StatusOK} server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { recorded.requests++ recorded.method = r.Method diff --git a/internal/mail/posting.go b/internal/mail/posting.go index 6e31b949..92d0b6c5 100644 --- a/internal/mail/posting.go +++ b/internal/mail/posting.go @@ -30,6 +30,7 @@ type Posting struct { // from the posting's kind — HEY's `bundled` flag means filed *inside* a bundle. IsBundle bool BubbledUp bool + BubbleScheduled bool Muted bool VisibleEntryCount int32 Creator Contact @@ -86,6 +87,7 @@ func NewPosting(posting generated.Posting) Posting { Seen: posting.Seen, IsBundle: posting.Kind == "bundle", BubbledUp: posting.BubbledUp, + BubbleScheduled: !posting.BubbleUpSchedule.BubbleUpAt.IsZero() || posting.BubbleUpSchedule.SurpriseMe, Muted: posting.Muted, VisibleEntryCount: posting.VisibleEntryCount, Creator: contactOf(posting.Creator), diff --git a/internal/mail/posting_test.go b/internal/mail/posting_test.go index f1a3e4e6..c4b1ba49 100644 --- a/internal/mail/posting_test.go +++ b/internal/mail/posting_test.go @@ -161,3 +161,17 @@ func TestPostingsDescribesAPage(t *testing.T) { t.Error("an empty page should describe as an empty slice, not nil") } } + +func TestNewPostingKeepsBubbleSchedulePresence(t *testing.T) { + for _, schedule := range []generated.BubbleUpSchedule{ + {BubbleUpAt: time.Date(2026, 12, 4, 8, 0, 0, 0, time.UTC)}, + {SurpriseMe: true}, + } { + if !NewPosting(generated.Posting{BubbleUpSchedule: schedule}).BubbleScheduled { + t.Fatal("lost scheduled bubble-up") + } + } + if NewPosting(generated.Posting{}).BubbleScheduled { + t.Fatal("empty schedule should not offer cancellation") + } +} diff --git a/internal/tui/bubble.go b/internal/tui/bubble.go new file mode 100644 index 00000000..8308930e --- /dev/null +++ b/internal/tui/bubble.go @@ -0,0 +1,281 @@ +package tui + +import ( + "context" + "strings" + "time" + + tea "charm.land/bubbletea/v2" + hey "github.com/basecamp/hey-sdk/go/pkg/hey" + + "github.com/basecamp/hey-cli/internal/mail" +) + +type bubbleAction int + +const ( + bubbleNow bubbleAction = iota + bubbleSchedule + bubbleChooseDate + bubbleCancel +) + +type bubbleChoice struct { + action bubbleAction + name string + slot hey.BubbleUpSlot + at time.Time +} + +type bubblePicker struct { + plainModal + postingID int64 + choices []bubbleChoice + cursor int + date *dateTimePicker + busy bool + loading bool + unknownState bool + lookupCancel context.CancelFunc + problem string + now func() time.Time + openedDay string +} + +type bubbleDoneMsg struct { + picker *bubblePicker + message string + err error +} + +func newBubblePicker(posting mail.Posting, scheduled bool, now func() time.Time) *bubblePicker { + at := now().UTC() + morning := time.Date(at.Year(), at.Month(), at.Day(), 8, 0, 0, 0, time.UTC) + p := &bubblePicker{postingID: posting.ID, now: now, openedDay: at.Format("2006-01-02")} + p.choices = append(p.choices, bubbleChoice{name: "Now"}) + if evening := morning.Add(10 * time.Hour); evening.After(at) { + p.choices = append(p.choices, bubbleChoice{name: "Later today", action: bubbleSchedule, slot: hey.BubbleUpLaterToday, at: evening}) + } + p.choices = append(p.choices, + bubbleChoice{name: "Tomorrow", action: bubbleSchedule, slot: hey.BubbleUpTomorrow, at: morning.AddDate(0, 0, 1)}, + bubbleChoice{name: "This weekend", action: bubbleSchedule, slot: hey.BubbleUpThisWeekend, at: morning.AddDate(0, 0, nextBubbleDay(at.Weekday(), time.Saturday))}, + bubbleChoice{name: "Next week", action: bubbleSchedule, slot: hey.BubbleUpNextWeek, at: morning.AddDate(0, 0, nextBubbleDay(at.Weekday(), time.Monday))}, + bubbleChoice{name: "Choose a date…", action: bubbleChooseDate}, + ) + if scheduled || posting.BubbledUp { + p.choices = append(p.choices, bubbleChoice{name: "Cancel bubble-up", action: bubbleCancel}) + } + return p +} + +func nextBubbleDay(from, to time.Weekday) int { return (int(to)-int(from)+6)%7 + 1 } + +func (v *mailView) startBubblePicker() tea.Cmd { + if !v.inThread && !v.searchActive && !v.bundleActive && v.refuseForSelection() { + return nil + } + if v.requests.loading { + return nil + } + posting := v.actionPosting() + if !v.inThread && v.searchActive { + posting = v.searchList.selectedPosting() + } + if !v.inThread && v.bundleActive { + posting = v.bundleList.selectedPosting() + } + if posting == nil || posting.ID == 0 || posting.IsBundle { + v.notice = "Open an individual email thread to bubble it up" + return nil + } + scheduled := posting.BubbleScheduled + for _, box := range v.boxes { + if box.ID == posting.BoxID && box.Kind == mail.KindBox && box.BoxKind == hey.BoxKindBubbleUp { + scheduled = true + } + } + picker := newBubblePicker(*posting, scheduled, time.Now) + v.openModal(picker) + if v.searchActive && posting.BoxID == 0 && !posting.BubbledUp && !posting.BubbleScheduled { + return v.loadBubbleState(picker) + } + return nil +} + +func (p *bubblePicker) handleKey(v *mailView, msg tea.KeyPressMsg) (tea.Cmd, bool) { + if p.unknownState { + if msg.Key().Code == tea.KeyEscape { + if p.lookupCancel != nil { + p.lookupCancel() + } + return nil, false + } + if !p.loading && msg.String() == "ctrl+r" { + return v.loadBubbleState(p), true + } + return nil, true + } + if p.busy { + return nil, true + } + if p.date != nil { + switch msg.Key().Code { + case tea.KeyEscape: + p.date = nil + p.problem = "" + return nil, true + case tea.KeyEnter: + return p.submit(v, bubbleChoice{name: "Choose a date…", action: bubbleChooseDate}), true + } + return p.date.handleKey(msg), true + } + switch msg.Key().Code { + case tea.KeyEscape: + return nil, false + case tea.KeyEnter: + choice := p.choices[p.cursor] + if choice.action == bubbleChooseDate { + p.date = newDateTimePicker(p.now().UTC().AddDate(0, 0, 1), true) + return p.date.focusFirst(), true + } + return p.submit(v, choice), true + } + p.cursor = stepListCursor(p.cursor, len(p.choices), msg) + p.problem = "" + return nil, true +} + +func (p *bubblePicker) submit(v *mailView, choice bubbleChoice) tea.Cmd { + sdk, ctx, id := v.vc.sdk, v.vc.ctx, p.postingID + now := p.now().UTC() + date := "" + if p.date != nil { + at, err := time.Parse("2006-01-02", p.date.date()) + if err != nil || at.Format("2006-01-02") != p.date.date() { + p.problem = "Enter a date as YYYY-MM-DD" + return nil + } + choice.at = at.Add(8 * time.Hour) + if at.Format("2006-01-02") == now.Format("2006-01-02") { + choice.slot = hey.BubbleUpLaterToday + choice.at = at.Add(18 * time.Hour) + } else { + date = at.Format("2006-01-02") + } + } else if choice.slot != "" && now.Format("2006-01-02") != p.openedDay { + p.problem = "The date changed. Close and reopen Bubble up." + return nil + } + if !choice.at.IsZero() && !choice.at.After(now) { + p.problem = "Choose a future date; today's slot is 18:00 UTC" + return nil + } + p.busy = true + p.problem = "" + v.pendingMutations++ + return func() tea.Msg { + var err error + message := "Thread will bubble up" + switch { + case choice.action == bubbleCancel: + err = sdk.Postings().CancelBubbleUp(ctx, id) + message = "Bubble-up canceled; thread returned to the Imbox, marked seen" + case choice.action == bubbleNow: + err = sdk.Postings().BubbleUpNow(ctx, id) + message = "Thread bubbled up" + case date != "": + err = sdk.Postings().ScheduleBubbleUp(ctx, date, id) + default: + err = sdk.Postings().ScheduleBubbleUpFor(ctx, choice.slot, id) + } + return bubbleDoneMsg{picker: p, message: message, err: err} + } +} + +func (v *mailView) bubbleDone(msg bubbleDoneMsg) tea.Cmd { + v.finishMutation() + p := msg.picker + p.busy = false + if msg.err != nil { + p.problem = errorNotice("Could not change bubble-up", msg.err) + return nil + } + if v.modal == p { + v.modal = nil + } + if v.inThread && v.threadPosting.ID == p.postingID { + v.ExitThread() + } + v.notice = msg.message + // Re-read the source instead of guessing its membership and ordering after HEY + // schedules, pops, or immediately resurfaces a thread. + if v.seenActive { + requestID, ctx := v.requests.begin(v.vc.ctx, mailRequestSeen) + v.seenNextPage = "" + v.seenLoadingMore = false + v.seenMoreID++ + return v.fetchSeenPostings(ctx, requestID) + } + if v.searchActive { + return v.requestSearch(v.searchQuery) + } + if v.bundleActive { + if v.bundleContactID != 0 { + return v.requestContactThreads(v.bundleContactID) + } + return v.requestBundle(v.bundlePostingID) + } + return v.reloadPostings() +} + +func (p *bubblePicker) handleMsg(msg tea.Msg) (tea.Cmd, bool) { + if p.date == nil || p.busy { + return nil, false + } + var cmd tea.Cmd + p.date.dateInput, cmd = p.date.dateInput.Update(msg) + return cmd, true +} + +func (p *bubblePicker) draw(v *mailView) string { + var body string + if p.loading { + body = "Loading Bubble Up…" + } else if p.unknownState { + body = "Press Ctrl+R to retry, or Esc to cancel." + } else if p.date != nil { + body = "Date (YYYY-MM-DD, on HEY's UTC calendar)\n" + p.date.view() + "\n\n08:00 UTC; today's date uses 18:00 UTC." + } else { + names := make([]string, len(p.choices)) + for i, choice := range p.choices { + names[i] = choice.name + if !choice.at.IsZero() { + names[i] += " · " + choice.at.Local().Format("Mon Jan 2, 15:04 MST") + } + } + body = strings.Join(modalListRows(names, p.cursor, modalContentWidth(v.vc.width), max(modalContentRows(v.vc.height)-3, 1)), "\n") + } + if p.busy { + body += "\n\nSaving…" + } + if p.problem != "" { + body += "\n\n" + p.problem + } + return overlayModal(v.contentView(), modalFrame("Bubble up", body, v.vc.width), v.vc.width, v.vc.height) +} + +func (p *bubblePicker) helpBindings() []helpBinding { + if p.loading { + return []helpBinding{{"esc", "cancel"}} + } + if p.unknownState { + return []helpBinding{{"ctrl+r", "retry"}, {"esc", "cancel"}} + } + if p.busy { + return []helpBinding{{"", "saving bubble-up…"}} + } + if p.date != nil { + return []helpBinding{{"↑/↓", "change day"}, {"enter", "schedule"}, {"esc", "back"}} + } + return []helpBinding{{"↑/↓", "choose"}, {"enter", "apply"}, {"esc", "cancel"}} +} diff --git a/internal/tui/bubble_state.go b/internal/tui/bubble_state.go new file mode 100644 index 00000000..c9d268f7 --- /dev/null +++ b/internal/tui/bubble_state.go @@ -0,0 +1,102 @@ +package tui + +import ( + "context" + "errors" + "time" + + tea "charm.land/bubbletea/v2" + hey "github.com/basecamp/hey-sdk/go/pkg/hey" + + "github.com/basecamp/hey-cli/internal/mail" +) + +const ( + maxBubbleLookupPages = 64 + bubbleLookupTimeout = 10 * time.Second +) + +type bubbleStateLoadedMsg struct { + picker *bubblePicker + canCancel bool + err error +} + +// Search answers a posting ID but no box or bubble metadata. Resolve membership +// using the same two feeds as hey bubble list, without scanning ordinary Imbox mail. +func (v *mailView) loadBubbleState(p *bubblePicker) tea.Cmd { + p.loading = true + p.unknownState = true + p.problem = "" + ctx, cancel := context.WithTimeout(v.vc.ctx, bubbleLookupTimeout) + p.lookupCancel = cancel + sdk, id := v.vc.sdk, p.postingID + return func() tea.Msg { + defer cancel() + canCancel, err := readBubbleState(ctx, sdk, id) + return bubbleStateLoadedMsg{picker: p, canCancel: canCancel, err: err} + } +} + +func readBubbleState(ctx context.Context, sdk *hey.Client, postingID int64) (bool, error) { + pages := 0 + for _, kind := range []string{hey.BoxKindImbox, hey.BoxKindBubbleUp} { + source := mail.Source{Kind: mail.KindBox, BoxKind: kind} + cursor := "" + visited := make(map[string]bool) + for { + if err := ctx.Err(); err != nil { + return false, err + } + if pages == maxBubbleLookupPages { + return false, errors.New("bubble-up list is too large to check right now") + } + if visited[cursor] { + return false, errors.New("bubble-up paging repeated a cursor") + } + visited[cursor] = true + pages++ + page, err := mail.ReadPage(ctx, sdk, source, cursor) + if err != nil { + return false, err + } + prefixEnded := false + for _, posting := range page.Postings { + if kind == hey.BoxKindImbox && !posting.BubbledUp { + prefixEnded = true + break + } + if posting.Id == postingID { + return true, nil + } + } + if prefixEnded || len(page.Postings) == 0 || page.Cursor == "" { + break + } + cursor = page.Cursor + } + } + return false, nil +} + +func (v *mailView) bubbleStateLoaded(msg bubbleStateLoadedMsg) { + p := msg.picker + if v.modal != p { + return + } + if p.lookupCancel != nil { + p.lookupCancel() + p.lookupCancel = nil + } + p.loading = false + if msg.err != nil { + p.problem = errorNotice("Could not load Bubble Up", msg.err) + return + } + current := newBubblePicker(mail.Posting{ID: p.postingID}, msg.canCancel, p.now) + p.choices = current.choices + p.openedDay = current.openedDay + p.cursor = 0 + p.unknownState = false + p.problem = "" +} diff --git a/internal/tui/bubble_state_test.go b/internal/tui/bubble_state_test.go new file mode 100644 index 00000000..a2e39601 --- /dev/null +++ b/internal/tui/bubble_state_test.go @@ -0,0 +1,215 @@ +package tui + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + hey "github.com/basecamp/hey-sdk/go/pkg/hey" + + "github.com/basecamp/hey-cli/internal/mail" +) + +func TestBubbleSearchResolvesRealMetadata(t *testing.T) { + for _, state := range []string{"ordinary", "scheduled", "bubbled"} { + for _, inThread := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/thread=%v", state, inThread), func(t *testing.T) { + var reads []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.Method != http.MethodGet && r.URL.Path != "/postings/seen.json" && r.URL.Path != "/postings/bubble_up.json" { + t.Errorf("lookup mutated mail: %s", r.Method) + } + reads = append(reads, r.URL.RequestURI()) + switch r.URL.Path { + case "/advanced_search.json": + fmt.Fprint(w, `{"matches":[{"posting_id":987,"topic":{"id":654,"name":"Hotel newsletter"}}]}`) + case "/topics/654.json": + fmt.Fprint(w, `{"id":654,"entries":[{"id":765,"kind":"message","summary":"Hotel newsletter"}]}`) + case "/topics/654/entries.json": + fmt.Fprint(w, `[{"id":765,"kind":"message","summary":"Hotel newsletter"}]`) + case "/messages/765.json": + fmt.Fprint(w, `{"id":765,"content":"
Hotel newsletter
"}`) + case "/postings/bubble_up.json": + if r.Method != http.MethodDelete || r.URL.Query().Get("posting_ids") != "987" { + t.Errorf("cancel targeted the wrong resource: %s %s", r.Method, r.URL) + } + w.WriteHeader(http.StatusOK) + case "/postings/seen.json": + w.WriteHeader(http.StatusOK) + case "/imbox.json": + if state == "bubbled" { + fmt.Fprint(w, `{"postings":[{"id":987,"bubbled_up":true}]}`) + } else { + // The ordinary prefix ends here: do not follow this cursor. + fmt.Fprint(w, `{"postings":[{"id":456}],"next_history_url":"https://app.hey.com/imbox?page=unneeded"}`) + } + case "/bubble_up.json": + if state == "scheduled" { + if r.URL.Query().Get("page") == "next / opaque" { + fmt.Fprint(w, `{"postings":[{"id":987}]}`) + } else { + fmt.Fprint(w, `{"postings":[{"id":456}],"next_history_url":"https://app.hey.com/bubble_up?page=next+%2F+opaque"}`) + } + } else { + fmt.Fprint(w, `{"postings":[]}`) + } + default: + t.Errorf("unexpected read %s", r.URL) + http.NotFound(w, r) + } + })) + defer server.Close() + v := mailWithPostings() + v.vc.sdk = hey.NewClient(&hey.Config{BaseURL: server.URL}, &hey.StaticTokenProvider{Token: "test-token"}, hey.WithMaxRetries(0)) + v.postingList.toggleSelected() + v.HandleContentKey(keyPress("s")) + modalOf[*mailSearchForm](v).input.SetValue("newsletter") + deliverToView(v, v.HandleContentKey(keyPress("enter"))) + if !v.searchActive || len(v.searchList.postings) != 1 { + t.Fatal("real search response did not open results") + } + if inThread { + next, _ := v.Update(v.openSelected()()) + deliverToView(v, next) + if !v.inThread || v.threadPosting.ID != 987 { + t.Fatal("search result did not open its thread") + } + } + cmd := v.HandleContentKey(keyPress("w")) + p := modalOf[*bubblePicker](v) + if cmd == nil || p == nil || !p.loading || p.postingID != 987 { + t.Fatal("hidden selection blocked the visible search target") + } + if v.pendingMutations != 0 { + t.Fatal("lookup counted as a mutation") + } + v.Update(cmd()) + if p.loading || p.unknownState || p.problem != "" { + t.Fatalf("lookup did not finish: %+v", p) + } + hasCancel := p.choices[len(p.choices)-1].action == bubbleCancel + if hasCancel != (state != "ordinary") { + t.Fatalf("cancel=%v for %s; reads=%v", hasCancel, state, reads) + } + if len(v.postingList.selectedIDs()) != 1 { + t.Fatal("lookup cleared the hidden inbox selection") + } + if hasCancel { + p.cursor = len(p.choices) - 1 + cmd := v.HandleContentKey(keyPress("enter")) + if cmd == nil { + t.Fatal("cancel was not dispatched") + } + if msg := cmd().(bubbleDoneMsg); msg.err != nil { + t.Fatal(msg.err) + } + } + for _, read := range reads { + if strings.Contains(read, "unneeded") { + t.Fatal("scanned ordinary Imbox mail") + } + } + }) + } + } +} + +func TestBubbleBundleIgnoresHiddenSelection(t *testing.T) { + v := mailWithPostings() + v.postingList.toggleSelected() + v.bundleActive = true + v.bundleList.setPostings([]mail.Posting{{ID: 987, BoxID: 1}}) + v.HandleContentKey(keyPress("w")) + if p := modalOf[*bubblePicker](v); p == nil || p.postingID != 987 { + t.Fatal("hidden inbox selection blocked bundle thread") + } +} + +func TestBubbleLookupFailureRetryAndDismissal(t *testing.T) { + fail := true + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if fail { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + fmt.Fprint(w, `{"postings":[{"id":987,"bubbled_up":true}]}`) + })) + defer server.Close() + v := mailWithPostings() + v.vc.sdk = hey.NewClient(&hey.Config{BaseURL: server.URL}, &hey.StaticTokenProvider{Token: "test-token"}, hey.WithMaxRetries(0)) + p := newBubblePicker(mail.Posting{ID: 987}, false, bubbleClock) + v.openModal(p) + v.Update(v.loadBubbleState(p)()) + if p.loading || !p.unknownState || p.problem == "" { + t.Fatal("failure silently hid cancellation") + } + if cmd := v.HandleContentKey(keyPress("enter")); cmd != nil || v.pendingMutations != 0 { + t.Fatal("unknown state permitted mutation") + } + fail = false + deliverToView(v, v.HandleContentKey(keyPress("ctrl+r"))) + if p.unknownState || p.choices[len(p.choices)-1].action != bubbleCancel { + t.Fatal("retry did not recover cancellation") + } + cmd := v.loadBubbleState(p) + v.HandleContentKey(keyPress("esc")) + if v.modal != nil { + t.Fatal("Escape did not dismiss loading picker") + } + replacement := newBubblePicker(mail.Posting{ID: 456}, false, bubbleClock) + v.openModal(replacement) + msg := cmd().(bubbleStateLoadedMsg) + if !errors.Is(msg.err, context.Canceled) { + t.Fatalf("lookup was not canceled: %v", msg.err) + } + v.Update(msg) + v.Update(bubbleStateLoadedMsg{picker: p, canCancel: true}) + if v.modal != replacement || replacement.choices[len(replacement.choices)-1].action == bubbleCancel { + t.Fatal("stale result affected replacement picker") + } +} + +func TestBubbleLookupBounds(t *testing.T) { + for _, mode := range []string{"cycle", "page cap", "canceled"} { + t.Run(mode, func(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + calls++ + cursor := "repeated" + if mode == "page cap" { + cursor = fmt.Sprint(calls) + } + json.NewEncoder(w).Encode(map[string]any{"postings": []map[string]any{{"id": 456, "bubbled_up": true}}, "next_history_url": "https://app.hey.com/imbox?page=" + cursor}) + })) + defer server.Close() + sdk := hey.NewClient(&hey.Config{BaseURL: server.URL}, &hey.StaticTokenProvider{Token: "test-token"}, hey.WithMaxRetries(0)) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if mode == "canceled" { + cancel() + } + found, err := readBubbleState(ctx, sdk, 987) + if found || err == nil { + t.Fatal("incomplete read reported a known state") + } + want := 2 + if mode == "page cap" { + want = maxBubbleLookupPages + } + if mode == "canceled" { + want = 0 + } + if calls != want { + t.Fatalf("read %d pages, want %d", calls, want) + } + }) + } +} diff --git a/internal/tui/bubble_test.go b/internal/tui/bubble_test.go new file mode 100644 index 00000000..5cfd92bc --- /dev/null +++ b/internal/tui/bubble_test.go @@ -0,0 +1,301 @@ +package tui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + hey "github.com/basecamp/hey-sdk/go/pkg/hey" + + "github.com/basecamp/hey-cli/internal/mail" +) + +func bubbleClock() time.Time { return time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) } + +func TestBubblePickerOpensFromListAndThread(t *testing.T) { + for _, inThread := range []bool{false, true} { + v := mailWithPostings() + v.inThread = inThread + if inThread { + v.threadPosting = v.postingList.postings[1] + } + v.HandleContentKey(keyPress("w")) + p := modalOf[*bubblePicker](v) + if p == nil { + t.Fatal("w did not open the picker") + } + want := v.postingList.postings[0].ID + if inThread { + want = v.threadPosting.ID + } + if p.postingID != want { + t.Fatalf("picker posting = %d, want %d", p.postingID, want) + } + if screen := v.View(); !strings.Contains(plainText(screen), "Bubble up") { + t.Fatal("picker not rendered") + } + v.HandleContentKey(keyPress("esc")) + if v.modal != nil { + t.Fatal("Escape did not close the picker") + } + } +} + +func TestBubblePickerRefusesBundlesAndSelections(t *testing.T) { + v := mailWithPostings() + v.postingList.postings[0].IsBundle = true + v.HandleContentKey(keyPress("w")) + if v.modal != nil { + t.Fatal("offered bubble-up for a bundle") + } + v.postingList.postings[0].IsBundle = false + v.postingList.toggleSelected() + v.HandleContentKey(keyPress("w")) + if v.modal != nil { + t.Fatal("offered single-thread action for a selection") + } +} + +func TestBubblePresetsAndCancellation(t *testing.T) { + p := newBubblePicker(mail.Posting{ID: 123}, false, bubbleClock) + wants := map[string]string{"Later today": "2026-11-20T18:00:00Z", "Tomorrow": "2026-11-21T08:00:00Z", "This weekend": "2026-11-21T08:00:00Z", "Next week": "2026-11-23T08:00:00Z"} + for _, c := range p.choices { + if want, ok := wants[c.name]; ok { + if c.at.Format(time.RFC3339) != want { + t.Errorf("%s at %s, want %s", c.name, c.at, want) + } + delete(wants, c.name) + } + if c.name == "Cancel bubble-up" { + t.Error("offered cancellation for unscheduled mail") + } + } + if len(wants) != 0 { + t.Fatalf("missing choices %v", wants) + } + for _, post := range []mail.Posting{{ID: 123, BubbledUp: true}, {ID: 123, BubbleScheduled: true}} { + p = newBubblePicker(post, post.BubbleScheduled, bubbleClock) + if p.choices[len(p.choices)-1].name != "Cancel bubble-up" { + t.Fatal("missing cancellation") + } + } + late := newBubblePicker(mail.Posting{ID: 123}, false, func() time.Time { return bubbleClock().Add(8 * time.Hour) }) + for _, c := range late.choices { + if c.name == "Later today" { + t.Fatal("offered past slot") + } + } + if nextBubbleDay(time.Saturday, time.Saturday) != 7 || nextBubbleDay(time.Monday, time.Monday) != 7 { + t.Fatal("next weekday should be in the future") + } +} + +func TestBubbleRequestsAndFailureRetry(t *testing.T) { + for _, name := range []string{"Now", "Later today", "Tomorrow", "This weekend", "Next week", "Choose a date…", "Cancel bubble-up"} { + t.Run(name, func(t *testing.T) { + calls := 0 + status := http.StatusUnprocessableEntity + var path, method string + var body struct { + PostingIDs []int64 `json:"posting_ids"` + Slot string `json:"slot"` + Date string `json:"date"` + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + path = r.URL.Path + method = r.Method + if r.Method == http.MethodPost { + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + } + w.WriteHeader(status) + })) + defer server.Close() + v := mailWithPostings() + v.vc.sdk = hey.NewClient(&hey.Config{BaseURL: server.URL}, &hey.StaticTokenProvider{Token: "test-token"}, hey.WithMaxRetries(0)) + p := newBubblePicker(mail.Posting{ID: 123}, true, bubbleClock) + v.openModal(p) + for i, c := range p.choices { + if c.name == name { + p.cursor = i + } + } + if name == "Choose a date…" { + v.HandleContentKey(keyPress("enter")) + p.date.dateInput.SetValue("2026-12-04") + } + cmd := v.HandleContentKey(keyPress("enter")) + if cmd == nil || !p.busy || v.pendingMutations != 1 { + t.Fatal("no pending request") + } + if duplicate := v.HandleContentKey(keyPress("enter")); duplicate != nil { + t.Fatal("duplicate dispatch") + } + v.Update(cmd()) + if calls != 1 || v.modal != p || p.problem == "" || p.busy || v.pendingMutations != 0 { + t.Fatal("failure did not preserve retryable picker") + } + if name == "Cancel bubble-up" { + if method != http.MethodDelete || !strings.HasPrefix(path, "/postings/bubble_up") { + t.Fatalf("cancel request = %s %s", method, path) + } + } else { + if len(body.PostingIDs) != 1 || body.PostingIDs[0] != 123 { + t.Fatalf("wrong target: %+v", body) + } + if name == "Now" && path != "/postings/bulk_bubble_up_now.json" { + t.Fatal(path) + } + if name == "Choose a date…" && (body.Date != "2026-12-04" || body.Slot != "custom") { + t.Fatalf("custom payload = %+v", body) + } + slots := map[string]string{"Later today": "today", "Tomorrow": "tomorrow", "This weekend": "weekend", "Next week": "next_week"} + if want, ok := slots[name]; ok && body.Slot != want { + t.Fatalf("slot = %s want %s", body.Slot, want) + } + } + status = http.StatusOK + cmd = v.HandleContentKey(keyPress("enter")) + refresh, _ := v.Update(cmd()) + if calls != 2 || v.modal != nil || v.pendingMutations != 0 || refresh == nil { + t.Fatal("success did not close picker and refresh") + } + }) + } +} + +func TestBubbleCustomDateValidationAndBack(t *testing.T) { + v := mailWithPostings() + p := newBubblePicker(mail.Posting{ID: 123}, false, bubbleClock) + v.openModal(p) + for i, c := range p.choices { + if c.name == "Choose a date…" { + p.cursor = i + } + } + v.HandleContentKey(keyPress("enter")) + for _, date := range []string{"2026-02-30", "2026-11-19", "not a date"} { + p.date.dateInput.SetValue(date) + if cmd := v.HandleContentKey(keyPress("enter")); cmd != nil || p.problem == "" || p.busy { + t.Fatalf("accepted invalid date %s", date) + } + } + v.HandleContentKey(keyPress("esc")) + if v.modal != p || p.date != nil { + t.Fatal("Escape should return to preset menu") + } + p.now = func() time.Time { return bubbleClock().AddDate(0, 0, 1) } + p.cursor = 1 + if cmd := v.HandleContentKey(keyPress("enter")); cmd != nil || !strings.Contains(p.problem, "date changed") { + t.Fatal("stale preset accepted after midnight") + } +} + +func TestBubblePickerUsesOverlayRowAndScheduledMetadata(t *testing.T) { + for _, source := range []string{"bundle", "seen"} { + t.Run(source, func(t *testing.T) { + v := mailWithPostings() + rows := []mail.Posting{{ID: 987, BubbleScheduled: true}} + switch source { + case "bundle": + v.bundleActive = true + v.bundleList.setPostings(rows) + case "seen": + v.seenActive = true + v.seenList.setPostings(rows) + } + v.HandleContentKey(keyPress("w")) + p := modalOf[*bubblePicker](v) + if p == nil || p.postingID != 987 || p.choices[len(p.choices)-1].action != bubbleCancel { + t.Fatalf("%s picker ignored its own row", source) + } + }) + } +} + +func TestBubbleCustomTodayUsesEveningSlot(t *testing.T) { + var slot, date string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body struct { + Slot string `json:"slot"` + Date string `json:"date"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + slot, date = body.Slot, body.Date + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + v := mailWithPostings() + v.vc.sdk = hey.NewClient(&hey.Config{BaseURL: server.URL}, &hey.StaticTokenProvider{Token: "test-token"}, hey.WithMaxRetries(0)) + p := newBubblePicker(mail.Posting{ID: 123}, false, bubbleClock) + p.date = newDateTimePicker(bubbleClock(), true) + cmd := p.submit(v, bubbleChoice{action: bubbleChooseDate}) + if cmd == nil { + t.Fatal("today's future evening slot was refused") + } + v.Update(cmd()) + if slot != "today" || date != "" { + t.Fatalf("today request slot=%q date=%q", slot, date) + } + p.now = func() time.Time { return bubbleClock().Add(8 * time.Hour) } + if cmd := p.submit(v, bubbleChoice{action: bubbleChooseDate}); cmd != nil { + t.Fatal("accepted today's elapsed evening slot") + } +} + +func TestBubblePickerPreservesItsOpeningScreen(t *testing.T) { + for _, screen := range []string{"inbox", "search", "bundle", "seen", "thread"} { + t.Run(screen, func(t *testing.T) { + v := modalViewWithPostings(t) + rows := []mail.Posting{{ID: 987, TopicID: 654, BoxID: 1, Name: "Hotel reservation search result"}} + switch screen { + case "search": + v.searchActive = true + v.searchList.setPostings(rows) + case "bundle": + v.bundleActive = true + v.bundleList.setPostings(rows) + case "seen": + v.seenActive = true + v.seenList.setPostings(rows) + case "thread": + v.inThread = true + v.threadPosting = rows[0] + v.threadNotice = "Some messages could not be loaded" + v.topicViewport.SetContent(strings.Repeat("Hotel reservation details\n", 80)) + } + v.vc.width, v.vc.height = 100, 30 + v.Resize(100, 30) + if screen == "thread" { + v.topicViewport.SetYOffset(7) + } + before := v.View() + offset := v.topicViewport.YOffset() + v.HandleContentKey(keyPress("w")) + if modalOf[*bubblePicker](v) == nil { + t.Fatal("picker did not open") + } + // The centered picker leaves the first rows visible. They must belong to + // the screen that opened it, including a thread's partial-read notice. + first := strings.TrimRight(strings.Split(stripANSI(before), "\n")[0], " ") + if !strings.HasPrefix(stripANSI(v.View()), first) { + t.Fatalf("%s background replaced: %q", screen, stripANSI(v.View())) + } + v.HandleContentKey(keyPress("esc")) + if v.modal != nil || v.View() != before || v.topicViewport.YOffset() != offset { + t.Fatal("dismissing picker changed the underlying screen or scroll position") + } + }) + } +} + +func TestBubblePickerPreservesScrollThroughModel(t *testing.T) { + testPickerScrollThroughModel(t, "w") +} diff --git a/internal/tui/mail.go b/internal/tui/mail.go index 701aa49c..004294f8 100644 --- a/internal/tui/mail.go +++ b/internal/tui/mail.go @@ -787,6 +787,13 @@ func (v *mailView) Update(msg tea.Msg) (tea.Cmd, bool) { } return notify("Opened attachment " + msg.filename), true + case bubbleStateLoadedMsg: + v.bubbleStateLoaded(msg) + return nil, true + + case bubbleDoneMsg: + return v.bubbleDone(msg), true + case postingActionDoneMsg: v.finishMutation() // A move of the open thread leaves it on screen in its new box, so later @@ -944,6 +951,11 @@ func (v *mailView) View() string { if v.modal != nil { return v.modal.draw(v) } + return v.contentView() +} + +// contentView draws the current mail screen without its temporary picker. +func (v *mailView) contentView() string { if v.inThread { v.fitThreadViewport() var lines []string @@ -1065,6 +1077,7 @@ func (v *mailView) HelpBindings() []helpBinding { } bindings = append(bindings, helpBinding{"v", "move"}, + helpBinding{"w", "bubble up"}, folderBinding, helpBinding{"u", "unseen"}, helpBinding{"i", "imbox"}, @@ -1153,6 +1166,7 @@ func (v *mailView) HelpBindings() []helpBinding { {"r", "reply"}, {"f", "forward"}, {"v", "move"}, + {"w", "bubble up"}, folderBinding, collectionBinding, {"e", "seen"}, @@ -1383,6 +1397,10 @@ func (v *mailView) HandleContentKey(msg tea.KeyPressMsg) tea.Cmd { return cmd } + if !v.inThread && (msg.String() == "w" || msg.String() == "W") { + return v.startBubblePicker() + } + if v.inThread { if cmd, handled := v.handleLinkKey(msg); handled { return cmd @@ -1394,6 +1412,8 @@ func (v *mailView) HandleContentKey(msg tea.KeyPressMsg) tea.Cmd { } switch msg.String() { + case "w", "W": + return v.startBubblePicker() case "r", "R": if v.topicID != 0 { return v.loadReplyContext(v.topicID, v.topicName) diff --git a/internal/tui/picker_scroll_test.go b/internal/tui/picker_scroll_test.go new file mode 100644 index 00000000..63e55651 --- /dev/null +++ b/internal/tui/picker_scroll_test.go @@ -0,0 +1,80 @@ +package tui + +import ( + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + + "github.com/basecamp/hey-cli/internal/htmlutil" +) + +func testPickerScrollThroughModel(t *testing.T, key string) { + t.Helper() + for _, position := range []string{"middle", "bottom"} { + for _, selected := range []bool{false, true} { + name := position + if selected { + name += "/selected-link" + } + t.Run(name, func(t *testing.T) { + m := openLinkThreadThroughModel(t) + v := m.mailView + v.pendingMutations = 0 + v.entries[0].Body = htmlutil.ToMarkdown(`` + strings.Repeat("Travel plans and hotel reservations.
", 100)) + v.rebuildTopicContent() + updated, _ := m.Update(tea.WindowSizeMsg{Width: 60, Height: 30}) + m = updated.(model) + if selected { + updated, _ = m.Update(keyPress("tab")) + m = updated.(model) + footer, visible := m.linkFooter() + if !visible || !strings.Contains(footer, "\n") { + t.Fatal("expected a wrapping link footer") + } + } + if position == "bottom" { + for range 30 { + updated, _ = m.Update(keyPress("pgdown")) + m = updated.(model) + } + } else { + for range 35 { + updated, _ = m.Update(keyPress("down")) + m = updated.(model) + } + } + offset := v.topicViewport.YOffset() + if offset == 0 { + t.Fatal("thread did not scroll") + } + link, linkKey := v.selectedLink, v.selectedLinkKey + before := m.View().Content + updated, _ = m.Update(keyPress(key)) + m = updated.(model) + if v.modal == nil { + t.Fatal("picker did not open") + } + // A taller background may clamp at the bottom while the picker is open. + want := min(offset, max(v.topicViewport.TotalLineCount()-v.topicViewport.Height(), 0)) + if got := v.topicViewport.YOffset(); got != want { + t.Fatalf("opening picker offset = %d, want %d", got, want) + } + updated, _ = m.Update(keyPress("esc")) + m = updated.(model) + if v.modal != nil { + t.Fatal("picker did not close") + } + if got := v.topicViewport.YOffset(); got != offset { + t.Errorf("dismissal offset = %d, want %d", got, offset) + } + if v.selectedLink != link || v.selectedLinkKey != linkKey { + t.Error("picker changed link selection") + } + if got := m.View().Content; got != before { + t.Error("dismissal changed the rendered screen") + } + }) + } + } +} diff --git a/internal/tui/tui.go b/internal/tui/tui.go index 38618ddd..8e98b1b1 100644 --- a/internal/tui/tui.go +++ b/internal/tui/tui.go @@ -72,6 +72,9 @@ type model struct { calendarView *calendarView journalView *journalView + // Keep the reading position while modal help changes the thread viewport. + mailModalScroll *int + // The Screener, opened over the mail section with ctrl+s screenerView *screenerView @@ -311,6 +314,8 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return opened, tea.Batch(initCmd, openCmd) case tea.WindowSizeMsg: + // A terminal resize lays out the selected link at its new dimensions. + m.mailModalScroll = nil m.width = msg.Width m.height = msg.Height m.vc.width = msg.Width @@ -802,12 +807,26 @@ func (m *model) updateHelpBindings() { bindings = append(bindings, helpBinding{"ctrl+a", description}) } } + // Opening a modal removes the link footer and changes the help height. + // Save the offset before that resize can reveal an old link or clamp the + // viewport near the bottom; restore it again when the modal closes. + mailThread := m.activeView == m.mailView && m.mailView.inThread + if mailThread && m.mailView.modal != nil && m.mailModalScroll == nil { + offset := m.mailView.topicViewport.YOffset() + m.mailModalScroll = &offset + } m.help.setBindings(bindings) contentHeight := m.contentHeight() if contentHeight != m.vc.height { m.vc.height = contentHeight m.activeView.Resize(m.vc.width, contentHeight) } + if mailThread && m.mailModalScroll != nil { + m.mailView.topicViewport.SetYOffset(*m.mailModalScroll) + } + if !mailThread || m.mailView.modal == nil { + m.mailModalScroll = nil + } } // linkFooter is the link status as it goes on screen. A destination that wraps onto