From 5e25db3e24e5dd62e3b4ae7218d63d6a722702aa Mon Sep 17 00:00:00 2001 From: Dasemu Date: Wed, 21 Oct 2026 04:08:36 +0200 Subject: [PATCH] fix(app): read views after queued writes, reload on write failure - Page and journal views read through the write queue after the previous view's pending saves, so they never load stale text. - A failed write reloads the current view and shows a message instead of leaving blocks on temporary ids; inserts also trigger reconciliation. - Completion replaces the query range, not up to the caret, and closes when the caret moves away. - Renaming a page reloads it so rewritten links are not overwritten. - Dropping below an expanded parent lands as its first child, where the indicator is drawn. Co-Authored-By: Claude Opus 5.5 --- app/lib/src/editor/block_row.dart | 18 ++++++++++------ app/lib/src/editor/completion.dart | 12 ++++++++--- app/lib/src/state/app_state.dart | 22 +++++++++++++++---- app/lib/src/state/outline_controller.dart | 9 ++++++-- app/lib/src/state/write_queue.dart | 7 +++--- app/lib/src/views/journals_view.dart | 6 +++++- app/lib/src/views/page_screen.dart | 17 +++++++++------ app/lib/src/views/shell.dart | 14 +++++++++++- app/test/logic_test.dart | 26 +++++++++++++++++++++-- 9 files changed, 102 insertions(+), 29 deletions(-) diff --git a/app/lib/src/editor/block_row.dart b/app/lib/src/editor/block_row.dart index 3b8510b..127b2e5 100644 --- a/app/lib/src/editor/block_row.dart +++ b/app/lib/src/editor/block_row.dart @@ -165,7 +165,9 @@ class _BlockRowState extends State { if (p.dy < box.size.height / 2) { d = _Drop.before; } else { - d = p.dx > contentX + 28 ? _Drop.child : _Drop.after; + // Below an expanded parent the gap is above its first child: drop there. + final expandedParent = widget.hasChildren && !n.collapsed; + d = expandedParent || p.dx > contentX + 28 ? _Drop.child : _Drop.after; } if (d != _drop) setState(() => _drop = d); } @@ -561,12 +563,7 @@ class _BlockEditorState extends State { void _accept(int i) { final q = _query; if (q == null || i >= _items.length) return; - final v = applyCompletion( - _text.text, - _text.selection.baseOffset, - q, - _items[i], - ); + final v = applyCompletion(_text.text, q, _items[i]); _closeCompletion(); _text.value = v; _last = v; @@ -643,6 +640,13 @@ class _BlockEditorState extends State { _closeCompletion(); return KeyEventResult.handled; } + // Moving the caret elsewhere ends the completion. + if (key == LogicalKeyboardKey.arrowLeft || + key == LogicalKeyboardKey.arrowRight || + key == LogicalKeyboardKey.home || + key == LogicalKeyboardKey.end) { + _closeCompletion(); + } } if (key == LogicalKeyboardKey.enter || diff --git a/app/lib/src/editor/completion.dart b/app/lib/src/editor/completion.dart index 1d14a89..486d341 100644 --- a/app/lib/src/editor/completion.dart +++ b/app/lib/src/editor/completion.dart @@ -82,15 +82,21 @@ CompletionQuery? detectCompletion(String text, int caret) { return best; } -/// Text after accepting `item` for `q` with the caret at `caret`. +/// Text after accepting `item` for `q` (replacing the query text, wherever the caret is). TextEditingValue applyCompletion( String text, - int caret, CompletionQuery q, CompletionItem item, ) { + final end = q.start + q.query.length; + if (end > text.length || text.substring(q.start, end) != q.query) { + return TextEditingValue( + text: text, + selection: TextSelection.collapsed(offset: text.length), + ); + } final head = text.substring(0, q.start); - var tail = text.substring(caret); + var tail = text.substring(end); switch (q.kind) { case CompletionKind.page: if (tail.startsWith(']]')) tail = tail.substring(2); diff --git a/app/lib/src/state/app_state.dart b/app/lib/src/state/app_state.dart index 64fc557..6faf9d2 100644 --- a/app/lib/src/state/app_state.dart +++ b/app/lib/src/state/app_state.dart @@ -34,8 +34,10 @@ class PageTarget extends AppRoute { /// paying for itself; rebuilds are scoped with `ListenableBuilder`. class AppState extends ChangeNotifier { AppState(this.backend, {WriteQueue? queue}) - : queue = queue ?? WriteQueue(onError: _logError), - refs = BlockRefCache(backend); + : refs = BlockRefCache(backend), + queue = queue ?? WriteQueue() { + this.queue.onError = _writeFailed; + } final GraphBackend backend; final WriteQueue queue; @@ -50,15 +52,27 @@ class AppState extends ChangeNotifier { /// Last page shown (for synapse reinforcement on navigation). String? _lastPageId; - /// Bumped when an error makes views reload from the core. + /// Bumped to make the current view reload from the core (failed writes, renames). int generation = 0; + /// Last write error, shown once by the shell. + String? writeError; + AppRoute get route => _route; bool get canGoBack => _back.isNotEmpty; bool get canGoForward => _forward.isNotEmpty; - static void _logError(Object e, StackTrace st) { + /// A failed write leaves the optimistic UI out of sync: reload the view from the core. + void _writeFailed(Object e, StackTrace st) { debugPrint('graph write failed: $e\n$st'); + writeError = '$e'; + reload(); + } + + /// Rebuilds the current view from the core (after queued writes have run). + void reload() { + generation++; + notifyListeners(); } void go(AppRoute r) { diff --git a/app/lib/src/state/outline_controller.dart b/app/lib/src/state/outline_controller.dart index ad1e842..16d740f 100644 --- a/app/lib/src/state/outline_controller.dart +++ b/app/lib/src/state/outline_controller.dart @@ -298,6 +298,7 @@ class OutlineController extends ChangeNotifier { if (wasFocused) focusedId = b.id; if (!_disposed) notifyListeners(); }); + _scheduleVerify(); } void _refocus(OutlineNode n, int? caret) { @@ -308,11 +309,15 @@ class OutlineController extends ChangeNotifier { } void _structural(Future> Function() op) { - _structuralEdits++; - final seen = _structuralEdits; _enqueue(() async { await op(); }); + _scheduleVerify(); + } + + void _scheduleVerify() { + _structuralEdits++; + final seen = _structuralEdits; _reconcile?.cancel(); _reconcile = Timer(const Duration(milliseconds: 600), () { if (seen == _structuralEdits) _verify(); diff --git a/app/lib/src/state/write_queue.dart b/app/lib/src/state/write_queue.dart index ff330a2..976085e 100644 --- a/app/lib/src/state/write_queue.dart +++ b/app/lib/src/state/write_queue.dart @@ -9,7 +9,7 @@ class WriteQueue { WriteQueue({this.onError}); /// Called with any error a task throws; the task's own future also completes with it. - final void Function(Object error, StackTrace stack)? onError; + void Function(Object error, StackTrace stack)? onError; final _tasks = Queue Function()>(); bool _running = false; @@ -23,13 +23,14 @@ class WriteQueue { return (_idle ??= Completer()).future; } - Future run(Future Function() task) { + /// Queues `task`. Reads pass `report: false` so their errors do not reach [onError]. + Future run(Future Function() task, {bool report = true}) { final done = Completer(); _tasks.add(() async { try { done.complete(await task()); } catch (e, st) { - onError?.call(e, st); + if (report) onError?.call(e, st); done.completeError(e, st); } }); diff --git a/app/lib/src/views/journals_view.dart b/app/lib/src/views/journals_view.dart index 099999b..ba2c51d 100644 --- a/app/lib/src/views/journals_view.dart +++ b/app/lib/src/views/journals_view.dart @@ -49,7 +49,11 @@ class _JournalsViewState extends State { final app = AppScope.read(context); try { final before = _days.isEmpty ? null : _days.last.view.page.journalDate; - final views = await app.backend.journals(before: before, limit: _batch); + if (_days.isEmpty) await WidgetsBinding.instance.endOfFrame; + final views = await app.queue.run( + () => app.backend.journals(before: before, limit: _batch), + report: false, + ); if (!mounted) return; setState(() { for (final v in views) { diff --git a/app/lib/src/views/page_screen.dart b/app/lib/src/views/page_screen.dart index 8e9ea33..d236c4a 100644 --- a/app/lib/src/views/page_screen.dart +++ b/app/lib/src/views/page_screen.dart @@ -41,12 +41,15 @@ class _PageScreenState extends State { final app = AppScope.read(context); try { final t = widget.target; - PageData? v; - if (t.id != null) { - v = await app.backend.page(t.id!); - } else { - v = await app.backend.openPage(t.title!); - } + // Read after the previous view's pending saves (flushed when it is disposed at the + // end of this frame) have reached the core. + await WidgetsBinding.instance.endOfFrame; + final v = await app.queue.run( + () => t.id != null + ? app.backend.page(t.id!) + : app.backend.openPage(t.title!).then((p) => p), + report: false, + ); if (!mounted) return; if (v == null) { setState(() => _error = 'This page no longer exists.'); @@ -228,6 +231,8 @@ class _TitleFieldState extends State<_TitleField> { await app.queue.run(() => app.backend.renamePage(widget.page.id, title)); _committed = title; app.renamed(widget.page.id, title); + // The core rewrote links in other blocks, possibly on this page: reload them. + app.reload(); } catch (e) { _text.text = _committed; messenger.showSnackBar(SnackBar(content: Text('Rename failed: $e'))); diff --git a/app/lib/src/views/shell.dart b/app/lib/src/views/shell.dart index 0219799..673c17c 100644 --- a/app/lib/src/views/shell.dart +++ b/app/lib/src/views/shell.dart @@ -27,6 +27,18 @@ class _ShellState extends State { final app = AppScope.of(context); final colors = context.colors; final route = app.route; + final error = app.writeError; + if (error != null) { + app.writeError = null; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!context.mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Could not save a change; reloaded. ($error)'), + ), + ); + }); + } return CallbackShortcuts( bindings: { const SingleActivator(LogicalKeyboardKey.keyK, control: true): () => @@ -96,7 +108,7 @@ class _ShellState extends State { ), Expanded( child: KeyedSubtree( - key: ValueKey(route), + key: ValueKey((route, app.generation)), child: switch (route) { JournalsRoute() => const JournalsView(), TimelineRoute() => const TimelineView(), diff --git a/app/test/logic_test.dart b/app/test/logic_test.dart index 0066290..e209e54 100644 --- a/app/test/logic_test.dart +++ b/app/test/logic_test.dart @@ -78,7 +78,6 @@ void main() { final tag = detectCompletion('x #se', 5)!; final v = applyCompletion( 'x #se', - 5, tag, const CompletionItem('Second Brain', 'Second Brain'), ); @@ -87,7 +86,6 @@ void main() { expect( applyCompletion( '[[Ru]]', - 4, page, const CompletionItem('Rust', 'Rust'), ).text, @@ -95,6 +93,16 @@ void main() { ); }); + test('replaces only the query even if the caret moved', () { + final q = detectCompletion('[[foo]]', 5)!; + final v = applyCompletion( + '[[foo]]', + q, + const CompletionItem('Foo', 'Foo'), + ); + expect(v.text, '[[Foo]]'); + }); + test('auto-pairs brackets', () { final v = autoPair( const TextEditingValue( @@ -152,6 +160,20 @@ void main() { }); }); + test('a failed write makes the app reload its view', () async { + final app = AppState(MemoryBackend()); + final gen = app.generation; + await app.queue + .run(() async => throw StateError('boom')) + .catchError((_) {}); + expect(app.generation, gen + 1); + expect(app.writeError, contains('boom')); + await app.queue + .run(() async => throw StateError('read'), report: false) + .catchError((_) {}); + expect(app.generation, gen + 1); + }); + test( 'WriteQueue runs tasks in order even when they finish out of order', () async {