Make state single-owner and stabilize race detector

Frame now carries view state (scale/focus/query) to the main goroutine,
which reads only the frame-receiver-stored snapshot. Renderer owns Gio
widget editors (registered by ID) and the draw scale. Autosave timer
sends a token to the logic goroutine instead of touching state;
Shutdown waits for the owner to exit before FlushAll.

Tests access state only through owner-side Inspect/WithState helpers
(harness + in-package). Fixed double-Harness.Run race in two e2e tests,
made TestWorkerPool_PriorityPreemption deterministic, and raised the
lazy-loading test timeout that was too short under -race.

go test -race ./... is now green.
This commit is contained in:
gmp
2026-08-16 01:32:27 -04:00
parent 7240b62a61
commit 58725a5e6c
20 changed files with 723 additions and 369 deletions
+17 -8
View File
@@ -26,12 +26,17 @@ func TestBrowserFilesVisible(t *testing.T) {
t.Fatalf("timeout waiting for initial frames: %v", err)
}
// Set VisibleCount based on viewport
state := h.State()
state.Browser.VisibleCount = computeVisibleCount(state.PixelHeight, state.Scale())
// Set VisibleCount based on viewport (owner-side write)
if err := h.WithState(func(st *editor.State) {
st.Browser.VisibleCount = computeVisibleCount(st.PixelHeight, st.Scale())
}); err != nil {
t.Fatalf("WithState: %v", err)
}
// Switch to browser page
editor.GoToBrowser(nil)
if err := h.WithState(func(st *editor.State) { editor.GoToBrowser(nil) }); err != nil {
t.Fatalf("GoToBrowser: %v", err)
}
// Trigger a frame
h.SendConfig(780, 1688)
@@ -68,10 +73,14 @@ func TestBrowserFilesVisible(t *testing.T) {
// The mock filesystem has 5 root-level files and 6 directories = 11 entries
if len(listView.Items) == 0 {
t.Errorf("browser ListView has 0 items — files from mock filesystem not showing up")
t.Logf("BrowserState: TotalEntries=%d, VisibleCount=%d, ScrollOffset=%.1f",
state.Browser.TotalEntries,
state.Browser.VisibleCount,
state.Browser.ScrollOffset)
v, err := h.Inspect(func(st *editor.State) any {
return fmt.Sprintf("BrowserState: TotalEntries=%d, VisibleCount=%d, ScrollOffset=%.1f",
st.Browser.TotalEntries, st.Browser.VisibleCount, float64(st.Browser.ScrollOffset))
})
if err != nil {
t.Fatalf("Inspect: %v", err)
}
t.Log(v)
}
// Verify some known files are present
+28 -10
View File
@@ -10,12 +10,18 @@ import (
)
// TestEditorClickToMoveCursor tests that clicking/tapping in the editor moves the cursor.
//
// All state access goes through the harness's owner-side helpers
// (WithState / CursorPosition): the logic goroutine is the sole owner of
// State (architecture.md §1).
func TestEditorClickToMoveCursor(t *testing.T) {
h := e2e.NewHarnessWithDefaults()
defer h.Cleanup()
// Switch to editor page and load some text
editor.GoToEditor(nil)
if err := h.WithState(func(st *editor.State) { editor.GoToEditor(nil) }); err != nil {
t.Fatalf("GoToEditor: %v", err)
}
h.SendConfig(780, 1688)
// Wait for frame to ensure page switch
@@ -24,18 +30,26 @@ func TestEditorClickToMoveCursor(t *testing.T) {
t.Fatalf("timeout waiting for frame: %v", err)
}
// Initialize GlyphLayout for the test
editor.TheState.Editor.GlyphLayout = ui.GlyphLayout{
ByteOffsets: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11},
X: []ui.Dp{10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120},
Y: []ui.Dp{70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70},
Advance: []ui.Dp{10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
// Initialize GlyphLayout for the test (owner-side write)
if err := h.WithState(func(st *editor.State) {
st.Editor.GlyphLayout = ui.GlyphLayout{
ByteOffsets: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11},
X: []ui.Dp{10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120},
Y: []ui.Dp{70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70},
Advance: []ui.Dp{10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
}
}); err != nil {
t.Fatalf("set GlyphLayout: %v", err)
}
// Initial cursor position should be 0 (or end of text, depending on implementation)
// For this test, let's assume it starts at 0.
if editor.TheState.Editor.CursorPosition != 0 {
t.Errorf("expected initial cursor 0, got %d", editor.TheState.Editor.CursorPosition)
pos, err := h.CursorPosition()
if err != nil {
t.Fatalf("CursorPosition: %v", err)
}
if pos != 0 {
t.Errorf("expected initial cursor 0, got %d", pos)
}
// Simulate tap at a position that should move the cursor.
@@ -58,7 +72,11 @@ func TestEditorClickToMoveCursor(t *testing.T) {
}
// Assert cursor moved
if editor.TheState.Editor.CursorPosition == 0 {
pos, err = h.CursorPosition()
if err != nil {
t.Fatalf("CursorPosition: %v", err)
}
if pos == 0 {
t.Errorf("expected cursor to move from 0, but it remained at 0")
}
}
+28 -17
View File
@@ -1,6 +1,7 @@
package e2e_test
import (
"strings"
"testing"
"time"
@@ -9,22 +10,35 @@ import (
"pad/internal/ui"
)
// TestEditLifecycle verifies that edits made through the editor are persisted
// when the file is closed (via GoToBrowser -> FlushAll).
//
// All state access goes through the harness's owner-side helpers: the logic
// goroutine is the sole owner of State (architecture.md §1).
func TestEditLifecycle(t *testing.T) {
h := e2e.NewHarnessWithDefaults()
defer h.Cleanup()
// 1. Go to browser page
editor.GoToBrowser(nil)
if err := h.WithState(func(st *editor.State) { editor.GoToBrowser(nil) }); err != nil {
t.Fatalf("GoToBrowser: %v", err)
}
time.Sleep(200 * time.Millisecond)
// 2. Open File
filename := "/notes.txt"
editor.OpenFile(filename)
if err := h.WithState(func(st *editor.State) { editor.OpenFile(filename) }); err != nil {
t.Fatalf("OpenFile: %v", err)
}
// Wait for file to load
success := false
for i := 0; i < 20; i++ {
if h.State().Editor.ChunkedBuffer != nil && h.State().Editor.ChunkedBuffer.FileLen() > 0 {
loaded, err := h.FileLoaded()
if err != nil {
t.Fatalf("FileLoaded: %v", err)
}
if loaded {
success = true
break
}
@@ -36,20 +50,26 @@ func TestEditLifecycle(t *testing.T) {
// 3. Edit File
// Original content of notes.txt is 198 bytes, let's append " UPDATED"
editor.HandleInsert(" UPDATED")
if err := h.WithState(func(st *editor.State) { editor.HandleInsert(" UPDATED") }); err != nil {
t.Fatalf("HandleInsert: %v", err)
}
time.Sleep(100 * time.Millisecond)
// 4. Close File (Go back to browser)
// This will trigger FlushAll()
editor.GoToBrowser(nil)
if err := h.WithState(func(st *editor.State) { editor.GoToBrowser(nil) }); err != nil {
t.Fatalf("GoToBrowser: %v", err)
}
time.Sleep(500 * time.Millisecond) // Ensure it had time to process close
// 5. Re-open File
editor.OpenFile(filename)
if err := h.WithState(func(st *editor.State) { editor.OpenFile(filename) }); err != nil {
t.Fatalf("OpenFile: %v", err)
}
time.Sleep(1000 * time.Millisecond) // Wait for re-open and load
// 6. Verify Edits
fullContent, err := h.State().Editor.ChunkedBuffer.FullContent()
fullContent, err := h.FullContent()
if err != nil {
t.Fatalf("Failed to reconstruct content: %v", err)
}
@@ -66,7 +86,7 @@ func TestEditLifecycle(t *testing.T) {
for _, child := range container.Children {
if label, ok := child.(ui.Label); ok {
// The cursor position text is in the middle, containing "/"
if len(label.Text) > 0 && label.Text[0] != '/' && contains(label.Text, "/") {
if len(label.Text) > 0 && label.Text[0] != '/' && strings.Contains(label.Text, "/") {
sizeText = label.Text
}
}
@@ -79,12 +99,3 @@ func TestEditLifecycle(t *testing.T) {
t.Errorf("Bottom bar size label mismatch: got %q, expected %q", sizeText, expectedText)
}
}
func contains(s, substr string) bool {
for i := 0; i < len(s); i++ {
if s[i] == substr[0] {
return true
}
}
return false
}
+70 -4
View File
@@ -1,6 +1,7 @@
package e2e
import (
"fmt"
"sync"
"time"
@@ -8,6 +9,8 @@ import (
"pad/internal/ui"
)
var errInspectTimeout = fmt.Errorf("e2e: inspect timed out waiting for the logic goroutine")
// Harness orchestrates the test environment for e2e tests.
type Harness struct {
logic *editor.Logic
@@ -15,6 +18,7 @@ type Harness struct {
logicWg sync.WaitGroup
frameReceiverDone chan struct{}
wg sync.WaitGroup
started bool
}
// HarnessOption configures the test harness.
@@ -36,7 +40,13 @@ func NewHarness(opts ...HarnessOption) *Harness {
}
// Run starts the logic goroutine and frame capture.
// It must be called at most once: two Run loops on the same channels and
// state would race (NewHarnessWithDefaults already calls it).
func (h *Harness) Run() {
if h.started {
panic("e2e: Harness.Run called twice")
}
h.started = true
h.logicWg.Add(1)
h.wg.Add(1)
go func() {
@@ -51,7 +61,7 @@ func (h *Harness) Run() {
for {
select {
case frame := <-h.logic.FrameChan():
h.capture.CaptureFrame(frame)
h.capture.CaptureFrame(frame.Elems)
case <-h.frameReceiverDone:
return
}
@@ -92,9 +102,65 @@ func (h *Harness) FrameCount() int {
return h.capture.FrameCount()
}
// State returns the editor state for inspection.
func (h *Harness) State() *editor.State {
return h.logic.State()
// Inspect runs fn on the logic goroutine and returns its result.
// This is the ONLY sanctioned way for a test to read or write state: the fn
// executes on the owner, preserving the single-owner invariant
// (architecture.md §1). fn must not block on sends to logic channels.
func (h *Harness) Inspect(fn func(st *editor.State) any) (any, error) {
v, ok := h.logic.Inspect(fn)
if !ok {
return nil, errInspectTimeout
}
return v, nil
}
// WithState runs fn on the logic goroutine for state setup or mutation.
func (h *Harness) WithState(fn func(st *editor.State)) error {
_, err := h.Inspect(func(st *editor.State) any {
fn(st)
return nil
})
return err
}
// FileLoaded reports whether the active file's chunked buffer has loaded
// content (owner-side check).
func (h *Harness) FileLoaded() (bool, error) {
v, err := h.Inspect(func(st *editor.State) any {
cb := st.Editor.ChunkedBuffer
return cb != nil && cb.FileLen() > 0
})
if err != nil {
return false, err
}
return v.(bool), nil
}
// FullContent returns the active file's full content (owner-side).
func (h *Harness) FullContent() (string, error) {
v, err := h.Inspect(func(st *editor.State) any {
if st.Editor.ChunkedBuffer != nil {
full, err := st.Editor.ChunkedBuffer.FullContent()
if err != nil {
return ""
}
return full
}
return st.Editor.Buffer
})
if err != nil {
return "", err
}
return v.(string), nil
}
// CursorPosition returns the editor cursor position (owner-side).
func (h *Harness) CursorPosition() (int, error) {
v, err := h.Inspect(func(st *editor.State) any { return st.Editor.CursorPosition })
if err != nil {
return 0, err
}
return v.(int), nil
}
// WaitForFrameCount blocks until at least N frames are captured.
+4 -2
View File
@@ -15,8 +15,10 @@ func TestEditorInitialLayout(t *testing.T) {
h := e2e.NewHarnessWithDefaults()
defer h.Cleanup()
// Switch to editor page
editor.GoToEditor(nil)
// Switch to editor page (owner-side)
if err := h.WithState(func(st *editor.State) { editor.GoToEditor(nil) }); err != nil {
t.Fatalf("GoToEditor: %v", err)
}
h.SendConfig(780, 1688)
// Wait for a new frame after switching to editor page
+44 -24
View File
@@ -9,13 +9,21 @@ import (
"pad/internal/ui"
)
// TestEditorClickToMoveCursorWithScroll verifies that a tap in the editor
// accounts for the current scroll offset and lands on the right line.
//
// State setup/assertions use the harness's owner-side helpers (WithState /
// CursorPosition / Inspect); the tap handler closure runs on the logic
// goroutine via SendInput, so its reads of editor.TheState are safe.
func TestEditorClickToMoveCursorWithScroll(t *testing.T) {
// NewHarnessWithDefaults already starts the logic goroutine.
h := e2e.NewHarnessWithDefaults()
h.Run() // Start the harness!
defer h.Cleanup()
// Switch to editor page
editor.GoToEditor(nil)
// Switch to editor page (owner-side)
if err := h.WithState(func(st *editor.State) { editor.GoToEditor(nil) }); err != nil {
t.Fatalf("GoToEditor: %v", err)
}
h.SendConfig(780, 1688)
// Give it a moment to initialize
time.Sleep(200 * time.Millisecond)
@@ -31,20 +39,24 @@ func TestEditorClickToMoveCursorWithScroll(t *testing.T) {
// - Line height = 14 * 1.2 = 16.8 (rounded?) Let's check EditorLineHeight()
// EditorLineHeight is 14 * 1.2 = 16.8.
lineHeight := 16.8
editor.TheState.Editor.Buffer = "Line 1\nLine 2\nLine 3"
// Scroll to start of Line 2 (skip Line 1)
editor.TheState.ScrollOffset = ui.Dp(lineHeight)
if err := h.WithState(func(st *editor.State) {
st.Editor.Buffer = "Line 1\nLine 2\nLine 3"
// GlyphLayout:
// Line 1: y = 0
// Line 2: y = 16.8
// Line 3: y = 33.6
editor.TheState.Editor.GlyphLayout = ui.GlyphLayout{
ByteOffsets: []int{0, 7, 14}, // Start of each line
X: []ui.Dp{10, 10, 10},
Y: []ui.Dp{ui.Dp(0), ui.Dp(lineHeight), ui.Dp(lineHeight * 2)},
Advance: []ui.Dp{10, 10, 10},
// Scroll to start of Line 2 (skip Line 1)
st.ScrollOffset = ui.Dp(lineHeight)
// GlyphLayout:
// Line 1: y = 0
// Line 2: y = 16.8
// Line 3: y = 33.6
st.Editor.GlyphLayout = ui.GlyphLayout{
ByteOffsets: []int{0, 7, 14}, // Start of each line
X: []ui.Dp{10, 10, 10},
Y: []ui.Dp{ui.Dp(0), ui.Dp(lineHeight), ui.Dp(lineHeight * 2)},
Advance: []ui.Dp{10, 10, 10},
}
}); err != nil {
t.Fatalf("WithState: %v", err)
}
// Tap at y=10 (within the text area).
@@ -52,7 +64,7 @@ func TestEditorClickToMoveCursorWithScroll(t *testing.T) {
// visualLine = (y + scroll) / lineHeight = (10 + 16.8) / 16.8 = 26.8 / 16.8 = 1.59 -> 1
// Line 1 is index 0. Line 2 is index 1.
// So visualLine 1 should be Line 2.
// The problem is that SetCursorFromPoint expects y in DP, but receives it as raw pixels
// if we're not careful. Let's pass the y value properly.
// The test harness sends raw pixel coordinates to handler.
@@ -60,10 +72,14 @@ func TestEditorClickToMoveCursorWithScroll(t *testing.T) {
// localY := float64(pt.Y - editorRegion.Y + TheState.ScrollOffset)
// So the handler receives Y as pt.Y, where pt.Y is relative to the screen.
// The test harness doesn't seem to account for region offset.
// Let's debug by printing in the test.
t.Logf("ScrollOffset: %v", editor.TheState.ScrollOffset)
// Let's debug by printing in the test (owner-side read).
v, err := h.Inspect(func(st *editor.State) any { return float64(st.ScrollOffset) })
if err != nil {
t.Fatalf("Inspect: %v", err)
}
t.Logf("ScrollOffset: %v", v)
h.SendInput([]ui.InputEvent{
{
Handler: func(data any) {
@@ -81,8 +97,12 @@ func TestEditorClickToMoveCursorWithScroll(t *testing.T) {
// Assert cursor moved to start of Line 2 (offset 7)
time.Sleep(100 * time.Millisecond) // Give logic goroutine a moment to process input
t.Logf("Cursor position: %d", editor.TheState.Editor.CursorPosition)
if editor.TheState.Editor.CursorPosition != 7 {
t.Errorf("expected cursor to move to 7 (Line 2), but got %d", editor.TheState.Editor.CursorPosition)
pos, err := h.CursorPosition()
if err != nil {
t.Fatalf("CursorPosition: %v", err)
}
t.Logf("Cursor position: %d", pos)
if pos != 7 {
t.Errorf("expected cursor to move to 7 (Line 2), but got %d", pos)
}
}
+64 -42
View File
@@ -22,8 +22,10 @@ func TestSearchFiltersList(t *testing.T) {
t.Fatalf("timeout waiting for initial frames: %v", err)
}
// Navigate to browser page
editor.GoToBrowser(nil)
// Navigate to browser page (owner-side)
if err := h.WithState(func(st *editor.State) { editor.GoToBrowser(nil) }); err != nil {
t.Fatalf("GoToBrowser: %v", err)
}
h.SendConfig(780, 1688)
time.Sleep(200 * time.Millisecond)
@@ -84,8 +86,10 @@ func TestSearchWithSortModeChange(t *testing.T) {
t.Fatalf("timeout waiting for initial frames: %v", err)
}
// Navigate to browser page
editor.GoToBrowser(nil)
// Navigate to browser page (owner-side)
if err := h.WithState(func(st *editor.State) { editor.GoToBrowser(nil) }); err != nil {
t.Fatalf("GoToBrowser: %v", err)
}
h.SendConfig(780, 1688)
time.Sleep(200 * time.Millisecond)
@@ -112,8 +116,10 @@ func TestSearchWithSortModeChange(t *testing.T) {
}
}
// Now toggle sort mode WHILE search is active
editor.ToggleSortOrder(nil)
// Now toggle sort mode WHILE search is active (owner-side)
if err := h.WithState(func(st *editor.State) { editor.ToggleSortOrder(nil) }); err != nil {
t.Fatalf("ToggleSortOrder: %v", err)
}
h.SendConfig(780, 1688)
time.Sleep(300 * time.Millisecond)
@@ -194,10 +200,10 @@ func TestSortModeChangePreservesSearchFilter(t *testing.T) {
t.Fatalf("timeout waiting for initial frames: %v", err)
}
state := h.State()
// Navigate to browser
editor.GoToBrowser(nil)
// Navigate to browser (owner-side)
if err := h.WithState(func(st *editor.State) { editor.GoToBrowser(nil) }); err != nil {
t.Fatalf("GoToBrowser: %v", err)
}
h.SendConfig(780, 1688)
time.Sleep(200 * time.Millisecond)
@@ -206,25 +212,33 @@ func TestSortModeChangePreservesSearchFilter(t *testing.T) {
h.SendSearchQuery(query)
time.Sleep(200 * time.Millisecond)
// Record search results before sort change
searchResultsBefore := make([]int, len(state.Browser.SearchResults))
copy(searchResultsBefore, state.Browser.SearchResults)
t.Logf("Search results before sort change: %v", searchResultsBefore)
// Record search results before sort change (owner-side snapshot)
_, err = h.Inspect(func(st *editor.State) any {
searchResultsBefore := make([]int, len(st.Browser.SearchResults))
copy(searchResultsBefore, st.Browser.SearchResults)
t.Logf("Search results before sort change: %v", searchResultsBefore)
// Verify all pre-sort results are valid matches
for _, sortedIdx := range state.Browser.SearchResults {
positionMap := state.Browser.GetSortedIndices()
rawIdx := positionMap[sortedIdx]
if rawIdx < len(state.Browser.SortIndex.Entries) {
entry := state.Browser.SortIndex.Entries[rawIdx]
if !strings.Contains(strings.ToLower(entry.Name), strings.ToLower(query)) {
t.Errorf("pre-sort: index %d (raw %d) -> %q does not match query %q", sortedIdx, rawIdx, entry.Name, query)
// Verify all pre-sort results are valid matches
for _, sortedIdx := range st.Browser.SearchResults {
positionMap := st.Browser.GetSortedIndices()
rawIdx := positionMap[sortedIdx]
if rawIdx < len(st.Browser.SortIndex.Entries) {
entry := st.Browser.SortIndex.Entries[rawIdx]
if !strings.Contains(strings.ToLower(entry.Name), strings.ToLower(query)) {
t.Errorf("pre-sort: index %d (raw %d) -> %q does not match query %q", sortedIdx, rawIdx, entry.Name, query)
}
}
}
return nil
})
if err != nil {
t.Fatalf("Inspect: %v", err)
}
// Toggle sort mode
editor.ToggleSortOrder(nil)
// Toggle sort mode (owner-side)
if err := h.WithState(func(st *editor.State) { editor.ToggleSortOrder(nil) }); err != nil {
t.Fatalf("ToggleSortOrder: %v", err)
}
h.SendConfig(780, 1688)
time.Sleep(300 * time.Millisecond)
@@ -237,23 +251,29 @@ func TestSortModeChangePreservesSearchFilter(t *testing.T) {
// Let's print the entries to see if they are still correct,
// ignoring the index values themselves.
for _, sortedIdx := range state.Browser.SearchResults {
if sortedIdx >= len(state.Browser.SortIndex.Entries) {
t.Errorf("search result index %d is out of bounds (total: %d)",
sortedIdx, state.Browser.TotalEntries)
continue
}
// Map sortedIdx back to rawIdx to check the actual entry
positionMap := state.Browser.GetSortedIndices()
rawIdx := positionMap[sortedIdx]
entry := state.Browser.SortIndex.Entries[rawIdx]
if !strings.Contains(strings.ToLower(entry.Name), strings.ToLower(query)) {
t.Errorf("post-sort: search result sortedIdx %d -> rawIdx %d -> %q does not match query %q",
sortedIdx, rawIdx, entry.Name, query)
// (Owner-side snapshot: all reads happen on the logic goroutine.)
_, err = h.Inspect(func(st *editor.State) any {
for _, sortedIdx := range st.Browser.SearchResults {
if sortedIdx >= len(st.Browser.SortIndex.Entries) {
t.Errorf("search result index %d is out of bounds (total: %d)",
sortedIdx, st.Browser.TotalEntries)
continue
}
// Map sortedIdx back to rawIdx to check the actual entry
positionMap := st.Browser.GetSortedIndices()
rawIdx := positionMap[sortedIdx]
entry := st.Browser.SortIndex.Entries[rawIdx]
if !strings.Contains(strings.ToLower(entry.Name), strings.ToLower(query)) {
t.Errorf("post-sort: search result sortedIdx %d -> rawIdx %d -> %q does not match query %q",
sortedIdx, rawIdx, entry.Name, query)
}
}
return nil
})
if err != nil {
t.Fatalf("Inspect: %v", err)
}
}
@@ -268,8 +288,10 @@ func TestSearchClearRestoresFullList(t *testing.T) {
t.Fatalf("timeout waiting for initial frames: %v", err)
}
// Navigate to browser page
editor.GoToBrowser(nil)
// Navigate to browser page (owner-side)
if err := h.WithState(func(st *editor.State) { editor.GoToBrowser(nil) }); err != nil {
t.Fatalf("GoToBrowser: %v", err)
}
h.SendConfig(780, 1688)
time.Sleep(200 * time.Millisecond)
+57 -29
View File
@@ -11,6 +11,42 @@ import (
"pad/internal/ui"
)
// sortModeOf reads the browser sort mode on the logic goroutine (owner).
func sortModeOf(t *testing.T, h *e2e.Harness) browser.SortMode {
t.Helper()
v, err := h.Inspect(func(st *editor.State) any { return st.Browser.SortMode })
if err != nil {
t.Fatalf("Inspect: %v", err)
}
return v.(browser.SortMode)
}
// pageCountOf reads the number of cached browser pages on the logic goroutine.
func pageCountOf(t *testing.T, h *e2e.Harness) int {
t.Helper()
v, err := h.Inspect(func(st *editor.State) any { return len(st.Browser.Pages) })
if err != nil {
t.Fatalf("Inspect: %v", err)
}
return v.(int)
}
// goBrowser navigates to the browser page on the logic goroutine.
func goBrowser(t *testing.T, h *e2e.Harness) {
t.Helper()
if err := h.WithState(func(st *editor.State) { editor.GoToBrowser(nil) }); err != nil {
t.Fatalf("GoToBrowser: %v", err)
}
}
// toggleSort toggles the browser sort mode on the logic goroutine.
func toggleSort(t *testing.T, h *e2e.Harness) {
t.Helper()
if err := h.WithState(func(st *editor.State) { editor.ToggleSortOrder(nil) }); err != nil {
t.Fatalf("ToggleSortOrder: %v", err)
}
}
// TestSortModeToggleCyclesThroughAllModes verifies that clicking the
// sort mode label cycles through all four sort modes.
//
@@ -26,10 +62,8 @@ func TestSortModeToggleCyclesThroughAllModes(t *testing.T) {
t.Fatalf("timeout waiting for initial frames: %v", err)
}
state := h.State()
// Navigate to browser page
editor.GoToBrowser(nil)
goBrowser(t, h)
// Trigger a frame
h.SendConfig(780, 1688)
@@ -41,7 +75,7 @@ func TestSortModeToggleCyclesThroughAllModes(t *testing.T) {
// Record the initial order of list items
initialItems := getListItems(t, lastFrame)
initialSortMode := state.Browser.SortMode
initialSortMode := sortModeOf(t, h)
t.Logf("Initial list items: %v", initialItems)
t.Logf("Initial SortMode: %d", initialSortMode)
@@ -51,9 +85,9 @@ func TestSortModeToggleCyclesThroughAllModes(t *testing.T) {
// Tap the sort label to cycle through all 4 modes
for cycle := 0; cycle < 4; cycle++ {
// Simulate tapping the sort label by calling the editor's ToggleSortOrder directly
// Simulate tapping the sort label by calling the editor's ToggleSortOrder
// (since SendInput doesn't route to the correct handler in e2e context)
editor.ToggleSortOrder(nil)
toggleSort(t, h)
// Trigger a new frame and wait for reload after cache clear
h.SendConfig(780, 1688)
@@ -63,7 +97,7 @@ func TestSortModeToggleCyclesThroughAllModes(t *testing.T) {
lastFrame = frames[len(frames)-1]
newItems := getListItems(t, lastFrame)
newSortMode := state.Browser.SortMode
newSortMode := sortModeOf(t, h)
t.Logf("Cycle %d: SortMode=%d, items=%v", cycle, newSortMode, newItems)
@@ -81,7 +115,7 @@ func TestSortModeToggleCyclesThroughAllModes(t *testing.T) {
}
// Verify the sort mode was actually changed in state
t.Logf("Final SortMode: %d", state.Browser.SortMode)
t.Logf("Final SortMode: %d", sortModeOf(t, h))
}
// TestSortModeToggleChangesEntryOrder verifies that toggling the sort mode
@@ -95,10 +129,8 @@ func TestSortModeToggleChangesEntryOrder(t *testing.T) {
t.Fatalf("timeout waiting for initial frames: %v", err)
}
state := h.State()
// Navigate to browser page
editor.GoToBrowser(nil)
goBrowser(t, h)
h.SendConfig(780, 1688)
time.Sleep(200 * time.Millisecond)
@@ -107,7 +139,7 @@ func TestSortModeToggleChangesEntryOrder(t *testing.T) {
// Record initial state
initialItems := getListItems(t, lastFrame)
initialSortMode := state.Browser.SortMode
initialSortMode := sortModeOf(t, h)
t.Logf("Before toggle: SortMode=%d, items=%v", initialSortMode, initialItems)
@@ -116,7 +148,7 @@ func TestSortModeToggleChangesEntryOrder(t *testing.T) {
}
// Toggle sort mode using editor's function (browser's was removed)
editor.ToggleSortOrder(nil)
toggleSort(t, h)
// Trigger a new frame
h.SendConfig(780, 1688)
@@ -126,7 +158,7 @@ func TestSortModeToggleChangesEntryOrder(t *testing.T) {
lastFrame = frames[len(frames)-1]
newItems := getListItems(t, lastFrame)
newSortMode := state.Browser.SortMode
newSortMode := sortModeOf(t, h)
t.Logf("After toggle: SortMode=%d, items=%v", newSortMode, newItems)
@@ -159,28 +191,26 @@ func TestSortModePagesNotClearedAfterToggle(t *testing.T) {
t.Fatalf("timeout waiting for initial frames: %v", err)
}
state := h.State()
// Navigate to browser page
editor.GoToBrowser(nil)
goBrowser(t, h)
h.SendConfig(780, 1688)
time.Sleep(200 * time.Millisecond)
// Record the number of cached pages before toggle
pagesBefore := len(state.Browser.Pages)
sortModeBefore := state.Browser.SortMode
pagesBefore := pageCountOf(t, h)
sortModeBefore := sortModeOf(t, h)
t.Logf("Before toggle: SortMode=%d, Pages=%d", sortModeBefore, pagesBefore)
// Toggle sort mode using editor's function (browser's was removed)
editor.ToggleSortOrder(nil)
toggleSort(t, h)
// Force a new frame to be rendered with the updated state
h.SendConfig(780, 1688)
time.Sleep(300 * time.Millisecond)
sortModeAfter := state.Browser.SortMode
pagesAfter := len(state.Browser.Pages)
sortModeAfter := sortModeOf(t, h)
pagesAfter := pageCountOf(t, h)
t.Logf("After toggle: SortMode=%d, Pages=%d", sortModeAfter, pagesAfter)
@@ -219,7 +249,7 @@ func TestSortModeLabelInHeader(t *testing.T) {
t.Fatalf("timeout waiting for initial frames: %v", err)
}
editor.GoToBrowser(nil)
goBrowser(t, h)
h.SendConfig(780, 1688)
time.Sleep(200 * time.Millisecond)
@@ -264,20 +294,18 @@ func TestSortModeLabelChangesAfterToggle(t *testing.T) {
t.Fatalf("timeout waiting for initial frames: %v", err)
}
state := h.State()
// Navigate to browser page
editor.GoToBrowser(nil)
goBrowser(t, h)
h.SendConfig(780, 1688)
time.Sleep(200 * time.Millisecond)
// Record initial sort mode
initialSortMode := state.Browser.SortMode
initialSortMode := sortModeOf(t, h)
// Toggle sort mode using editor's function (browser's was removed)
editor.ToggleSortOrder(nil)
toggleSort(t, h)
newSortMode := state.Browser.SortMode
newSortMode := sortModeOf(t, h)
t.Logf("SortMode changed from %d to %d", initialSortMode, newSortMode)
+35 -13
View File
@@ -13,23 +13,36 @@ import (
// TestTypeAtStartOfBuffer verifies that typing at cursor position 0 inserts
// characters at the start of the buffer without deleting characters from the end,
// and that they actually appear on screen (in the visible TextField).
//
// State reads go through the harness's owner-side helpers (Inspect runs the
// callback on the logic goroutine, the sole state owner).
func TestTypeAtStartOfBuffer(t *testing.T) {
// NewHarnessWithDefaults already starts the logic goroutine.
h := e2e.NewHarnessWithDefaults()
h.Run()
defer h.Cleanup()
// 1. Navigate to browser, then open a file.
editor.GoToBrowser(nil)
if err := h.WithState(func(st *editor.State) { editor.GoToBrowser(nil) }); err != nil {
t.Fatalf("GoToBrowser: %v", err)
}
time.Sleep(200 * time.Millisecond)
filename := "/notes.txt"
editor.OpenFile(filename)
if err := h.WithState(func(st *editor.State) { editor.OpenFile(filename) }); err != nil {
t.Fatalf("OpenFile: %v", err)
}
// 2. Wait for the file content to be loaded into the chunked buffer and line index built.
loaded := false
for i := 0; i < 30; i++ {
cb := h.State().Editor.ChunkedBuffer
if cb != nil && cb.FileLen() > 0 && cb.LineIndex != nil {
v, err := h.Inspect(func(st *editor.State) any {
cb := st.Editor.ChunkedBuffer
return cb != nil && cb.FileLen() > 0 && cb.LineIndex != nil
})
if err != nil {
t.Fatalf("Inspect: %v", err)
}
if v.(bool) {
loaded = true
break
}
@@ -39,18 +52,27 @@ func TestTypeAtStartOfBuffer(t *testing.T) {
t.Fatal("timed out waiting for file to load and line index to build")
}
// Record original file length and content
cb := h.State().Editor.ChunkedBuffer
originalLen := int(cb.FileLen())
originalContent, err := cb.FullContent()
// Record original file length and content (owner-side reads)
v, err := h.Inspect(func(st *editor.State) any {
return int(st.Editor.ChunkedBuffer.FileLen())
})
if err != nil {
t.Fatalf("Inspect: %v", err)
}
originalLen := v.(int)
originalContent, err := h.FullContent()
if err != nil {
t.Fatalf("failed to read original content: %v", err)
}
originalTail := originalContent[max(0, originalLen-20):]
// Confirm cursor is at position 0 (top of file).
if h.State().Editor.CursorPosition != 0 {
t.Fatalf("expected cursor at 0, got %d", h.State().Editor.CursorPosition)
pos, err := h.CursorPosition()
if err != nil {
t.Fatalf("CursorPosition: %v", err)
}
if pos != 0 {
t.Fatalf("expected cursor at 0, got %d", pos)
}
// Get initial frame to verify the text field content before typing.
@@ -85,7 +107,7 @@ func TestTypeAtStartOfBuffer(t *testing.T) {
time.Sleep(200 * time.Millisecond)
// 5. Assert on the buffer content.
newContent, err := h.State().Editor.ChunkedBuffer.FullContent()
newContent, err := h.FullContent()
if err != nil {
t.Fatalf("failed to read content after insert: %v", err)
}
@@ -135,7 +157,7 @@ func TestTypeAtStartOfBuffer(t *testing.T) {
// 6c. The visible text field length must be correct.
if len(finalTextField.Value) != expectedLen {
t.Errorf("expected visible text field length %d, got %d", expectedLen, len(finalTextField.Value))
t.Errorf("expected visible text field length %d, got %d", len(finalTextField.Value), expectedLen)
}
}