diff --git a/libs/cmdio/paged_template_test.go b/libs/cmdio/paged_template_test.go index 03a5fc1c9d5..1ee1b5039f0 100644 --- a/libs/cmdio/paged_template_test.go +++ b/libs/cmdio/paged_template_test.go @@ -44,6 +44,18 @@ func stripANSI(s string) string { return ansiStripPattern.ReplaceAllString(s, "") } +// screenLines returns the lines a terminal would show for s: tea redraws +// its view (spinner, prompt) by returning to column 0 with \r and +// erasing, so only the text after a line's last \r is still visible. +func screenLines(s string) []string { + lines := strings.Split(stripANSI(s), "\n") + for i, line := range lines { + line = strings.TrimRight(line, "\r") + lines[i] = line[strings.LastIndex(line, "\r")+1:] + } + return lines +} + // pagedOutput runs a full paged render, feeding ENTER to auto-drain, // and returns the ANSI-stripped output. func pagedOutput( @@ -64,24 +76,33 @@ func pagedOutput( return stripANSI(out.String()) } -func countContentLines(s string) int { - count := 0 - for line := range strings.SplitSeq(s, "\n") { +// contentLines returns the visible rows, without the pager's prompt and +// spinner lines. +func contentLines(s string) []string { + var rows []string + for _, line := range screenLines(s) { trimmed := strings.TrimSpace(line) - if trimmed == "" || strings.Contains(trimmed, pagerPromptText) { + if trimmed == "" || strings.Contains(trimmed, pagerPromptText) || strings.Contains(trimmed, pagerLoadingText) { continue } - count++ + rows = append(rows, trimmed) } - return count + return rows +} + +func countContentLines(s string) int { + return len(contentLines(s)) } func TestPagedTemplateDrainsFullIterator(t *testing.T) { out := pagedOutput(t, MockDiscard(t.Context()), &numberIterator{n: 23}, "", "{{range .}}{{.}}\n{{end}}", 5) assert.Equal(t, 23, countContentLines(out)) + // Pages must come out in order, not just all present. + var want []string for i := 1; i <= 23; i++ { - assert.Contains(t, out, strconv.Itoa(i)) + want = append(want, strconv.Itoa(i)) } + assert.Equal(t, want, contentLines(out)) } func TestPagedTemplateRespectsLimit(t *testing.T) { @@ -183,7 +204,7 @@ func TestPagedTemplateMatchesNonPagedForSmallList(t *testing.T) { 100, )) - assertSameContentLines(t, expected.String(), stripANSI(actual.String())) + assertSameContentLines(t, expected.String(), strings.Join(screenLines(actual.String()), "\n")) } func assertSameContentLines(t *testing.T, want, got string) { diff --git a/libs/cmdio/pager.go b/libs/cmdio/pager.go index 0ecb330e5cd..8f2911f3732 100644 --- a/libs/cmdio/pager.go +++ b/libs/cmdio/pager.go @@ -49,14 +49,20 @@ type pagerModel[T any] struct { total int // Keep only one fetch in flight at a time: the iterator is not safe - // to read from two goroutines. If SPACE or ENTER arrives while - // fetching, drainAll is recorded and the pending batchMsg chains - // the next fetch. - fetching bool - drainAll bool - hasPrinted bool - iterDone bool - err error + // to read from two goroutines. If ENTER arrives while fetching, + // drainAll is recorded and the pagePrintedMsg that follows the + // fetched page chains the next fetch. + fetching bool + // printing is set from a batchMsg until its pagePrintedMsg: tea runs + // every returned Cmd on its own goroutine, so a fetch or Quit issued + // before the page's print reaches the event loop can overtake it and + // the page's rows are lost or reordered. Keys wait for it. + printing bool + quitPending bool + drainAll bool + hasPrinted bool + iterDone bool + err error } // newPagerModel wires ctx into the fetch closure so nothing on the @@ -104,6 +110,10 @@ type batchMsg struct { err error } +// pagePrintedMsg follows a page's print in the same tea.Sequence, so +// when Update sees it the page's lines are already queued for output. +type pagePrintedMsg struct{} + func (m *pagerModel[T]) Init() tea.Cmd { m.fetching = true return tea.Batch(m.fetch(m.pageSize, m.limit, m.total), m.spinner.Tick) @@ -163,22 +173,30 @@ func (m *pagerModel[T]) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } m.total += msg.count m.hasPrinted = true - // One Println cmd (not N) keeps the batch ordered even though - // tea.Sequence dispatches each cmd on its own goroutine. + // One Println for the whole batch: tea.Sequence delivers each + // cmd's message before running the next, so what follows it in + // the same Sequence lands after the page is queued for output. var printCmd tea.Cmd if len(msg.lines) > 0 { printCmd = tea.Println(strings.Join(msg.lines, "\n")) } - switch { - case msg.done: + if msg.done { m.iterDone = true return m, tea.Sequence(printCmd, tea.Quit) - case m.drainAll: + } + m.printing = true + return m, tea.Sequence(printCmd, func() tea.Msg { return pagePrintedMsg{} }) + + case pagePrintedMsg: + m.printing = false + switch { + case m.quitPending: + return m, tea.Quit + case m.drainAll && !m.iterDone && m.err == nil: m.fetching = true - return m, tea.Sequence(printCmd, m.fetch(m.pageSize, m.limit, m.total)) - default: - return m, printCmd + return m, m.fetch(m.pageSize, m.limit, m.total) } + return m, nil case tea.KeyMsg: if m.iterDone { @@ -194,7 +212,7 @@ func (m *pagerModel[T]) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case tea.KeyEnter: return m, m.startDrain() case tea.KeyEsc, tea.KeyCtrlC: - return m, tea.Quit + return m, m.quit() case tea.KeySpace: return m, m.startAdvance() case tea.KeyRunes: @@ -202,14 +220,23 @@ func (m *pagerModel[T]) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case " ": return m, m.startAdvance() case "q", "Q": - return m, tea.Quit + return m, m.quit() } } return m, nil } +// quit waits for a pending page print so its rows are not dropped. +func (m *pagerModel[T]) quit() tea.Cmd { + if m.printing { + m.quitPending = true + return nil + } + return tea.Quit +} + func (m *pagerModel[T]) startAdvance() tea.Cmd { - if m.drainAll || m.fetching { + if m.drainAll || m.fetching || m.printing { return nil } m.fetching = true @@ -221,9 +248,9 @@ func (m *pagerModel[T]) startDrain() tea.Cmd { return nil } m.drainAll = true - // If a fetch is already in flight, its batchMsg will see drainAll - // and chain the next fetch. Otherwise kick one off here. - if m.fetching { + // If a fetch or a page print is pending, its pagePrintedMsg will see + // drainAll and chain the next fetch. Otherwise kick one off here. + if m.fetching || m.printing { return nil } m.fetching = true diff --git a/libs/cmdio/pager_test.go b/libs/cmdio/pager_test.go index 503172e7176..8e6b22f978c 100644 --- a/libs/cmdio/pager_test.go +++ b/libs/cmdio/pager_test.go @@ -131,22 +131,68 @@ func TestPagerModelBatchDonePrintsHeaderOnlyEmptyIter(t *testing.T) { func TestPagerModelBatchPromptsWhenMore(t *testing.T) { m := newTestPager(t, &numberIterator{n: 100}, 5) + m.fetching = true _, cmd := m.Update(batchMsg{lines: []string{"1", "2"}, done: false}) assert.False(t, m.iterDone) assert.True(t, m.hasPrinted) assert.False(t, m.drainAll) + assert.True(t, m.printing) + assert.Equal(t, pagerPromptText, m.View()) + cmds := unwrapCmds(t, runCmd(t, cmd)) + require.Len(t, cmds, 2) + assert.Contains(t, printedText(t, runCmd(t, cmds[0])), "1\n2") + printed := runCmd(t, cmds[1]) + require.IsType(t, pagePrintedMsg{}, printed) + + _, cmd = m.Update(printed) + assert.Nil(t, cmd) + assert.False(t, m.printing) assert.Equal(t, pagerPromptText, m.View()) - assert.Contains(t, printedText(t, runCmd(t, cmd)), "1\n2") +} + +// TestPagerModelKeysWaitForPagePrint covers the window between a batchMsg +// and its pagePrintedMsg: tea runs each Cmd on its own goroutine, so a +// fetch or Quit issued then could overtake the page's print and drop rows. +func TestPagerModelKeysWaitForPagePrint(t *testing.T) { + m := newTestPager(t, &numberIterator{n: 100}, 5) + m.fetching = true + _, _ = m.Update(batchMsg{lines: []string{"1", "2"}, done: false}) + + _, cmd := m.Update(tea.KeyMsg{Type: tea.KeySpace}) + assert.Nil(t, cmd, "SPACE before the page is printed must not fetch") + _, cmd = m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + assert.Nil(t, cmd, "ENTER before the page is printed must not fetch") + assert.True(t, m.drainAll) + + _, cmd = m.Update(pagePrintedMsg{}) + _, isFetch := runCmd(t, cmd).(batchMsg) + assert.True(t, isFetch, "the deferred drain fetches once the page is printed") +} + +func TestPagerModelQuitWaitsForPagePrint(t *testing.T) { + m := newTestPager(t, &numberIterator{n: 100}, 5) + m.fetching = true + _, _ = m.Update(batchMsg{lines: []string{"1", "2"}, done: false}) + + _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'q'}}) + assert.Nil(t, cmd, "q before the page is printed must not quit yet") + + _, cmd = m.Update(pagePrintedMsg{}) + _, isQuit := runCmd(t, cmd).(tea.QuitMsg) + assert.True(t, isQuit, "the deferred quit fires once the page is printed") } func TestPagerModelBatchDrainingChainsFetch(t *testing.T) { m := newTestPager(t, &numberIterator{n: 100}, 5) m.drainAll = true + m.fetching = true _, cmd := m.Update(batchMsg{lines: []string{"1", "2"}, done: false}) cmds := unwrapCmds(t, runCmd(t, cmd)) require.Len(t, cmds, 2) assert.Contains(t, printedText(t, runCmd(t, cmds[0])), "1\n2") - _, isFetch := runCmd(t, cmds[1]).(batchMsg) + _, cmd = m.Update(runCmd(t, cmds[1])) + assert.True(t, m.fetching) + _, isFetch := runCmd(t, cmd).(batchMsg) assert.True(t, isFetch, "draining must auto-fetch the next batch") } @@ -206,12 +252,12 @@ func TestPagerModelSpaceIgnoredDuringFetch(t *testing.T) { func TestPagerModelEnterDuringFetchDefersFetch(t *testing.T) { // ENTER during an in-flight fetch flips drainAll but can't issue a new - // fetch; the pending batchMsg will chain one when it arrives. + // fetch; the pagePrintedMsg after the pending batch chains one. m := newTestPager(t, &numberIterator{n: 100}, 5) m.fetching = true _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) assert.True(t, m.drainAll) - assert.Nil(t, cmd, "ENTER during fetch must defer to batchMsg chaining") + assert.Nil(t, cmd, "ENTER during fetch must defer to pagePrintedMsg chaining") } func TestPagerModelQuitKeys(t *testing.T) {