Restore last file, cursor, scroll, selection and find state on relaunch (spec §7)

Persist a tiny JSON snapshot (SessionState) written by the cmd layer
($HOME/.pad/session.json off-Android, /storage/emulated/0/Pad/ on
Android) and call the logic-owned snapshot rate-limited (<=1/s, on
change) from emitFrame plus unconditionally at Shutdown. On launch the
cmd layer hands the snapshot to Logic.BeginRestore before Run; the
file re-opens through the normal openFile path and lands straight on
the editor page.

- Cursor/selection land with the content, clamped to a shrunk file
  (path-guarded so a late result for a replaced file cannot apply the
  snapshot to the wrong buffer); a missing file falls back to the
  browser.
- Scroll is applied only after the first ScaleEvent has been laid out:
  the size ConfigEvent precedes it and the one-way MaxScroll clamp in a
  wrong-unit layout would corrupt the offset (found by e2e).
- Find: query + open/closed + current match are persisted; results are
  regenerated by re-scanning and the saved current match is re-selected
  by byte offset (Find.Restoring/RestoreMatch) without re-scrolling the
  restored viewport. A closed-bar query re-scans on the next bar open
  instead (an eager scan would be dropped and leave Scanning stuck).
- The main-owned find_bar widget is seeded with the restored query so
  its first frame matches the logic-side query.

Docs: spec.md gains §2.4 and drops the §7 row; invariant 5 updated;
architecture.md gains §6.7. Tests: 7 e2e tests covering cursor/scroll/
selection restore, clamping, missing-file fallback, find-bar restore
(open/closed), and the saver/shutdown persist paths.
This commit is contained in:
gmp
2026-08-20 16:01:02 -04:00
parent f31f849665
commit e3690d6b98
10 changed files with 961 additions and 23 deletions
+35 -1
View File
@@ -457,11 +457,45 @@ Only the visible byte range is shaped and drawn each frame:
- A browser tap sends the path on `OpenFileChan`. The logic goroutine creates
the `ChunkedBuffer`, dispatches `StatFile` (size guard) and the read +
`BuildLineIndex` tasks, switches `page` to the editor, and sets
`justOpenedAt`.
`justOpenedAt`. The relaunch restore (below) reuses the same `openFile`
path.
- **Opening-tap swallow:** the tap that opens the file is also delivered as an
editor tap in the same frame. A short time window (`justOpenedAt`) swallows
it so the viewport does not jump to the tapped (often EOF) position.
### 6.7 State restoration on relaunch (`session.go`)
- The restorable state is a plain comparable value, `SessionState` (last
file, cursor byte, scroll Dp, selection range, find query/visibility/
current-match byte). The search results themselves are not stored; they are
re-scanned on restore.
- **Ownership:** the logic goroutine owns snapshot content. The cmd layer
(`cmd/pad/main.go`) owns the JSON file and registers the writer via
`Logic.SetSessionSaver`; the owner invokes it rate-limited (≤ 1/s, only on
change) from `emitFrame` and unconditionally at `Shutdown` (post-exit,
single-threaded, next to `FlushAll`). Satisfies the single-owner rule:
the callback receives a value copy, and the file I/O is a tiny synchronous
write in the cmd layer's closure.
- **Restore:** the cmd layer reads the file at startup and calls
`Logic.BeginRestore(s)` BEFORE `Run()` (single-threaded window, like
`NewLogic` itself): it sets `Filename`, shows the editor page, and arms the
scroll. `Run()` then re-opens the file through the normal `openFile` path.
- **Stat success:** the find state lands (query, visibility, current-match
byte via `Find.Restoring`/`Find.RestoreMatch`, so the re-scan's first
result re-selects the saved match WITHOUT re-scrolling the restored
viewport).
- **Content arrival:** cursor/selection land, clamped to the file length
(path-guarded, so a late result for a replaced file cannot apply the
snapshot to the wrong buffer); the query re-scans only if the find bar
was open (a closed-bar scan would be dropped and leave `Scanning` stuck).
- **Scroll offset:** applied only after the first `ScaleEvent` has been
laid out: the size `ConfigEvent` precedes it, and a layout in between
computes the viewport in the wrong unit, whose one-way `MaxScroll` clamp
would corrupt the offset.
- **File gone** (stat failure): the restore is abandoned and the app lands
on the browser page with a clean editor. Any user open of another file
cancels an in-flight restore for the same reason as the path-guard.
## 7. Browser internals (`internal/browser`)
- `BrowserState` is **embedded by value** in `State` (single owner; no
+29 -6
View File
@@ -95,7 +95,8 @@ elsewhere.
the newer content when it completes ("latest state wins"). Writes stage to
a unique per-call temp file and rename into place, so a crash or a
concurrent reader never observes a partial file. Failed writes are retried.
This is the only persistence mechanism.
This is the only document persistence mechanism (the app's own state is a
separate tiny session file — §2.4).
### 2.3 Large files (measured)
@@ -110,6 +111,25 @@ elsewhere.
in-range files); edits splice only affected chunks. Details:
`architecture.md` §6.
### 2.4 State restoration on relaunch
- On launch, Pad re-opens the file from the last session and lands straight
on the editor page, restoring the cursor, scroll offset, live selection,
and the find bar (query, open/closed, current match). A relaunch therefore
never requires re-browsing to the last file.
- The snapshot is a tiny JSON file (a few hundred bytes) written by the
cmd layer: `$HOME/.pad/session.json` off-Android, and
`/storage/emulated/0/Pad/session.json` on Android (the dir that already
carries the browser's `.pad` index caches). Search results are NOT stored:
they are regenerated by re-scanning the restored query, and the current
match is re-selected by byte offset.
- The snapshot is written rate-limited (≤ 1/s, only on change) while the app
runs and unconditionally at shutdown, so a kill shortly after a change
loses at most ~1 s of state.
- If the restored file no longer exists (deleted/moved, e.g. by Syncthing),
the app falls back to the browser page; positions that exceed a shrunk
file are clamped to its new end.
## 3. Code organization (actual)
```
@@ -119,7 +139,8 @@ internal/
browser/ # BrowserState, BrowserManager, sort, search,
# pagination, layout, handlers
editor/ # Logic goroutine, State, ChunkedBuffer, LineIndex,
# IME handling, autosave, Frame handoff (frame.go)
# IME handling, autosave, relaunch session (session.go),
# Frame handoff (frame.go)
io/pool/ # Worker pool (priority lanes), task types,
# real/ — real filesystem (rooted at /)
# mock/ — in-memory FS for tests
@@ -153,9 +174,12 @@ Full details, channel topology, and ownership rules: [`architecture.md`](./archi
inflates memory (this caused a 1 GB leak, fixed in Phase 3).
4. **The IME snippet is the visible window**, and rune↔byte conversion happens
in one place (`HandleReplaceRange` / `RuneIndexToByte`).
5. **Autosave is the only persistence.** If state persistence (last file,
cursor, scroll) is added later, it must go through the same
owner-dispatches-a-task pattern.
5. **Persistence goes through the owner.** Autosave dispatches `WriteFile`
tasks for document content; the relaunch session (last file, cursor,
scroll, selection, find state) is marshaled by the owner and written by
the cmd layer's saver callback (tiny JSON, synchronous, torn writes
rejected on load). If session state ever grows beyond a few KB, move the
write to a worker-pool task (autosave pattern).
6. **Logic work stays < 16 ms.** Anything that can block or scan more than the
viewport goes to the worker pool.
7. **Scroll offset is always clamped to `[0, maxScroll]`,** where
@@ -183,7 +207,6 @@ recorded here so future rounds don't mistake doc text for behavior:
| Feature | Status | Notes |
|---|---|---|
| Undo (any) | **not implemented** | No undo stack exists; the old `SaveUndoTask` is dead code. |
| State restoration on relaunch | **not implemented** | Last file / cursor / scroll are not persisted. |
| External change detection | **not implemented** | No mtime compare on open/resume, no watcher, no Keep/Reload prompt. |
| Syncthing conflict handling | **not implemented** | No `.sync-conflict-*` file detection or merging. |
| File-system watcher | **not implemented** | Browser does not live-refresh; it re-scans on navigation. |