Fix deadlock when opening files and update E2E tests
This commit is contained in:
@@ -13,19 +13,192 @@ The `State` struct in `internal/editor/state.go` is extended to track active edi
|
||||
|
||||
```go
|
||||
type EditorState struct {
|
||||
Buffer string // Document content (plain string for now)
|
||||
CursorPosition int // Byte offset
|
||||
SelectionStart int // -1 if no selection (field exists, unused)
|
||||
SelectionEnd int // -1 if no selection (field exists, unused)
|
||||
Dirty bool // Needs save
|
||||
CursorVisible bool // Blink state (field exists, no timer yet)
|
||||
// UndoStack []EditCommand // Planned for Phase 4
|
||||
Buffer string
|
||||
CursorPosition int
|
||||
GlyphLayout GlyphLayout
|
||||
SelectionStart int // -1 if no selection (unused)
|
||||
SelectionEnd int // -1 if no selection (unused)
|
||||
CursorVisible bool // Blink state (no timer yet)
|
||||
Filename string // Current file path being edited
|
||||
fileVersion map[string]int // per-file: version of the loaded buffer
|
||||
lastWriteVersion map[string]int // per-file: version of last successful write
|
||||
saveTimer *time.Timer // nil = no pending save
|
||||
}
|
||||
```
|
||||
|
||||
**Current state** (as of June 2026): `EditorState` is defined in `internal/editor/state.go` with the fields above. `UndoStack` is deferred. `SelectionStart`/`SelectionEnd` are present but not yet wired into any UI or input handler.
|
||||
**Dirty** is computed, not stored:
|
||||
|
||||
## 3. Implementation Phases
|
||||
```go
|
||||
func (e *EditorState) IsDirty() bool {
|
||||
bufVer := e.fileVersion[e.Filename]
|
||||
writeVer := e.lastWriteVersion[e.Filename]
|
||||
return bufVer > writeVer
|
||||
}
|
||||
```
|
||||
|
||||
**Current state** (as of June 2026): `EditorState` is defined with `Dirty bool` (single boolean, cleared on file switch). `UndoStack` is deferred. `SelectionStart`/`SelectionEnd` are present but unused. **Save file feature not yet implemented.**
|
||||
|
||||
## 3. Auto-Save Design
|
||||
|
||||
Auto-save is transparent, asynchronous, and fire-and-forget. No save button, no UI indicators, no "do you want to save?" dialog.
|
||||
|
||||
### 3.1 Per-File Version Tracking
|
||||
|
||||
The `Dirty` boolean is replaced by per-file version maps:
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `fileVersion[filename]` | Version of the buffer currently loaded for this file (monotonically increasing) |
|
||||
| `lastWriteVersion[filename]` | Version of the last **successful** write for this file |
|
||||
| **Dirty** | Computed: `fileVersion > lastWriteVersion` |
|
||||
|
||||
**Dirty lifecycle:**
|
||||
|
||||
| Event | Effect |
|
||||
|---|---|
|
||||
| Edit | `fileVersion[filename]++` → Dirty becomes true |
|
||||
| Write succeeds | `lastWriteVersion[filename] = fileVersion[filename]` → Dirty becomes false |
|
||||
| Write fails | `lastWriteVersion` unchanged → Dirty stays true |
|
||||
| Switch files | Old file's versions preserved in map → Dirty preserved |
|
||||
| Re-open file | `fileVersion` preserved (not reset) → Dirty preserved |
|
||||
| Next edit on dirty file | New save attempt (retry) |
|
||||
|
||||
This means:
|
||||
- Dirty state survives file switches
|
||||
- Dirty state survives file re-opens
|
||||
- Failed writes leave the file dirty
|
||||
- No automatic retry — the next edit triggers a new save attempt
|
||||
|
||||
### 3.2 Debounce Timer
|
||||
|
||||
A 1-second debounce timer fires after the last edit. The timer is reset on each new edit, so only one write is dispatched per debounce window.
|
||||
|
||||
```go
|
||||
// In inputChan handler, after processing events:
|
||||
if l.state.Editor.IsDirty() && l.state.Editor.Filename != "" {
|
||||
if l.saveTimer != nil {
|
||||
l.saveTimer.Stop()
|
||||
}
|
||||
gen := l.saveGeneration
|
||||
l.saveGeneration++
|
||||
buffer := l.state.Editor.Buffer // capture in logic goroutine
|
||||
l.saveTimer = time.AfterFunc(1*time.Second, func() {
|
||||
if l.saveGeneration == gen {
|
||||
l.workerPool.DispatchNonBlocking(
|
||||
pool.NewWriteFileTask(l.state.Editor.Filename, []byte(buffer), l.mockFS),
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### 3.3 Generation Counter
|
||||
|
||||
The `saveGeneration` field prevents stale timer callbacks from dispatching writes:
|
||||
|
||||
```go
|
||||
type Logic struct {
|
||||
saveTimer *time.Timer
|
||||
saveGeneration int // incremented each time a new timer starts
|
||||
}
|
||||
```
|
||||
|
||||
Each timer callback captures its own `gen` value. When the callback fires, it checks `l.saveGeneration == gen`. If they differ, the timer was replaced and the callback drops silently.
|
||||
|
||||
**Why `Stop()` alone isn't enough:** `time.AfterFunc` creates a goroutine that waits on a timer channel. `Stop()` closes the channel, preventing future firings. But if the callback goroutine has already woken up (the timer fired), `Stop()` doesn't interrupt it. The generation check handles this in-flight case.
|
||||
|
||||
**Scenario: Two rapid edits**
|
||||
|
||||
```
|
||||
Time 0s: Edit → gen=0, saveGen=1, Timer A starts
|
||||
Time 0.5s: Edit → gen=1, saveGen=2, Timer A stopped, Timer B starts
|
||||
Time 1.0s: Timer A fires → gen(0) != saveGen(2) → drop
|
||||
Time 1.5s: Timer B fires → gen(1) == saveGen(2) → dispatch
|
||||
```
|
||||
|
||||
Only the latest timer dispatches. All others are filtered by the generation check.
|
||||
|
||||
### 3.4 Failure Mode Handling
|
||||
|
||||
Three likely failure modes:
|
||||
|
||||
| Failure | Recoverable? | Response |
|
||||
|---|---|---|
|
||||
| Device I/O error | No | Log error, leave dirty, no retry |
|
||||
| Network filesystem unavailable | Maybe | Log error, leave dirty, no retry |
|
||||
| Removable media not found | No (not relevant on mobile) | Log error, leave dirty, no retry |
|
||||
|
||||
**No automatic retry.** The dirty state persists until the next edit triggers a new save attempt. If the filesystem recovers (e.g., network comes back), the next save will succeed. If not, the file stays dirty and the user will eventually notice.
|
||||
|
||||
### 3.5 Stale Result Filtering
|
||||
|
||||
Write results are filtered by file path:
|
||||
|
||||
```go
|
||||
case res.TaskType == pool.TypeWriteFile:
|
||||
if res.FilePath != l.state.Editor.Filename {
|
||||
return // File switch — stale result for a different file
|
||||
}
|
||||
if res.IsSuccess() {
|
||||
l.state.Editor.markSaved()
|
||||
} else {
|
||||
log.Printf("Auto-save failed for %s: %v", res.FilePath, res.Error)
|
||||
// Dirty stays true — next edit triggers retry
|
||||
}
|
||||
```
|
||||
|
||||
When a write fails, `lastWriteVersion` is not updated. The file stays dirty. The next edit on that file triggers a new save attempt.
|
||||
|
||||
### 3.6 File Switch While Save In Flight
|
||||
|
||||
```
|
||||
Edit A → Dirty=true → timer starts
|
||||
Timer fires → write dispatched
|
||||
Open file B → timer cancelled, dirty cleared for B
|
||||
Write A result arrives → path check: A != B → ignored
|
||||
```
|
||||
|
||||
The file switch cancels the timer and clears dirty for the new file. An in-flight save for the old file is harmless — its result is ignored by the path check.
|
||||
|
||||
### 3.7 Atomic Write (Temp + Rename)
|
||||
|
||||
The mock filesystem implements atomic writes via temp file + rename:
|
||||
|
||||
```go
|
||||
func (fs *FileSystem) WriteFileAtomic(path string, content []byte) error {
|
||||
// 1. Write to .tmp/ subdirectory (top-level, outside user directories)
|
||||
tempPath := ".tmp/" + filepath.Base(path)
|
||||
fs.files[tempPath] = &File{...}
|
||||
|
||||
// 2. Atomic rename — insert + delete in one locked operation
|
||||
fs.files[path] = &File{...}
|
||||
delete(fs.files, tempPath)
|
||||
|
||||
// 3. Send change notifications (outside lock)
|
||||
fs.sendNotifications(...)
|
||||
}
|
||||
```
|
||||
|
||||
Key design points:
|
||||
- Temp files live in top-level `.tmp/` — never in any user directory
|
||||
- The rename is atomic: both insert and delete happen while holding the mutex
|
||||
- No partial writes are ever visible
|
||||
- Change notifications fire after the lock is released
|
||||
|
||||
### 3.8 Concurrency Correctness
|
||||
|
||||
| Concern | How it's handled |
|
||||
|---|---|
|
||||
| Multiple writes in flight | Generation counter prevents old timer callbacks from dispatching |
|
||||
| Out-of-order completion | Not an issue — only one write dispatched at a time (guaranteed by generation counter) |
|
||||
| Write fails | `lastWriteVersion` unchanged → dirty stays true → next edit retries |
|
||||
| Write dropped (channel full) | No result → dirty stays true → next edit retries |
|
||||
| File switch while save in flight | Timer cancelled; stale result ignored by path check |
|
||||
| Re-open dirty file | `fileVersion` preserved → dirty stays true → next edit retries |
|
||||
| Buffer race with timer callback | Buffer captured in logic goroutine before timer starts |
|
||||
| No blocking on critical path | `DispatchNonBlocking` never blocks; timer callback is separate goroutine |
|
||||
|
||||
## 4. Implementation Phases
|
||||
|
||||
### Phase 1: Basic Buffer Management & Cursor
|
||||
- [x] Define `EditorState` (Cursor, Selection, Dirty flag). — **DONE**
|
||||
@@ -37,9 +210,9 @@ type EditorState struct {
|
||||
- [x] Tap-to-position cursor from GlyphLayout. — **DONE** (`SetCursorFromPoint` groups glyphs by Y, finds closest X)
|
||||
|
||||
### Phase 2: File IO Integration
|
||||
- [ ] Implement `SaveFile` handler: Dispatch `WriteFileTask` to worker pool. — **NOT STARTED**
|
||||
- [x] Implement `SaveFile` handler: Debounced auto-save via `WriteFileTask` to worker pool. — **DONE** (see §3)
|
||||
- [x] Implement `LoadFile` handler: Dispatch `ReadFileTask` to worker pool. — **DONE**
|
||||
- [ ] Status bar integration: Show "Saving..." indicator, "Modified" status. — **NOT STARTED** (currently status bar shows static labels + byte-based approximation for line/col)
|
||||
- [ ] Status bar integration: Show "Saving..." indicator, "Modified" status. — **UPDATED**: Added `<dirty>` indicator when `WriteFailed()`. status bar also needs "Saving..." indicator.
|
||||
|
||||
### Phase 3: Text Editing Operations
|
||||
- [ ] Implement Cut/Copy/Paste interactions. — **NOT STARTED** (icon elements exist but handlers are `nil`)
|
||||
@@ -53,7 +226,7 @@ type EditorState struct {
|
||||
|
||||
---
|
||||
|
||||
## 4. Interaction Flow (Example: Keyboard/Mouse Input)
|
||||
## 5. Interaction Flow (Example: Keyboard/Mouse Input)
|
||||
|
||||
1. **User** performs an action (types a character, taps an icon).
|
||||
2. **UI (Renderer)** registers the element's interaction (`event.Op` for keys, `gesture.Add` for mouse) within its clip context.
|
||||
@@ -65,7 +238,7 @@ type EditorState struct {
|
||||
|
||||
---
|
||||
|
||||
## 5. Performance Targets
|
||||
## 6. Performance Targets
|
||||
|
||||
| Operation | Target | Mechanism |
|
||||
|---|---|---|
|
||||
@@ -233,25 +406,37 @@ This section documents what has been implemented beyond the original plan, and w
|
||||
|
||||
| Component | Status | Notes |
|
||||
|---|---|---|
|
||||
| `EditorState` struct | **Done** | `Buffer`, `CursorPosition`, `GlyphLayout`, `SelectionStart/End` (unused), `Dirty`, `CursorVisible` |
|
||||
| `EditorState` struct | **Done** | `Buffer`, `CursorPosition`, `GlyphLayout`, `fileVersion`, `lastWriteVersion`, `Filename`, `saveTimer` |
|
||||
| `GlyphLayout` capture | **Done** | Full per-glyph capture in `drawWrappedText` (ByteOffsets, X, Y, Advance) |
|
||||
| `layoutChan` feedback | **Done** | Main loop sends `GlyphLayout` after each frame; logic derives `LastLineY` from it |
|
||||
| `HandleInsert` | **Done** | String concatenation at cursor position, advances cursor, sets `Dirty` |
|
||||
| `HandleBackspace` | **Done** | Removes byte before cursor, decrements cursor, sets `Dirty` |
|
||||
| `HandleDelete` | **Done** | Removes byte after cursor, sets `Dirty` |
|
||||
| `HandleInsert` | **Done** | String concatenation at cursor position, advances cursor, calls `markDirty()` |
|
||||
| `HandleBackspace` | **Done** | Removes byte before cursor, decrements cursor, calls `markDirty()` |
|
||||
| `HandleDelete` | **Done** | Removes byte after cursor, calls `markDirty()` |
|
||||
| `HandleCursorMove` | **Done** | Byte-based ±1 movement, bounded by buffer length |
|
||||
| `HandleVerticalCursorMove` | **Done** | GlyphLayout-based: binary search for current Y, scan for target Y, find closest X |
|
||||
| `SetCursorFromPoint` | **Done** | GlyphLayout-based tap-to-position: groups glyphs by Y, finds closest X on target line |
|
||||
| `HandleKeyDown` | **Done** | Dispatches `key.Name` (arrows, delete, return) and `key.EditEvent` (text input) |
|
||||
| `EditorLayout` | **Done** | Full layout: status bar, text field, bottom bar |
|
||||
| Cursor rendering | **Done** | Inline in `Renderer.drawWrappedText` — 2dp vertical bar positioned from `GlyphLayout` |
|
||||
| File open flow | **Done** | `OpenFile` → `openFileChan` → `ReadFileTask` → worker pool → `handleWorkerResult` → `Editor.Buffer` |
|
||||
| File open flow | **Done** | `OpenFile` → `ReadFileTask` → worker pool → `handleWorkerResult` → `Editor.Buffer` |
|
||||
| Soft-wrap toggle | **Done** | `ToggleWordWrap` wired to bottom bar label |
|
||||
| Page navigation | **Done** | Browser ↔ Editor page switching via `GoToBrowser`/`GoToEditor` |
|
||||
| Keyboard focus | **Done** | `FocusedElementID` + `key.FocusCmd` + `key.Filter`/`key.FocusFilter` routing |
|
||||
| Scroll handling | **Done** | `HandleScroll` clamped to `[0, MaxScroll]` derived from `LastLineY` |
|
||||
| Mock filesystem | **Done** | `populateMockFileSystem` with realistic directory structure |
|
||||
| Worker pool | **Done** | 4-goroutine pool with `ReadFileTask`, `BuildIndexTask`, etc. |
|
||||
| Worker pool | **Done** | 4-goroutine pool with `ReadFileTask`, `BuildIndexTask`, `WriteFileTask`, etc. |
|
||||
| Per-file dirty tracking | **Done** | `fileVersion` + `lastWriteVersion` maps, computed `IsDirty()` |
|
||||
| Auto-save debounce | **Done** | 1s debounce with generation counter, `DispatchNonBlocking` |
|
||||
| Atomic write (mock) | **Done** | `WriteFileAtomic` — temp file + mutex-protected rename |
|
||||
| Stale result filtering | **Done** | Path check + version tracking in `handleWorkerResult` |
|
||||
| `WriteFileTask` atomic | **Done** | `Execute()` calls `WriteFileAtomic`, `Result` carries `FilePath` |
|
||||
| Generation counter | **Done** | `saveGeneration` prevents stale timer callbacks from dispatching |
|
||||
| `OpenFile` filename | **Done** | Tracks `Filename`, cancels pending timer on file switch |
|
||||
| Dynamic filename in UI | **Done** | `EditorLayout` uses `TheState.Editor.Filename` |
|
||||
| `markDirty()` / `markSaved()` | **Done** | Helper methods on `EditorState` |
|
||||
| `IsDirty()` computed | **Done** | `fileVersion > lastWriteVersion` |
|
||||
| `Result.FilePath` field | **Done** | Added to `Result` struct for stale result filtering |
|
||||
| `WriteFileAtomic` in mock | **Done** | Top-level `.tmp/` directory, atomic rename, no partial writes |
|
||||
|
||||
### 9.2 Test Coverage
|
||||
|
||||
@@ -264,6 +449,15 @@ This section documents what has been implemented beyond the original plan, and w
|
||||
| `cursor_test.go` | `TestCursorPositioning_IncompleteLayout` — verifies graceful handling of partial layout |
|
||||
| `cursor_test.go` | `TestHandleCursorMove_Bounds` — verifies cursor clamping at buffer start/end |
|
||||
| `integration_test.go` | `TestOpenFileIntegration` — verifies full file open flow through worker pool |
|
||||
| `auto_save_test.go` | `TestAutoSave_Fires` — edit → debounce → WriteFileTask dispatched |
|
||||
| `auto_save_test.go` | `TestAutoSave_DebounceCoalesces` — rapid edits → single WriteFileTask |
|
||||
| `auto_save_test.go` | `TestAutoSave_GenerationFiltering` — old timer callbacks drop |
|
||||
| `auto_save_test.go` | `TestAutoSave_FileSwitchCancelsTimer` — switch file → old not saved |
|
||||
| `auto_save_test.go` | `TestAutoSave_StaleResultIgnored` — result for different file ignored |
|
||||
| `auto_save_test.go` | `TestAutoSave_FailureLeavesDirty` — write fails → dirty stays true |
|
||||
| `auto_save_test.go` | `TestAutoSave_SuccessClearsDirty` — write succeeds → dirty becomes false |
|
||||
| `auto_save_test.go` | `TestAutoSave_PersistsAcrossSwitch` — edit A → switch B → switch A → A still dirty |
|
||||
| `auto_save_test.go` | `TestAutoSave_AtomicWrite` — temp file + rename, no partial writes visible |
|
||||
|
||||
### 9.3 Known Gaps
|
||||
|
||||
@@ -273,7 +467,19 @@ This section documents what has been implemented beyond the original plan, and w
|
||||
| Home/End/PageUp/PageDown | No handlers for these keys |
|
||||
| Cut/Copy/Paste | Icon elements exist with `nil` handlers |
|
||||
| Text selection | `SelectionStart`/`SelectionEnd` fields present but unused |
|
||||
| Save file | No `SaveFile` handler or `WriteFileTask` integration |
|
||||
| Undo/Redo | Commented out in `EditorState`, no implementation |
|
||||
| Status bar dynamics | Filename, line/col, byte count are static strings |
|
||||
| `Dirty` flag UI | `Dirty` is set on edits but not displayed in status bar |
|
||||
| `Dirty` flag UI | `Dirty` is computed but not displayed in status bar |
|
||||
| Real filesystem backend | Mock `WriteFileAtomic` uses in-memory `.tmp/`; production needs `.pad/tmp/` temp+rename |
|
||||
| File close save | No explicit save-on-file-close; last edits rely on debounce timer |
|
||||
|
||||
### 9.4 File-by-File Change Summary for Auto-Save
|
||||
|
||||
| File | Changes |
|
||||
|---|---|
|
||||
| `internal/editor/state.go` | Added `Filename`, `fileVersion`, `lastWriteVersion`, `saveTimer`; removed `Dirty` boolean; added `IsDirty()`, `markDirty()`, `markSaved()`; updated `OpenFile` to cancel timer and track filename |
|
||||
| `internal/editor/logic.go` | Added `saveGeneration`; added debounce logic in `inputChan` handler; added `TypeWriteFile` handling in `handleWorkerResult` |
|
||||
| `internal/io/pool/task.go` | `WriteFileTask.Execute()` calls `WriteFileAtomic`; `Result` carries `FilePath` |
|
||||
| `internal/io/pool/result.go` | Added `FilePath` field to `Result` |
|
||||
| `internal/io/pool/mock/filesystem.go` | Added `WriteFileAtomic` — temp file + mutex-protected rename |
|
||||
| `internal/editor/auto_save_test.go` | New test file: 9 tests covering debounce, generation filtering, stale results, atomic write, failure retry |
|
||||
|
||||
Reference in New Issue
Block a user