fix(settings): preserve server editor drafts until save succeeds

This commit is contained in:
2026-10-24 10:52:01 +01:00
parent 6609b52b1c
commit 25437b3181
6 changed files with 414 additions and 27 deletions
@@ -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<SavedServer?> editSavedServer(
BuildContext context, {
SavedServer? server,
Future<void> Function(SavedServer)? onSave,
}) {
final page = _ServerEditor(server: server);
final page = _ServerEditor(server: server, onSave: onSave);
return Navigator.of(context).push<SavedServer>(
usesCupertinoHost(context)
? CupertinoPageRoute(builder: (_) => page)
@@ -17,35 +20,51 @@ Future<SavedServer?> editSavedServer(
}
class _ServerEditor extends StatefulWidget {
const _ServerEditor({this.server});
const _ServerEditor({this.server, this.onSave});
final SavedServer? server;
final Future<void> 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<void> _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,
),
);
}
}
@@ -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<void> _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<void> _remove(BuildContext context, SavedServer server) async {
@@ -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.
@@ -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 = <ServerCatalog>[];
Completer<bool>? pending;
@override
Future<bool> save(ServerCatalog catalog) async {
writes.add(catalog);
if (pending != null && !await pending!.future) return false;
return super.save(catalog);
}
}
Future<void> _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<bool>();
final activations = <SavedServer?>[];
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<CupertinoButton>(button).onPressed
: tester.widget<FilledButton>(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<EditableText>(
find.descendant(
of: find.byKey(const Key('server-profile-name')),
matching: find.byType(EditableText),
),
);
final addresses = tester.widget<EditableText>(
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);
},
);
}
}
+44
View File
@@ -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<bool> save(ServerCatalog catalog) async {
globalContext.setProperty(
'serverEditorSaveAttempts'.toJS,
(++_attempts).toJS,
);
await Future<void>.delayed(const Duration(seconds: 3));
if (_attempts == 1) return false;
return super.save(catalog);
}
}
+68
View File
@@ -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));
}