browser: document lazy loading implementation plan

- Add detailed §15 lazy loading plan with 7 implementation steps
- Update Phase 2 checklist with specific tasks
- Add E2E test harness for browser files
- Refactor browser layout and handler structure
- Add .gitignore for common patterns

WIP: Actual lazy loading not yet implemented.
This commit is contained in:
gmp
2026-05-31 18:43:46 +00:00
parent 6a43e3c0db
commit 3f1c881a06
8 changed files with 516 additions and 5 deletions
+261 -5
View File
@@ -643,11 +643,17 @@ The browser scroll position is persisted in the existing `state.json`:
- [ ] Wire into main event loop (replace placeholder browser)
- [ ] Basic scroll and tap-to-open
### Phase 2: Lazy Loading
- [ ] Page-based loading with worker dispatch
- [ ] Prefetch logic
- [ ] Page eviction under memory pressure
- [ ] Loading indicators for unloaded pages
### Phase 2: Lazy Loading (Detailed Plan)
See §15 for the complete lazy loading implementation plan with step-by-step details.
- [ ] Create `BrowserManager` orchestrator (Step 1)
- [ ] Wire initial directory load via `BuildIndexTask` (Step 2)
- [ ] Implement scroll-based prefetching (Step 3)
- [ ] Handle worker results in logic goroutine (Step 4)
- [ ] Implement page eviction (Step 5)
- [ ] Implement dirty page refresh (Step 6)
- [ ] Write E2E tests with mock filesystem (Step 7)
### Phase 3: Deferred — Alphabetical Index Sidebar
@@ -862,6 +868,256 @@ These run after all functional tests pass. They verify targets but do not block
---
## 15. Lazy Loading Implementation Plan (Detailed)
This section contains the detailed step-by-step plan for implementing lazy loading with the mock filesystem, enabling robust E2E testing with large simulated directories.
### 15.1 Current State Assessment
**What's Already Implemented:**
| Component | Status | Notes |
|-----------|--------|-------|
| Browser types | ✅ Complete | `BrowserState`, `Page`, `PageSize=100`, `PrefetchDist=2` |
| Page loading logic | ✅ Partial | `loadPageFromIndex()`, `LoadInitialPages()` exist but not wired |
| Worker pool | ✅ Complete | Priority dispatch, `LoadPagesTask` defined |
| Mock filesystem | ✅ Complete | Thread-safe, configurable delay |
| Test harness | ✅ Complete | Frame capture, input simulation |
**Gaps to Fill:**
1. **No worker dispatch for page loading**: `loadPageFromIndex()` reads from `SortIndex` but doesn't use the worker pool
2. **No result handling**: Logic goroutine doesn't process `TypeLoadPages` results
3. **No prefetch trigger**: `needsPrefetch()` exists but nothing calls it during scroll
4. **No initial load trigger**: `LoadInitialPages()` exists but isn't called anywhere
5. **No dirty page refresh**: `Page.Dirty` flag exists but no mechanism to refresh
---
### 15.2 Implementation Steps
#### Step 1: Add Browser Manager
Create a `BrowserManager` that orchestrates lazy loading operations.
**File:** `browser/manager.go` (new file)
```go
type BrowserManager struct {
state *BrowserState
workerPool *pool.WorkerPool
fs *mock.FileSystem
dirPath string
}
func NewBrowserManager(state *BrowserState, wp *pool.WorkerPool, fs *mock.FileSystem) *BrowserManager
func (bm *BrowserManager) NavigateTo(dirPath string)
func (bm *BrowserManager) OnScroll()
func (bm *BrowserManager) HandleResult(result pool.Result)
```
**Responsibilities:**
- Dispatch tasks to worker pool
- Handle results and update browser state
- Trigger prefetch on scroll
- Manage page lifecycle
---
#### Step 2: Wire Initial Directory Load
When navigating to a directory:
1. Dispatch `BuildIndexTask` to read from mock filesystem
2. On result: populate `SortIndex` and `TotalEntries`
3. Dispatch `LoadInitialPages()` to load visible pages
**Flow:**
```
NavigateTo(dirPath)
↓
BuildIndexTask(dirPath)
↓
Result: SortIndex populated
↓
LoadInitialPages()
↓
First frame rendered with visible entries
```
---
#### Step 3: Implement Scroll-Based Prefetching
In `HandleScroll()`:
1. Check which pages should be prefetched using `needsPrefetch()`
2. Dispatch `LoadPagesTask` for unloaded pages
3. Handle results by populating `Pages` map
**Key logic:**
```go
func (bm *BrowserManager) OnScroll() {
minPage, maxPage := computeVisiblePageRange(bm.state)
// Check for unloaded pages in prefetch range
for i := minPage - PrefetchDist; i <= maxPage + PrefetchDist; i++ {
if _, ok := bm.state.Pages[i]; !ok {
bm.dispatchLoadPage(i)
}
}
// Evict distant pages
bm.state.EvictPages()
}
```
---
#### Step 4: Handle Worker Results
In logic goroutine (editor/logic.go):
```go
case result := <-workerPool.ResultChan():
if result.IsBrowserResult() {
browserManager.HandleResult(result)
}
```
**Result handling:**
- `TypeBuildIndex`: Populate `SortIndex`, set `TotalEntries`, trigger initial page load
- `TypeLoadPages`: Update `Pages` map with loaded entries
- `TypeReadDir`: Handle directory read results
---
### 15.3 Memory Management
#### Step 5: Implement Page Eviction
In `HandleScroll()` or periodic timer:
1. Call `EvictPages()` to unload distant pages
2. Track memory usage (optional: add metrics)
**Eviction policy:**
- Keep pages within `PrefetchDist` of visible range
- Release `page.Entries` and set `Loaded = false`
- Keep `Page` struct for metadata
---
### 15.4 Dirty Page Handling
#### Step 6: Implement Dirty Page Refresh
When a page is marked dirty:
1. Reload from index
2. Merge into `Pages` map
**Dirty detection:**
- External file changes (via file watcher)
- Manual refresh trigger
- Periodic mtime check
---
### 15.5 E2E Tests
#### Step 7: Write Comprehensive Tests
**File:** `browser/lazy_loading_test.go` (new file)
```go
func TestLazyLoadingLargeDirectory(t *testing.T) {
// 1. Create mock filesystem with 10,000 entries
// 2. Navigate to directory
// 3. Verify only visible pages are loaded
// 4. Scroll down
// 5. Verify new pages are loaded
// 6. Verify old pages are evicted
}
func TestPrefetchOnScroll(t *testing.T) {
// 1. Load initial pages
// 2. Scroll slightly
// 3. Verify prefetch pages are loaded
}
func TestDirtyPageRefresh(t *testing.T) {
// 1. Load page
// 2. Mark as dirty
// 3. Verify page is reloaded
}
```
**Test scenarios:**
| Test | Purpose |
|------|--------|
| `TestLazyLoadingLargeDirectory` | Verify page-based loading works with 10k+ entries |
| `TestPrefetchOnScroll` | Verify prefetch distance is respected |
| `TestDirtyPageRefresh` | Verify dirty pages are reloaded |
| `TestEvictionUnderMemoryPressure` | Verify eviction works correctly |
| `TestConcurrentScrollAndLoad` | Verify no race conditions |
---
### 15.6 Architecture Diagram
```
┌─────────────────────────────────────────────────────────────┐
│ Logic Goroutine │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌────────────────┐ │
│ │ BrowserState│◄──►│BrowserMgr │ │ Result Handler│ │
│ │ (Pages map) │ │ (orchest.) │ │ (HandleResult)│ │
│ └─────────────┘ └─────┬──────┘ └────────────────┘ │
│ │ │
└───────────────────────────┼────────────────────────────────┘
│ Dispatch
▼
┌───────────────┐
│ Worker Pool │
│ (4 workers) │
└───────┬───────┘
│ Execute
▼
┌───────────────┐
│ Mock Filesystem│
│ (ReadDir) │
└───────────────┘
```
---
### 15.7 File Changes Summary
| File | Change | Purpose |
|------|--------|---------|
| `browser/manager.go` | **New** | Browser lazy loading orchestrator |
| `browser/browser.go` | Modify | Add `LoadPagesTask` dispatch |
| `browser/handlers.go` | Modify | Add prefetch on scroll |
| `editor/logic.go` | Modify | Wire result handling |
| `browser/lazy_loading_test.go` | **New** | E2E tests for lazy loading |
---
### 15.8 Key Design Decisions
1. **Page-based loading**: Load 100 entries at a time (configurable)
2. **Prefetch distance**: Load 2 pages beyond visible region
3. **Priority**: Page loads are `HighPriority` (user-visible)
4. **Eviction**: Remove pages beyond prefetch distance
5. **Mock filesystem**: Use configurable delay to simulate slow I/O in tests
---
### 15.9 Verification Strategy
1. **Unit tests**: Test page loading logic in isolation
2. **Integration tests**: Test with mock filesystem and worker pool
3. **E2E tests**: Test full flow with frame capture
4. **Stress tests**: 10,000+ entries with concurrent operations
---
## 14. Deferred Features
### 14.1 Alphabetical Index Sidebar (DEFERRED)