From a9a35839dcfb8a656f042afde0e8dabe7f7a4e93 Mon Sep 17 00:00:00 2001 From: Elija Sorensen <3824702+WhiskeyTuesday@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:10:39 -0700 Subject: [PATCH 1/3] Add a Trash tab and restore action to the TUI --- docs/architecture/mail-sources-and-paging.md | 11 + docs/tui.md | 11 + go.mod | 2 + internal/mail/page.go | 34 ++- internal/mail/source.go | 5 +- internal/tui/collections_test.go | 2 +- internal/tui/mail.go | 70 ++++- internal/tui/mail_test.go | 10 +- internal/tui/move.go | 2 +- internal/tui/trash.go | 114 ++++++++ internal/tui/trash_test.go | 259 +++++++++++++++++++ internal/tui/tui_test.go | 2 +- 12 files changed, 499 insertions(+), 23 deletions(-) create mode 100644 internal/tui/trash.go create mode 100644 internal/tui/trash_test.go diff --git a/docs/architecture/mail-sources-and-paging.md b/docs/architecture/mail-sources-and-paging.md index 6fa6636f3..c215b2331 100644 --- a/docs/architecture/mail-sources-and-paging.md +++ b/docs/architecture/mail-sources-and-paging.md @@ -125,3 +125,14 @@ and never carries the cursor back to the top. All four sections wait on a `requestLane` — the journal's is one kind deep, since its whole question is which day is selected — so "is this answer still the one the reader asked for" has one answer in the TUI rather than one per section. + +## Trash is a topic source + +The TUI adds a virtual `KindTrash` source with no box ID. `mail.ReadPage` reads it +through the SDK's `Topics.GetTrashPage`, preserving the opaque `Link` cursor. The +adapter supplies topic IDs as row identities and `readPostingsPage` keeps those as +`TopicID`; they are never posting IDs. Trash rows are already seen so opening one +cannot send a posting observation. All posting mutations are blocked in Trash. +Restoring calls `Topics.Restore` with the topic ID, and removes the row only after +success. A restore response received after switching sources cannot remove a row +from the new source. Trash is excluded from box move destinations. diff --git a/docs/tui.md b/docs/tui.md index 22045222f..0ddca5f99 100644 --- a/docs/tui.md +++ b/docs/tui.md @@ -173,6 +173,17 @@ The Screener keeps up too. When a first-time sender writes, the count above the changes on its own, and if you have The Screener open the new sender appears in the queue without moving your place in it. +## Trash + +Press `0` or select **Trash** at the end of the mail tab row. The list grows as you +scroll. Enter reads a trashed thread; `i` restores the selected or open thread through +HEY's normal restore action. A successful restore removes it from the Trash list and +closes its open reader. A failed restore leaves it available to retry. + +Restore acts on one thread at a time. Trashed threads can be read and their attachments +opened or saved, but filing, replies, labels, bulk selection and trashing again are +unavailable until they are restored. Permanent deletion and Empty Trash are not exposed. + ## The Screener Press Ctrl+S from the mail list to open The Screener. When senders are waiting, the mail diff --git a/go.mod b/go.mod index 91d4e5bf4..070afd301 100644 --- a/go.mod +++ b/go.mod @@ -125,3 +125,5 @@ require ( google.golang.org/protobuf v1.36.12 // indirect k8s.io/klog/v2 v2.140.0 // indirect ) + +replace github.com/basecamp/hey-sdk/go => /home/ers/Work/hey-sdk/go diff --git a/internal/mail/page.go b/internal/mail/page.go index 0f1905fe1..d7557ca6e 100644 --- a/internal/mail/page.go +++ b/internal/mail/page.go @@ -10,8 +10,8 @@ import ( ) // Page is one page of a source's postings. Cursor is whatever the next read needs to -// carry on where this page stopped — a geared_pagination cursor for a label or a -// collection, HEY's own next_history_url for a box — and is empty at the end of the +// carry on where this page stopped — a geared_pagination cursor for a label, a +// collection or Trash, HEY's own next_history_url for a box — and is empty at the end of the // list. Total is HEY's count of everything in the source, zero where it does not say. type Page struct { Postings []generated.Posting @@ -23,6 +23,8 @@ type Page struct { // first page. func ReadPage(ctx context.Context, client *hey.Client, source Source, cursor string) (Page, error) { switch source.Kind { + case KindTrash: + return readTrashPage(ctx, client, cursor) case KindBox: return readBoxPage(ctx, client, source, cursor) case KindFolder: @@ -208,3 +210,31 @@ func readCollectionPage(ctx context.Context, client *hey.Client, source Source, } return Page{Postings: result.Collection.Postings, Cursor: result.NextPage, Total: result.TotalCount}, nil } + +// Trash serves topics, rather than postings. Their topic IDs are list identities +// only: callers must restore through Topics, never dispatch a posting mutation. +func readTrashPage(ctx context.Context, client *hey.Client, cursor string) (Page, error) { + var params *generated.GetTrashTopicsParams + if cursor != "" { + params = &generated.GetTrashTopicsParams{Page: &cursor} + } + result, err := client.Topics().GetTrashPage(ctx, params) + if err != nil { + return Page{}, err + } + if result == nil || result.Topics == nil { + return Page{}, fmt.Errorf("mail: Trash answered no page") + } + page := Page{Cursor: result.NextPage} + for _, topic := range result.Topics.Topics { + created := topic.LatestEntry.CreatedAt + if created.IsZero() { + created = topic.CreatedAt + } + page.Postings = append(page.Postings, generated.Posting{ + Id: topic.Id, AppUrl: topic.AppUrl, Name: topic.Name, Summary: topic.LatestEntry.Summary, + Creator: topic.Creator, CreatedAt: created, Seen: true, + }) + } + return page, nil +} diff --git a/internal/mail/source.go b/internal/mail/source.go index 64f0e1f28..746ac136f 100644 --- a/internal/mail/source.go +++ b/internal/mail/source.go @@ -1,5 +1,5 @@ // Package mail reads the places HEY keeps postings — a box, a label, a collection, a -// bundle's unseen threads, a contact's threads — through one Source type and one page +// bundle's unseen threads, a contact's threads, or Trash — through one Source type and one page // read, so a caller never has to know which endpoint a source is served by. package mail @@ -19,11 +19,12 @@ const ( KindCollection Kind = "collection" KindBundle Kind = "bundle" KindContact Kind = "contact" + KindTrash Kind = "trash" ) // Source is a place postings are read from. BoxKind carries HEY's own kind for a box // (hey.BoxKindImbox and friends), which is what tells the named box routes apart; it is -// empty for a label or a collection. +// empty for the other source kinds. type Source struct { Kind Kind ID int64 diff --git a/internal/tui/collections_test.go b/internal/tui/collections_test.go index 418c079e7..8d923fe6a 100644 --- a/internal/tui/collections_test.go +++ b/internal/tui/collections_test.go @@ -84,7 +84,7 @@ func TestMailViewLoadsAndPagesCollections(t *testing.T) { loaded := runCmd(v.Init()).(mailSourcesLoadedMsg) v.Update(loaded) - if len(v.boxes) != 2 || v.boxes[1].Kind != mail.KindCollection { + if len(v.boxes) != 3 || v.boxes[1].Kind != mail.KindCollection { t.Fatalf("sources = %+v", v.boxes) } if cmd := v.SubnavRight(); cmd == nil || !v.seenActive { diff --git a/internal/tui/mail.go b/internal/tui/mail.go index 701aa49c2..116b99e6f 100644 --- a/internal/tui/mail.go +++ b/internal/tui/mail.go @@ -279,7 +279,9 @@ type mailLinkBody struct { } type mailView struct { - vc *viewContext + threadFromTrash bool + trashRestoreID int64 + vc *viewContext boxes []mail.Source boxIndex int @@ -572,6 +574,7 @@ func (v *mailView) Update(msg tea.Msg) (tea.Cmd, bool) { if opened := v.openedPosting(msg.postingID); opened != nil { v.threadPosting = *opened } + v.threadFromTrash = msg.postingID != 0 && v.currentSourceKind() == mail.KindTrash && !v.searchActive && !v.bundleActive && !v.seenActive v.threadBoxKind = v.postingBoxKind(v.threadPosting) v.topicName = msg.title v.entries = msg.entries @@ -787,6 +790,9 @@ func (v *mailView) Update(msg tea.Msg) (tea.Cmd, bool) { } return notify("Opened attachment " + msg.filename), true + case trashRestoredMsg: + return v.trashRestored(msg), true + case postingActionDoneMsg: v.finishMutation() // A move of the open thread leaves it on screen in its new box, so later @@ -1092,7 +1098,7 @@ func (v *mailView) HelpBindings() []helpBinding { bindings = append(bindings, helpBinding{"enter", "open attachment"}) } } - return bindings + return v.trashHelp(bindings) } if v.searchActive { return []helpBinding{{"enter", "open"}, {"/", "new search"}} @@ -1130,7 +1136,7 @@ func (v *mailView) HelpBindings() []helpBinding { if v.lastBulkReplyID != 0 { bindings = append(bindings, helpBinding{"ctrl+u", "undo bulk reply"}) } - return modifiersLast(bindings) + return modifiersLast(v.trashHelp(bindings)) } ignoreBinding := helpBinding{"-", "ignore"} if selected := v.postingList.selectedPosting(); selected != nil && selected.Muted { @@ -1184,7 +1190,7 @@ func (v *mailView) HelpBindings() []helpBinding { if v.lastBulkReplyID != 0 { bindings = append(bindings, helpBinding{"ctrl+u", "undo bulk reply"}) } - return modifiersLast(bindings) + return modifiersLast(v.trashHelp(bindings)) } func (v *mailView) SubnavItems() ([]navItem, int, string, bool) { @@ -1251,6 +1257,12 @@ func (v *mailView) SubnavItems() ([]navItem, int, string, bool) { selected = len(items) - 1 } } + if v.trashIndex() >= 0 { + items = append(items, navItem{shortcut: "0", label: "Trash"}) + if v.currentSourceKind() == mail.KindTrash && !v.seenActive { + selected = len(items) - 1 + } + } return items, selected, label, true } @@ -1258,7 +1270,7 @@ func (v *mailView) SubnavItems() ([]navItem, int, string, bool) { func (v *mailView) tabBoxIndexes() []int { indexes := make([]int, 0, len(v.boxes)) for i, source := range v.boxes { - if !isOrganizedMailSource(source.Kind) { + if source.Kind == mail.KindBox { indexes = append(indexes, i) } } @@ -1308,6 +1320,16 @@ func (v *mailView) SubnavLeft() tea.Cmd { return nil } switch v.currentSourceKind() { + case mail.KindTrash: + if v.hasCollections() { + v.openCollections() + return nil + } + if v.hasLabels() { + v.openLabels() + return nil + } + return v.openPreviouslySeen() case mail.KindCollection: if v.hasLabels() { v.openLabels() @@ -1338,20 +1360,23 @@ func (v *mailView) SubnavRight() tea.Cmd { v.openLabels() } else if v.hasCollections() { v.openCollections() + } else { + return v.switchBox(v.trashIndex()) } return nil } switch v.currentSourceKind() { + case mail.KindTrash: + return nil case mail.KindFolder: if v.hasCollections() { v.openCollections() } else { - v.openLabels() + return v.switchBox(v.trashIndex()) } return nil case mail.KindCollection: - v.openCollections() - return nil + return v.switchBox(v.trashIndex()) case mail.KindBox: tabIndexes := v.tabBoxIndexes() for i, boxIndex := range tabIndexes { @@ -1387,6 +1412,9 @@ func (v *mailView) HandleContentKey(msg tea.KeyPressMsg) tea.Cmd { if cmd, handled := v.handleLinkKey(msg); handled { return cmd } + if cmd, handled := v.handleTrashKey(msg.String()); handled { + return cmd + } // Enter opens what is selected: a link once Tab has picked one, which // handleLinkKey has already answered, and otherwise the attachment. if msg.Key().Code == tea.KeyEnter && len(v.attachments) > 0 { @@ -1430,6 +1458,10 @@ func (v *mailView) HandleContentKey(msg tea.KeyPressMsg) tea.Cmd { return cmd } + if cmd, handled := v.handleTrashKey(msg.String()); handled { + return cmd + } + if v.searchActive { switch msg.Key().Code { case tea.KeyUp: @@ -1854,6 +1886,8 @@ func (v *mailView) handleBoxShortcut(key string) tea.Cmd { v.openCollections() return func() tea.Msg { return nil } } + case "0": + return v.switchBox(v.trashIndex()) case "9": return v.openPreviouslySeen() } @@ -1983,6 +2017,9 @@ func sourceIndex(sources []mail.Source, id int64, kind mail.Kind) int { func (v *mailView) applySources(sources []mail.Source) tea.Cmd { currentID, currentKind := v.currentSourceIdentity() v.boxes = orderBoxes(sources) + if len(sources) > 0 && v.trashIndex() < 0 { + v.boxes = append(v.boxes, mail.Source{Kind: mail.KindTrash, Name: "Trash"}) + } v.requests.loading = false if len(v.boxes) == 0 { return nil @@ -2192,6 +2229,11 @@ func (v *mailView) requestTopic(boxID, topicID, postingID int64, title string) t } func (v *mailView) postingIndex(postingID int64) int { + // Trash identities are topic IDs; a posting completion from an overlaid search + // must never match one just because its numeric ID happens to be the same. + if v.currentSourceKind() == mail.KindTrash { + return -1 + } return postingIndexIn(v.postingList.postings, postingID) } @@ -2813,7 +2855,7 @@ func (v *mailView) openThreadPicker(key string) tea.Cmd { // label files out of the box it is actually in rather than out of whatever list is // behind it. Only a topic opened by its id has no row, and nothing to file. func (v *mailView) fileablePosting() *mail.Posting { - if v.threadPosting.ID == 0 { + if v.threadFromTrash || v.threadPosting.ID == 0 { return nil } return &v.threadPosting @@ -3138,7 +3180,7 @@ func threadNoun(count int) string { // for the same reason. An empty list keeps it, as it always has: there is nothing to // refuse yet. func (v *mailView) trashOffered() bool { - return bundlesIn(v.trashTargets()) == 0 + return !v.inTrash() && bundlesIn(v.trashTargets()) == 0 } func bundlesIn(postings []mail.Posting) int { @@ -3474,7 +3516,13 @@ func (v *mailView) readPostingsPage(ctx context.Context, source mail.Source, pag if err != nil { return nil, "", err } - return mail.Postings(read.Postings), read.Cursor, nil + postings := mail.Postings(read.Postings) + if source.Kind == mail.KindTrash { + for i := range postings { + postings[i].TopicID = read.Postings[i].Id + } + } + return postings, read.Cursor, nil } func (v *mailView) fetchSearchResults(ctx context.Context, requestID uint64, query string, page int) tea.Cmd { diff --git a/internal/tui/mail_test.go b/internal/tui/mail_test.go index 5fec82c98..2bfcd0b4a 100644 --- a/internal/tui/mail_test.go +++ b/internal/tui/mail_test.go @@ -210,8 +210,8 @@ func TestMailViewHandlesBoxesLoaded(t *testing.T) { if !consumed { t.Error("boxesLoadedMsg should be consumed") } - if len(v.boxes) != 3 { - t.Errorf("expected 3 boxes, got %d", len(v.boxes)) + if len(v.boxes) != 4 { + t.Errorf("expected 3 boxes plus Trash, got %d sources", len(v.boxes)) } } @@ -1445,7 +1445,7 @@ func TestMailViewLoadsFolderSourcesAndPostings(t *testing.T) { if !consumed || postingsCmd == nil { t.Fatal("folder sources should be loaded and start the first mailbox request") } - if len(v.boxes) != 2 || v.boxes[1].Kind != mail.KindFolder || v.boxes[1].Name != "Receipts" { + if len(v.boxes) != 3 || v.boxes[1].Kind != mail.KindFolder || v.boxes[1].Name != "Receipts" { t.Fatalf("mail sources = %+v", v.boxes) } @@ -1699,7 +1699,7 @@ func TestMailViewFolderDiscoveryFailurePreservesMailAndRetries(t *testing.T) { failed := runCmd(v.Init()).(mailSourcesLoadedMsg) firstPostings, consumed := v.Update(failed) - if !consumed || firstPostings == nil || len(v.boxes) != 1 || v.folderDiscoveryErr == "" { + if !consumed || firstPostings == nil || len(v.boxes) != 2 || v.folderDiscoveryErr == "" { t.Fatalf("folder failure state = consumed:%v command:%v sources:%+v error:%q", consumed, firstPostings != nil, v.boxes, v.folderDiscoveryErr) } if !strings.Contains(v.notice, "press b to retry") { @@ -1713,7 +1713,7 @@ func TestMailViewFolderDiscoveryFailurePreservesMailAndRetries(t *testing.T) { } recovered := runCmd(retry).(mailSourcesLoadedMsg) v.Update(recovered) - if v.folderDiscoveryErr != "" || len(v.boxes) != 2 || v.boxes[1].Name != "Receipts" { + if v.folderDiscoveryErr != "" || len(v.boxes) != 3 || v.boxes[1].Name != "Receipts" { t.Errorf("recovered sources = %+v error=%q", v.boxes, v.folderDiscoveryErr) } if v.notice != "" { diff --git a/internal/tui/move.go b/internal/tui/move.go index 0244e66db..c1bbc2162 100644 --- a/internal/tui/move.go +++ b/internal/tui/move.go @@ -28,7 +28,7 @@ func newMovePicker(posting mail.Posting, boxes []mail.Source, currentSource mail destinations := make([]mail.Source, 0, len(boxes)) for _, box := range boxes { isCurrentSource := box.ID == currentSource.ID && box.Kind == currentSource.Kind - if isOrganizedMailSource(box.Kind) || isCurrentSource || box.BoxKind == hey.BoxKindBubbleUp { + if box.Kind == mail.KindTrash || isOrganizedMailSource(box.Kind) || isCurrentSource || box.BoxKind == hey.BoxKindBubbleUp { continue } destinations = append(destinations, box) diff --git a/internal/tui/trash.go b/internal/tui/trash.go new file mode 100644 index 000000000..f8864f06f --- /dev/null +++ b/internal/tui/trash.go @@ -0,0 +1,114 @@ +package tui + +import ( + "strings" + + tea "charm.land/bubbletea/v2" + + "github.com/basecamp/hey-cli/internal/mail" +) + +type trashRestoredMsg struct { + topicID int64 + err error +} + +func (v *mailView) trashIndex() int { + for i, source := range v.boxes { + if source.Kind == mail.KindTrash { + return i + } + } + return -1 +} + +func (v *mailView) inTrash() bool { + if v.inThread { + return v.threadFromTrash + } + return v.currentSourceKind() == mail.KindTrash && !v.searchActive && !v.bundleActive && !v.seenActive +} + +// Trash rows are topics, not posting IDs. Only restore is a mutation here. +func (v *mailView) handleTrashKey(key string) (tea.Cmd, bool) { + if !v.inTrash() { + return nil, false + } + if v.trashRestoreID != 0 && key == "enter" { + return nil, true + } + if key == "i" || key == "I" { + return v.restoreTrashTopic(), true + } + switch key { + case "r", "R", "f", "F", "v", "V", "b", "B", "n", "N", "w", "W", "e", "E", "u", "U", "l", "a", "A", "d", "D", "p", "P", "t", "T", "!", "-", "+", "ctrl+b", "ctrl+u", "space", " ", "x": + v.notice = "Restore this thread before changing it" + return nil, true + } + return nil, false +} + +func (v *mailView) restoreTrashTopic() tea.Cmd { + if v.requests.loading || v.trashRestoreID != 0 { + return nil + } + selected := v.actionPosting() + if v.inThread && v.threadFromTrash { + selected = &v.threadPosting + } + if selected == nil || selected.TopicID == 0 { + return nil + } + id := selected.TopicID + v.trashRestoreID = id + v.pendingMutations++ + sdk, ctx := v.vc.sdk, v.vc.ctx + return func() tea.Msg { return trashRestoredMsg{topicID: id, err: sdk.Topics().Restore(ctx, id)} } +} + +func (v *mailView) trashRestored(msg trashRestoredMsg) tea.Cmd { + v.finishMutation() + v.trashRestoreID = 0 + if msg.err != nil { + return func() tea.Msg { return errMsg{msg.err} } + } + if v.inThread && v.threadFromTrash && v.topicID == msg.topicID { + v.ExitThread() + } + if v.currentSourceKind() != mail.KindTrash { + return notify("Thread restored") + } + // A page or live head read begun before the restore may still contain this + // topic. Ignore those answers so they cannot resurrect the restored row. + v.moreRequestID++ + v.liveRequestID++ + v.postingPaging.loading = false + if index := postingIndexIn(v.postingList.postings, msg.topicID); index >= 0 { + v.removePostingAt(index) + } + if v.requests.kind == mailRequestPostings && v.requests.loading { + v.requests.cancel() + return tea.Batch(notify("Thread restored"), v.reloadPostings()) + } + return tea.Batch(notify("Thread restored"), v.loadMorePostings()) +} + +func (v *mailView) trashHelp(bindings []helpBinding) []helpBinding { + if !v.inTrash() { + return bindings + } + filtered := make([]helpBinding, 0, len(bindings)) + for _, binding := range bindings { + switch strings.ToLower(binding.key) { + case "r", "f", "v", "b", "n", "w", "e", "u", "l", "a", "d", "p", "t", "!", "-", "+", "ctrl+b", "ctrl+u", "space/x": + continue + case "i": + binding.desc = "restore" + } + filtered = append(filtered, binding) + } + if v.inThread { + filtered = append(filtered, helpBinding{"i", "restore"}) + } + return filtered +} diff --git a/internal/tui/trash_test.go b/internal/tui/trash_test.go new file mode 100644 index 000000000..6d73e4ec4 --- /dev/null +++ b/internal/tui/trash_test.go @@ -0,0 +1,259 @@ +package tui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + hey "github.com/basecamp/hey-sdk/go/pkg/hey" + + "github.com/basecamp/hey-cli/internal/mail" +) + +func trashView(t *testing.T, handler http.HandlerFunc) *mailView { + t.Helper() + server := httptest.NewServer(handler) + t.Cleanup(server.Close) + v := mailWithPostings() + v.vc.sdk = hey.NewClient(&hey.Config{BaseURL: server.URL}, &hey.StaticTokenProvider{Token: "test-token"}, hey.WithMaxRetries(0)) + v.boxes = append(v.boxes, mail.Source{Kind: mail.KindTrash, Name: "Trash"}) + v.boxIndex = v.trashIndex() + v.postingList.setPostings([]mail.Posting{{ID: 701, TopicID: 701, Name: "Conference travel plans", Seen: true}}) + return v +} + +func TestTrashTabAndNumberShortcut(t *testing.T) { + v := mailWithPostings() + v.applySources(v.boxes) + v.requests.loading = false + if v.trashIndex() < 0 { + t.Fatal("Trash source missing") + } + items, _, _, _ := v.SubnavItems() + last := items[len(items)-1] + if last.shortcut != "0" || last.label != "Trash" { + t.Fatalf("last tab = %+v", last) + } + cmd := v.handleBoxShortcut("0") + if cmd == nil || v.currentSourceKind() != mail.KindTrash { + t.Fatal("0 did not open Trash") + } + items, selected, label, _ := v.SubnavItems() + if items[selected].shortcut != "0" || label != "Trash" { + t.Fatal("Trash tab was not selected") + } + v.requests.loading = false + v.SubnavLeft() + if !v.seenActive && v.modal == nil { + t.Fatal("left arrow did not leave Trash") + } +} + +func TestTrashRestoresTopicAndOnlyRemovesRowOnSuccess(t *testing.T) { + for _, inThread := range []bool{false, true} { + status := http.StatusForbidden + calls := 0 + v := trashView(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + if r.Method != http.MethodPut || r.URL.Path != "/topics/701/status/active.json" { + t.Errorf("restore request = %s %s", r.Method, r.URL) + } + w.WriteHeader(status) + }) + if inThread { + v.inThread = true + v.threadFromTrash = true + v.topicID = 701 + v.threadPosting = v.postingList.postings[0] + } + cmd := v.HandleContentKey(keyPress("i")) + if cmd == nil || v.pendingMutations != 1 { + t.Fatal("restore not dispatched") + } + if v.HandleContentKey(keyPress("i")) != nil { + t.Fatal("duplicate restore dispatch") + } + v.Update(cmd()) + if len(v.postingList.postings) != 1 || v.inThread != inThread || v.pendingMutations != 0 { + t.Fatal("failure discarded thread") + } + status = http.StatusOK + cmd = v.HandleContentKey(keyPress("I")) + v.Update(cmd()) + if calls != 2 || len(v.postingList.postings) != 0 || v.inThread || v.pendingMutations != 0 { + t.Fatal("success did not restore and remove the row") + } + } +} + +func TestTrashBlocksPostingMutations(t *testing.T) { + for _, inThread := range []bool{false, true} { + v := trashView(t, func(w http.ResponseWriter, r *http.Request) { + t.Errorf("unexpected request %s", r.URL) + w.WriteHeader(http.StatusOK) + }) + if inThread { + v.inThread = true + v.threadFromTrash = true + v.topicID = 701 + v.threadPosting = v.postingList.postings[0] + } + for _, key := range []string{"t", "T", "v", "V", "b", "n", "w", "r", "f", "a", "l", "d", "p", "u", "e", "!", "-", "+", "ctrl+b", "ctrl+u", "space", "x"} { + if cmd := v.HandleContentKey(keyPress(key)); cmd != nil || v.modal != nil || v.pendingMutations != 0 { + t.Fatalf("%q dispatched a posting action from Trash", key) + } + } + if v.trashOffered() { + t.Fatal("Trash offered t") + } + restored := false + for _, binding := range v.HelpBindings() { + if binding.key == "t" || binding.key == "v" || binding.key == "r" { + t.Fatalf("unsafe help binding %+v", binding) + } + if binding.key == "i" && binding.desc == "restore" { + restored = true + } + } + if !restored { + t.Fatal("missing restore help") + } + } +} + +func TestTrashRowsReadTopicsAndPageByOpaqueCursor(t *testing.T) { + var pages []string + v := trashView(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/topics/trash.json" { + t.Errorf("unexpected path %s", r.URL.Path) + } + page := r.URL.Query().Get("page") + pages = append(pages, page) + w.Header().Set("Content-Type", "application/json") + if page == "" { + w.Header().Set("Link", `; rel="next"`) + _ = json.NewEncoder(w).Encode(map[string]any{"title": "Trash", "topics": []map[string]any{{"id": 701, "name": "Conference travel plans", "creator": map[string]any{"name": "Alex Morgan"}, "latest_entry": map[string]any{"summary": "Flight details"}}}}) + } else { + _ = json.NewEncoder(w).Encode(map[string]any{"topics": []any{}}) + } + }) + source := *v.currentSource() + rows, next, err := v.readPostingsPage(v.vc.ctx, source, "") + if err != nil || len(rows) != 1 || rows[0].TopicID != 701 || rows[0].ID != 701 || !rows[0].Seen || next != "opaque-next" { + t.Fatalf("first page %+v %q %v", rows, next, err) + } + _, next, err = v.readPostingsPage(v.vc.ctx, source, next) + if err != nil || next != "" || len(pages) != 2 || pages[1] != "opaque-next" { + t.Fatalf("paging %v %q %v", pages, next, err) + } + if !strings.Contains(rows[0].Summary, "Flight details") { + t.Fatal("missing summary") + } +} + +func TestRestoreReplyCannotRemoveSameIDFromAnotherSource(t *testing.T) { + v := trashView(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) + cmd := v.HandleContentKey(keyPress("i")) + v.boxIndex = 0 + v.postingList.setPostings([]mail.Posting{{ID: 701, TopicID: 900}}) + v.Update(cmd()) + if len(v.postingList.postings) != 1 { + t.Fatal("late restore removed unrelated row") + } +} + +func TestOpeningTrashThreadDoesNotObservePosting(t *testing.T) { + v := trashView(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/topics/701.json": + _, _ = w.Write([]byte(`{"id":701,"name":"Conference travel plans","status":"trashed","screened_in":true,"entries":[{"id":801,"kind":"message","summary":"Flight details"}]}`)) + case "/topics/701/entries.json": + _, _ = w.Write([]byte(`[{"id":801,"kind":"message","summary":"Flight details"}]`)) + case "/messages/801.json": + _, _ = w.Write([]byte(`{"id":801,"content":"

Flight details

"}`)) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL) + w.WriteHeader(http.StatusNotFound) + } + }) + cmd := v.openSelected() + if cmd == nil { + t.Fatal("Enter did not start a thread read") + } + loaded := cmd() + v.Update(loaded) + if !v.inThread || !v.threadFromTrash || v.topicID != 701 || v.pendingMutations != 0 || v.fileablePosting() != nil { + t.Fatalf("Trash reader state: inThread=%v trash=%v topic=%d pending=%d", v.inThread, v.threadFromTrash, v.topicID, v.pendingMutations) + } +} + +func TestRestoreInvalidatesEarlierTrashPageReads(t *testing.T) { + v := trashView(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) + cmd := v.HandleContentKey(keyPress("i")) + oldMore, oldLive := v.moreRequestID, v.liveRequestID + v.Update(cmd()) + v.Update(postingsAppendedMsg{requestID: oldMore, boxID: 0, sourceKind: mail.KindTrash, postings: []mail.Posting{{ID: 701, TopicID: 701}}}) + v.Update(postingsRefreshedMsg{requestID: oldLive, boxID: 0, sourceKind: mail.KindTrash, postings: []mail.Posting{{ID: 701, TopicID: 701}}}) + if len(v.postingList.postings) != 0 { + t.Fatal("an earlier read resurrected the restored topic") + } +} + +func TestTrashCanBeReachedFromEndOfTabNavigation(t *testing.T) { + for _, kind := range []mail.Kind{mail.KindBox, mail.KindFolder, mail.KindCollection} { + v := mailWithPostings() + v.boxes = append(v.boxes, mail.Source{Kind: mail.KindTrash, Name: "Trash"}) + switch kind { + case mail.KindBundle, mail.KindContact, mail.KindTrash: + t.Fatalf("unexpected source kind %s", kind) + case mail.KindBox: + v.seenActive = true + case mail.KindFolder, mail.KindCollection: + v.boxes = append(v.boxes, mail.Source{Kind: kind, ID: 12, Name: "Travel"}) + v.boxIndex = len(v.boxes) - 1 + } + if cmd := v.SubnavRight(); cmd == nil || v.currentSourceKind() != mail.KindTrash || v.seenActive { + t.Fatalf("right from %s did not reach Trash", kind) + } + } +} + +func TestMovePickerNeverOffersTrashAsDestination(t *testing.T) { + v := mailWithPostings() + v.boxes = append(v.boxes, mail.Source{Kind: mail.KindTrash, Name: "Trash"}) + v.startMove() + picker := modalOf[*movePicker](v) + if picker == nil { + t.Fatal("move picker missing") + } + for _, source := range picker.destinations { + if source.Kind == mail.KindTrash { + t.Fatal("Trash offered as a box move") + } + } +} + +func TestRestoreInvalidatesEarlierTrashReload(t *testing.T) { + v := trashView(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) + restore := v.HandleContentKey(keyPress("i")) + _ = v.reloadPostings() + oldRequest := v.requests.id + v.Update(restore()) + v.Update(postingsLoadedMsg{requestID: oldRequest, boxID: 0, sourceKind: mail.KindTrash, postings: []mail.Posting{{ID: 701, TopicID: 701}}}) + if len(v.postingList.postings) != 0 { + t.Fatal("an earlier reload resurrected a restored topic") + } +} + +func TestPostingActionCannotRemoveTrashTopicWithSameNumericID(t *testing.T) { + v := trashView(t, func(w http.ResponseWriter, r *http.Request) { t.Fatal("unexpected request") }) + v.searchActive = true + v.searchList.setPostings([]mail.Posting{{ID: 701, TopicID: 900}}) + v.Update(postingActionDoneMsg{boxID: 0, sourceKind: mail.KindTrash, postingID: 701, effect: postingActionRemove}) + if len(v.postingList.postings) != 1 || len(v.searchList.postings) != 0 { + t.Fatal("posting completion affected the Trash topic instead of only the search result") + } +} diff --git a/internal/tui/tui_test.go b/internal/tui/tui_test.go index b4a44dde6..f755eb578 100644 --- a/internal/tui/tui_test.go +++ b/internal/tui/tui_test.go @@ -411,7 +411,7 @@ func TestFolderDiscoveryCompletesWhileAnotherSectionIsActive(t *testing.T) { }, }) m = updated.(model) - if len(m.mailView.boxes) != 2 || m.mailView.boxes[1].Name != "Receipts" { + if len(m.mailView.boxes) != 3 || m.mailView.boxes[1].Name != "Receipts" { t.Errorf("mail sources = %+v", m.mailView.boxes) } if cmd == nil { From 381a06bf28b25822263f3b46f01fd9d147df2225 Mon Sep 17 00:00:00 2001 From: Elija Sorensen <3824702+WhiskeyTuesday@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:49:39 -0700 Subject: [PATCH 2/3] Make the pending SDK dependency portable for review --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 070afd301..4317290d6 100644 --- a/go.mod +++ b/go.mod @@ -126,4 +126,4 @@ require ( k8s.io/klog/v2 v2.140.0 // indirect ) -replace github.com/basecamp/hey-sdk/go => /home/ers/Work/hey-sdk/go +replace github.com/basecamp/hey-sdk/go => github.com/WhiskeyTuesday/hey-sdk/go v0.36.1-0.20261121014628-998231a1a7ee diff --git a/go.sum b/go.sum index f414ba735..8bdcfe13b 100644 --- a/go.sum +++ b/go.sum @@ -43,6 +43,8 @@ github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6 github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM= github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo= github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk= +github.com/WhiskeyTuesday/hey-sdk/go v0.36.1-0.20261121014628-998231a1a7ee h1:8h7QOWcDXFIMrNOVS8DvZwafFoZVDaj7xpfxen8CxdY= +github.com/WhiskeyTuesday/hey-sdk/go v0.36.1-0.20261121014628-998231a1a7ee/go.mod h1:g4+w+Htmntp03iF9L7afzWyPVYeQzxFUYONlw9r4R+s= github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0= github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= github.com/alecthomas/chroma/v2 v2.20.0 h1:sfIHpxPyR07/Oylvmcai3X/exDlE8+FA820NTz+9sGw= @@ -91,8 +93,6 @@ github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuP github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= github.com/basecamp/actioncable-client/go/v2 v2.0.2 h1:h2Sl15gj2lI/EX5E0EUxjyYgf0LF9Gn1zqEUInSrUpc= github.com/basecamp/actioncable-client/go/v2 v2.0.2/go.mod h1:3Y0N9V5LXclT5nQWcPhq/+6rj4eKXgKAX8dx15X8yB8= -github.com/basecamp/hey-sdk/go v0.35.1 h1:azrn9JoilQaQ3QDBtZb4hiROmQFUyEIWWVWFq65wSTw= -github.com/basecamp/hey-sdk/go v0.35.1/go.mod h1:g4+w+Htmntp03iF9L7afzWyPVYeQzxFUYONlw9r4R+s= github.com/basecamp/mcp v0.0.0-20261119020105-1a6d02c5380a h1:5SI0hmC3B5wLusmAG917J9HGWnU2JLV+S2Ek8A0ABxk= github.com/basecamp/mcp v0.0.0-20261119020105-1a6d02c5380a/go.mod h1:K3sgTH90CIR6Ed0XPnivIBqNIpw6aeOlcXThBrZ+2gc= github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w= From 8466640cdb9dc4e8113f0d573834cf26e1e6a534 Mon Sep 17 00:00:00 2001 From: Elija Sorensen <3824702+WhiskeyTuesday@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:38:24 -0700 Subject: [PATCH 3/3] Invalidate stale Trash refreshes after restoring from another source --- internal/tui/trash.go | 7 ++-- internal/tui/trash_test.go | 72 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 3 deletions(-) diff --git a/internal/tui/trash.go b/internal/tui/trash.go index f8864f06f..73f62be06 100644 --- a/internal/tui/trash.go +++ b/internal/tui/trash.go @@ -75,13 +75,14 @@ func (v *mailView) trashRestored(msg trashRestoredMsg) tea.Cmd { if v.inThread && v.threadFromTrash && v.topicID == msg.topicID { v.ExitThread() } + // A live read begun before the restore may still contain this topic, even + // if the reader switched away and returns to Trash before the read arrives. + v.liveRequestID++ if v.currentSourceKind() != mail.KindTrash { return notify("Thread restored") } - // A page or live head read begun before the restore may still contain this - // topic. Ignore those answers so they cannot resurrect the restored row. + // Navigation already invalidates pages; only cancel paging here in Trash. v.moreRequestID++ - v.liveRequestID++ v.postingPaging.loading = false if index := postingIndexIn(v.postingList.postings, msg.topicID); index >= 0 { v.removePostingAt(index) diff --git a/internal/tui/trash_test.go b/internal/tui/trash_test.go index 6d73e4ec4..7c653b07d 100644 --- a/internal/tui/trash_test.go +++ b/internal/tui/trash_test.go @@ -5,6 +5,7 @@ import ( "net/http" "net/http/httptest" "strings" + "sync/atomic" "testing" hey "github.com/basecamp/hey-sdk/go/pkg/hey" @@ -257,3 +258,74 @@ func TestPostingActionCannotRemoveTrashTopicWithSameNumericID(t *testing.T) { t.Fatal("posting completion affected the Trash topic instead of only the search result") } } + +func TestRestoreAwayFromTrashInvalidatesEarlierLiveRefresh(t *testing.T) { + var restored atomic.Bool + v := trashView(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodPut && r.URL.Path == "/topics/701/status/active.json": + restored.Store(true) + w.WriteHeader(http.StatusOK) + case r.Method == http.MethodGet && r.URL.Path == "/topics/trash.json": + w.Header().Set("Content-Type", "application/json") + topics := []map[string]any{{"id": 702, "name": "Hotel receipt"}} + if !restored.Load() { + topics = append(topics, map[string]any{"id": 701, "name": "Conference travel plans"}) + } + _ = json.NewEncoder(w).Encode(map[string]any{"topics": topics}) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL) + w.WriteHeader(http.StatusNotFound) + } + }) + + // Hold the old response until after a restore and a round trip through the Imbox. + refresh := v.refreshBox(AnyBoxChanged) + if refresh == nil { + t.Fatal("Trash refresh did not start") + } + stale := refresh() + restore := v.HandleContentKey(keyPress("i")) + if restore == nil { + t.Fatal("restore did not start") + } + v.switchBox(0) + v.Update(currentPostingsLoaded(v, []mail.Posting{{ID: 701, TopicID: 900, Name: "Dinner reservation"}})) + moreRequest := v.moreRequestID + v.Update(restore()) + if len(v.postingList.postings) != 1 || v.postingList.postings[0].TopicID != 900 { + t.Fatal("restore changed the Imbox row with the same numeric ID") + } + if v.moreRequestID != moreRequest { + t.Fatal("restore invalidated paging for the other source") + } + read := v.switchBox(v.trashIndex()) + v.Update(read()) + if got := postingIDs(v.postingList.postings); len(got) != 1 || postingIndexIn(v.postingList.postings, 702) < 0 { + t.Fatalf("fresh Trash read = %v, want only the remaining topic", got) + } + v.Update(stale) + if got := postingIDs(v.postingList.postings); len(got) != 1 || postingIndexIn(v.postingList.postings, 702) < 0 { + t.Fatalf("stale refresh reinserted the restored topic: %v", got) + } +} + +func TestFailedRestoreAwayFromTrashKeepsLiveRefreshValid(t *testing.T) { + v := trashView(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusForbidden) }) + restore := v.HandleContentKey(keyPress("i")) + oldLive := v.liveRequestID + v.switchBox(0) + v.Update(restore()) + if v.liveRequestID != oldLive || v.pendingMutations != 0 || v.trashRestoreID != 0 { + t.Fatal("failed restore invalidated the refresh or left the mutation pending") + } + v.switchBox(v.trashIndex()) + v.Update(currentPostingsLoaded(v, []mail.Posting{{ID: 701, TopicID: 701}})) + v.Update(postingsRefreshedMsg{ + requestID: oldLive, sourceKind: mail.KindTrash, + postings: []mail.Posting{{ID: 701, TopicID: 701}, {ID: 702, TopicID: 702}}, + }) + if len(v.postingList.postings) != 2 { + t.Fatal("failed restore prevented an otherwise valid refresh") + } +}