From 25437b3181e75fa5191bd76616cf14d950c3124e Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 24 Oct 2026 10:52:01 +0100 Subject: [PATCH] fix(settings): preserve server editor drafts until save succeeds --- .../settings/saved_server_editor.dart | 81 +++++--- .../settings/saved_servers_section.dart | 21 ++- app/notes/settings-server-editor-save-ux.md | 50 +++++ .../saved_server_editor_save_test.dart | 177 ++++++++++++++++++ app/tool/server_editor_save_probe.dart | 44 +++++ app/tool/server_editor_save_probe.mjs | 68 +++++++ 6 files changed, 414 insertions(+), 27 deletions(-) create mode 100644 app/notes/settings-server-editor-save-ux.md create mode 100644 app/test/features/settings/saved_server_editor_save_test.dart create mode 100644 app/tool/server_editor_save_probe.dart create mode 100644 app/tool/server_editor_save_probe.mjs diff --git a/app/lib/features/settings/saved_server_editor.dart b/app/lib/features/settings/saved_server_editor.dart index 772aa9af..490fc5c4 100644 --- a/app/lib/features/settings/saved_server_editor.dart +++ b/app/lib/features/settings/saved_server_editor.dart @@ -4,11 +4,14 @@ import 'package:flutter/material.dart'; import '../../core/servers/server_catalog.dart'; import '../../ui/adaptive/host.dart'; +/// When supplied, [onSave] must finish successfully before the route closes. +/// Throwing keeps the draft open and displays the error for a retry. Future editSavedServer( BuildContext context, { SavedServer? server, + Future Function(SavedServer)? onSave, }) { - final page = _ServerEditor(server: server); + final page = _ServerEditor(server: server, onSave: onSave); return Navigator.of(context).push( usesCupertinoHost(context) ? CupertinoPageRoute(builder: (_) => page) @@ -17,35 +20,51 @@ Future editSavedServer( } class _ServerEditor extends StatefulWidget { - const _ServerEditor({this.server}); + const _ServerEditor({this.server, this.onSave}); final SavedServer? server; + final Future Function(SavedServer)? onSave; @override State<_ServerEditor> createState() => _ServerEditorState(); } class _ServerEditorState extends State<_ServerEditor> { + // Keep the identity through retries, including a persisted profile whose + // connection activation failed after the write succeeded. + late final _id = + widget.server?.id ?? 'server-${DateTime.now().microsecondsSinceEpoch}'; late final _name = TextEditingController(text: widget.server?.name ?? ''); late final _addresses = TextEditingController( text: widget.server?.endpoints.join('\n') ?? '', ); String? _error; + bool _saving = false; - void _save() { + Future _save() async { + if (_saving) return; try { final server = SavedServer.validated( - id: - widget.server?.id ?? - 'server-${DateTime.now().microsecondsSinceEpoch}', + id: _id, name: _name.text, legacyEndpoint: widget.server?.legacyEndpoint, endpoints: _addresses.text .split('\n') .where((line) => line.trim().isNotEmpty), ); + setState(() { + _saving = true; + _error = null; + }); + await widget.onSave?.call(server); + if (!mounted) return; Navigator.of(context).pop(server); } catch (error) { - setState(() => _error = '$error'); + if (mounted) { + setState(() { + _saving = false; + _error = '$error'; + }); + } } } @@ -71,6 +90,7 @@ class _ServerEditorState extends State<_ServerEditor> { CupertinoTextField( key: Key(key), controller: controller, + enabled: !_saving, placeholder: multiline ? 'wss://server.example/connect' : 'Home', minLines: multiline ? 3 : 1, maxLines: multiline ? null : 1, @@ -85,6 +105,7 @@ class _ServerEditorState extends State<_ServerEditor> { return TextField( key: Key(key), controller: controller, + enabled: !_saving, decoration: InputDecoration( labelText: label, border: const OutlineInputBorder(), @@ -100,12 +121,16 @@ class _ServerEditorState extends State<_ServerEditor> { Widget build(BuildContext context) { final cupertino = usesCupertinoHost(context); final title = widget.server == null ? 'Add server' : 'Edit server'; + final saveLabel = _saving ? 'Saving server…' : 'Save server'; final save = cupertino ? CupertinoButton.filled( - onPressed: _save, - child: const Text('Save server'), + onPressed: _saving ? null : _save, + child: Text(saveLabel), ) - : FilledButton(onPressed: _save, child: const Text('Save server')); + : FilledButton( + onPressed: _saving ? null : _save, + child: Text(saveLabel), + ); final body = SafeArea( child: ListView( padding: const EdgeInsets.all(16), @@ -131,12 +156,15 @@ class _ServerEditorState extends State<_ServerEditor> { if (_error != null) Padding( padding: const EdgeInsets.only(top: 12), - child: Text( - _error!, - style: TextStyle( - color: cupertino - ? CupertinoColors.systemRed.resolveFrom(context) - : Theme.of(context).colorScheme.error, + child: Semantics( + liveRegion: true, + child: Text( + _error!, + style: TextStyle( + color: cupertino + ? CupertinoColors.systemRed.resolveFrom(context) + : Theme.of(context).colorScheme.error, + ), ), ), ), @@ -145,14 +173,17 @@ class _ServerEditorState extends State<_ServerEditor> { ], ), ); - return cupertino - ? CupertinoPageScaffold( - navigationBar: CupertinoNavigationBar(middle: Text(title)), - child: body, - ) - : Scaffold( - appBar: AppBar(title: Text(title)), - body: body, - ); + return PopScope( + canPop: !_saving, + child: cupertino + ? CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar(middle: Text(title)), + child: body, + ) + : Scaffold( + appBar: AppBar(title: Text(title)), + body: body, + ), + ); } } diff --git a/app/lib/features/settings/saved_servers_section.dart b/app/lib/features/settings/saved_servers_section.dart index 9896d417..0e52c963 100644 --- a/app/lib/features/settings/saved_servers_section.dart +++ b/app/lib/features/settings/saved_servers_section.dart @@ -8,13 +8,30 @@ import '../../ui/adaptive/host.dart'; import 'saved_server_editor.dart'; import 'server_connections.dart'; +class _ServerSaveFailure implements Exception { + const _ServerSaveFailure(this.message); + final String message; + + @override + String toString() => message; +} + class SavedServersSection extends StatelessWidget { const SavedServersSection({super.key, required this.connections}); final ServerConnections connections; Future _edit(BuildContext context, [SavedServer? server]) async { - final edited = await editSavedServer(context, server: server); - if (edited != null) await connections.save(edited); + await editSavedServer( + context, + server: server, + onSave: (edited) async { + if (!await connections.save(edited)) { + throw _ServerSaveFailure( + connections.error ?? 'The server configuration could not be saved.', + ); + } + }, + ); } Future _remove(BuildContext context, SavedServer server) async { diff --git a/app/notes/settings-server-editor-save-ux.md b/app/notes/settings-server-editor-save-ux.md new file mode 100644 index 00000000..8b20e89f --- /dev/null +++ b/app/notes/settings-server-editor-save-ux.md @@ -0,0 +1,50 @@ +# Settings server editor save/retry UX + +## Finding and scoped fix + +The editor popped its route with a validated draft before `connections.save` +started. A rejected persistence write therefore lost the typed configuration. +The section now supplies an optional awaited `onSave` callback; the route closes +only on success. Errors appear inline (live-region semantics), preserving both +fields. Native controls show `Saving server…`; fields, duplicate submissions and +Back are blocked only while the save is pending. Normal Back/cancel and existing +callers without the callback retain their route/result behavior. + +New profile identity is stable through retries. This also prevents a duplicate +profile if persistence succeeds but subsequent connection activation fails. +Selection, server isolation, catalog persistence and connection APIs are unchanged. +No shell, navigation foundation, theme, transport or device changes. + +Actual source diff: `saved_server_editor.dart` adds awaited save/pending/error +handling and stable draft identity; `saved_servers_section.dart` moves persistence +inside that callback instead of saving after the editor has popped. + +## Evidence and checks + +- Four new regression cases (Material + Cupertino, failed edit/pending/retry and + failed activation/add/retry) failed against the original source and pass now. + Two additional cases verify Back cancels drafts without persistence/activation. +- `flutter test test/features/settings test/core/servers + test/application/server_selection_test.dart + test/application/server_fallback_wiring_test.dart`: **88 passed**. +- `flutter analyze`: **no issues**. +- `flutter build web`: **passed**, including Wasm dry run. +- Isolated browser fixture build and `node tool/server_editor_save_probe.mjs`: + **12 checks passed** at 390×844 across Material and Cupertino hosts, including + actual typing, pending/repeated click, failure draft retention and retry. + Fixture uses only in-memory persistence, loopback static hosting, a fresh Chrome + profile and OS-assigned ports; no server/socket/production requests. +- Six PNG captures and `result.json` live in + `app/build/server-editor-save-evidence/` in this worktree (ignored build output). + Both failure/draft captures were visually inspected: fields, error and retry + control are visible without overflow. Probe Chrome and loopback server exited. + +## Limits + +Browser fixture is not an end-to-end production storage test. Native Android/iOS, +screen-reader speech and physical-device behavior are unverified. No deployment, +APK build, installation, ADB, production data changes or shared-service restart. +`PipelinesRoot._activate` replaces the native app during connection activation; +draft retention across a failure after that root remount is not verified/fixed +here. The activation-error retry test uses an injected callback without remount. +Rejected persistence writes never invoke activation and do retain the editor. diff --git a/app/test/features/settings/saved_server_editor_save_test.dart b/app/test/features/settings/saved_server_editor_save_test.dart new file mode 100644 index 00000000..d7120f5d --- /dev/null +++ b/app/test/features/settings/saved_server_editor_save_test.dart @@ -0,0 +1,177 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/servers/server_catalog.dart'; +import 'package:pipelines_app/core/servers/server_catalog_store.dart'; +import 'package:pipelines_app/features/settings/saved_servers_section.dart'; +import 'package:pipelines_app/features/settings/server_connections.dart'; + +class _ControlledStore extends MemoryServerCatalogStore { + _ControlledStore({super.catalog}); + + final writes = []; + Completer? pending; + + @override + Future save(ServerCatalog catalog) async { + writes.add(catalog); + if (pending != null && !await pending!.future) return false; + return super.save(catalog); + } +} + +Future _openEditor( + WidgetTester tester, + ServerConnections connections, + bool cupertino, { + bool edit = false, +}) async { + final body = SingleChildScrollView( + child: SavedServersSection(connections: connections), + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp( + home: CupertinoPageScaffold(child: SafeArea(child: body)), + ) + : MaterialApp(home: Scaffold(body: body)), + ); + await tester.tap(find.text(edit ? 'Edit Home' : 'Add server')); + await tester.pumpAndSettle(); + await tester.enterText( + find.byKey(const Key('server-profile-name')), + 'My home', + ); + await tester.enterText( + find.byKey(const Key('server-profile-addresses')), + 'wss://home.test/connect\nws://192.168.1.2:8083/connect', + ); + await tester.ensureVisible(find.text('Save server')); + await tester.pumpAndSettle(); +} + +void main() { + for (final cupertino in [false, true]) { + testWidgets('Back cancels an unsaved draft ($cupertino)', (tester) async { + final store = _ControlledStore(); + final connections = ServerConnections( + store: store, + onSelected: (_) async => fail('Cancel must not select a server'), + ); + addTearDown(connections.dispose); + await _openEditor(tester, connections, cupertino); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('server-profile-name')), findsNothing); + expect(store.writes, isEmpty); + expect(connections.catalog.servers, isEmpty); + }); + + testWidgets( + 'failed edit keeps draft and blocks duplicate save ($cupertino)', + (tester) async { + final original = SavedServer.validated( + id: 'home', + name: 'Home', + endpoints: ['wss://home.test/connect'], + ); + final store = _ControlledStore( + catalog: ServerCatalog(servers: [original], selectedId: original.id), + )..pending = Completer(); + final activations = []; + final connections = ServerConnections( + store: store, + onSelected: (server) async => activations.add(server), + ); + addTearDown(connections.dispose); + await connections.load(); + await _openEditor(tester, connections, cupertino, edit: true); + await tester.tap(find.text('Save server')); + await tester.pump(); + + expect(find.text('Saving server…'), findsOneWidget); + final button = find.widgetWithText( + cupertino ? CupertinoButton : FilledButton, + 'Saving server…', + ); + expect( + cupertino + ? tester.widget(button).onPressed + : tester.widget(button).onPressed, + isNull, + ); + await tester.tap(find.text('Saving server…')); + await tester.binding.handlePopRoute(); + await tester.pump(); + expect(find.byKey(const Key('server-profile-name')), findsOneWidget); + expect(store.writes, hasLength(1)); + expect(connections.catalog.active?.name, 'Home'); + expect(activations, isEmpty); + + store.pending!.complete(false); + await tester.pumpAndSettle(); + expect(find.textContaining('could not be saved'), findsOneWidget); + final name = tester.widget( + find.descendant( + of: find.byKey(const Key('server-profile-name')), + matching: find.byType(EditableText), + ), + ); + final addresses = tester.widget( + find.descendant( + of: find.byKey(const Key('server-profile-addresses')), + matching: find.byType(EditableText), + ), + ); + expect(name.controller.text, 'My home'); + expect(addresses.controller.text, contains('ws://192.168.1.2:8083')); + expect(connections.catalog.active?.name, 'Home'); + + store.pending = null; + await tester.ensureVisible(find.text('Save server')); + await tester.tap(find.text('Save server')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('server-profile-name')), findsNothing); + expect(connections.catalog.active?.name, 'My home'); + expect(store.catalog?.active?.endpoints, hasLength(2)); + expect(store.writes, hasLength(2)); + expect(activations.single?.id, original.id); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets( + 'activation failure retry does not duplicate new profile ($cupertino)', + (tester) async { + final store = _ControlledStore(); + var attempts = 0; + final connections = ServerConnections( + store: store, + onSelected: (_) async { + if (++attempts == 1) throw StateError('Connection unavailable'); + }, + ); + addTearDown(connections.dispose); + await connections.load(); + await _openEditor(tester, connections, cupertino); + await tester.tap(find.text('Save server')); + await tester.pumpAndSettle(); + expect(find.textContaining('Connection unavailable'), findsOneWidget); + expect(find.byKey(const Key('server-profile-name')), findsOneWidget); + expect(store.catalog?.servers, hasLength(1)); + final savedId = store.catalog!.servers.single.id; + + await tester.ensureVisible(find.text('Save server')); + await tester.tap(find.text('Save server')); + await tester.pumpAndSettle(); + expect(attempts, 2); + expect(store.catalog?.servers, hasLength(1)); + expect(store.catalog?.servers.single.id, savedId); + expect(find.byKey(const Key('server-profile-name')), findsNothing); + expect(tester.takeException(), isNull); + }, + ); + } +} diff --git a/app/tool/server_editor_save_probe.dart b/app/tool/server_editor_save_probe.dart new file mode 100644 index 00000000..ec53934c --- /dev/null +++ b/app/tool/server_editor_save_probe.dart @@ -0,0 +1,44 @@ +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/servers/server_catalog.dart'; +import 'package:pipelines_app/core/servers/server_catalog_store.dart'; +import 'package:pipelines_app/features/settings/saved_servers_section.dart'; +import 'package:pipelines_app/features/settings/server_connections.dart'; + +// Isolated, in-memory browser fixture: first write fails, retry succeeds. +// No sockets, real storage, or production requests. +void main() { + final cupertino = Uri.base.queryParameters['host'] == 'cupertino'; + final connections = ServerConnections( + store: _Store(), + onSelected: (_) async {}, + ); + final body = SafeArea( + child: SingleChildScrollView( + child: SavedServersSection(connections: connections), + ), + ); + runApp( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: body)) + : MaterialApp(home: Scaffold(body: body)), + ); +} + +class _Store extends MemoryServerCatalogStore { + var _attempts = 0; + + @override + Future save(ServerCatalog catalog) async { + globalContext.setProperty( + 'serverEditorSaveAttempts'.toJS, + (++_attempts).toJS, + ); + await Future.delayed(const Duration(seconds: 3)); + if (_attempts == 1) return false; + return super.save(catalog); + } +} diff --git a/app/tool/server_editor_save_probe.mjs b/app/tool/server_editor_save_probe.mjs new file mode 100644 index 00000000..6c85b7b9 --- /dev/null +++ b/app/tool/server_editor_save_probe.mjs @@ -0,0 +1,68 @@ +// Build: flutter build web -t tool/server_editor_save_probe.dart -o build/server_editor_save_probe_web +// Run: node tool/server_editor_save_probe.mjs [evidence directory] +import assert from 'node:assert/strict'; +import { once } from 'node:events'; +import { mkdir, mkdtemp, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { startServer, launchChrome, waitForPort, waitForPage, connect, sleep } from './pipelines_probe_cdp_lib.mjs'; +import { axNodes, enableSemantics, waitFor, capture, assertName, click, clickAt } from './pipelines_probe_cdp_input.mjs'; + +const output = resolve(process.argv[2] ?? 'build/server-editor-save-evidence'); +await mkdir(output, { recursive: true }); +const fixture = await startServer(resolve('build/server_editor_save_probe_web')); +const profile = await mkdtemp(join(tmpdir(), 'server-editor-save-')); +const chrome = launchChrome('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', profile, 'about:blank'); +const log = { checks: [], captures: [] }; +let c; +try { + c = await connect((await waitForPage(await waitForPort(join(profile, 'DevToolsActivePort')))).webSocketDebuggerUrl); + await c.send('Page.enable'); + await c.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true }); + for (const host of ['material', 'cupertino']) { + await c.send('Page.navigate', { url: `${fixture.url}?host=${host}` }); + assert.ok(await waitFor(() => c.evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), 12000)); + await enableSemantics(c); + await click(c, 'Add server'); + const type = async (index, text) => { + const field = (await axNodes(c)).filter(node => node.role?.value === 'textbox')[index]; + assert.ok(field, `field ${index}`); + const { model } = await c.send('DOM.getBoxModel', { backendNodeId: field.backendDOMNodeId }); + const [x1, y1, , , x3, y3] = model.content; + await clickAt(c, (x1 + x3) / 2, (y1 + y3) / 2); + await c.send('Input.insertText', { text }); + await sleep(200); + }; + await type(0, 'Home draft'); + await type(1, 'wss://home.test/connect'); + await click(c, 'Save server'); + await assertName(c, 'Saving server…', `${host}: pending state visible`, log); + await click(c, 'Saving server…'); + assert.equal(await c.evaluate('globalThis.serverEditorSaveAttempts'), 1); + log.checks.push(`${host}: repeat click does not submit again`); + await capture(c, output, log, `${host}-saving`); + await assertName(c, 'could not be saved', `${host}: save refusal shown in editor`, log); + await assertName(c, 'Home draft', `${host}: name draft retained`, log); + await assertName(c, 'wss://home.test/connect', `${host}: address draft retained`, log); + await capture(c, output, log, `${host}-failure-draft`); + await click(c, 'Save server'); + await assertName(c, 'Selected server', `${host}: retry succeeds`, log); + assert.equal(await c.evaluate('globalThis.serverEditorSaveAttempts'), 2); + assert.ok(!(await axNodes(c)).some(node => node.role?.value === 'textbox')); + await capture(c, output, log, `${host}-retry-saved`); + } + console.log(JSON.stringify(log, null, 2)); +} catch (error) { + if (c) { + await capture(c, output, log, 'failure'); + await writeFile(join(output, 'failure-ax.json'), JSON.stringify(await axNodes(c), null, 2)); + } + throw error; +} finally { + await writeFile(join(output, 'result.json'), JSON.stringify(log, null, 2)); + c?.close(); + const exited = once(chrome, 'exit'); + chrome.kill(); + await exited; + await new Promise(done => fixture.server.close(done)); +}