Persist exact tab locations including Settings under Pipelines

This commit is contained in:
2026-11-08 01:04:00 +00:00
parent d6006bb1f8
commit 151d99fbb6
10 changed files with 778 additions and 25 deletions
+10
View File
@@ -200,12 +200,14 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
@override
Future<void> setInitialRoutePath(AppRoute configuration) async {
_rememberParent(configuration);
_route = configuration;
}
@override
Future<void> setNewRoutePath(AppRoute configuration) async {
if (configuration == _route) return;
_rememberParent(configuration);
_route = configuration;
notifyListeners();
}
@@ -217,10 +219,18 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
Future<bool> popRoute() async =>
await _navigatorKey.currentState?.maybePop() ?? false;
void _rememberParent(AppRoute route) {
if (route.kind == AppRouteKind.templates ||
route.kind == AppRouteKind.schedules) {
_templatesReturn = AppRoute.settings;
}
}
/// Records a user move; the Router turns the new configuration into a
/// history entry (or a replacement when it already matches the location).
void goTo(AppRoute route) {
if (route == _route) return;
_rememberParent(route);
_route = route;
notifyListeners();
}
+74 -24
View File
@@ -40,6 +40,8 @@ import 'schedules_destination.dart';
import 'search_destination.dart';
import 'server_endpoint.dart';
import 'templates_destination.dart';
import 'tab_locations.dart';
import 'tab_locations_store.dart';
/// The application's return-to-foreground policy for the shared socket.
///
@@ -76,8 +78,10 @@ class PipelinesApp extends StatefulWidget {
this.androidFeedReader = fetchLatestUpdate,
this.androidInstaller = downloadAndInstall,
this.webRefresher = refreshWebPage,
this.tabLocationsStore,
});
final TabLocationsStore? tabLocationsStore;
final ServerEndpoint server;
final PipelinesClient? client;
final bool? cupertino;
@@ -219,6 +223,19 @@ class _PipelinesAppState extends State<PipelinesApp>
// a dropped or unknown query is canonicalised away.
final location = routeLocation(_provider.value.uri);
final initial = AppRoute.parse(location);
final nativeDefault =
widget.routeInformationProvider == null &&
!kIsWeb &&
const [
'',
'/',
].contains(WidgetsBinding.instance.platformDispatcher.defaultRouteName);
final restoreTab = !widget.resetRoute && (location == '/' || nativeDefault);
_tabLocations = TabLocations(
widget.tabLocationsStore ??
SharedPreferencesTabLocationsStore(scope: _navigationScope),
);
_tabLocations.record(initial, visited: !restoreTab);
if (location != initial.path) {
_provider.routerReportsNewRouteInformation(
RouteInformation(uri: Uri.parse(initial.path)),
@@ -248,7 +265,9 @@ class _PipelinesAppState extends State<PipelinesApp>
);
_delegate.addListener(_routeChanged);
// Seed retained destinations for deep links as well as later navigation.
_routeChanged();
_rememberChatRoute(initial);
_rememberBodyRoute(_delegate.shellRoute);
unawaited(_restoreTabLocations(restoreTab));
_chatQuestionNotices = ChatQuestionNotices(
gateway: _session.gateway,
canNotify: () => _notifications.canNotify,
@@ -344,6 +363,7 @@ class _PipelinesAppState extends State<PipelinesApp>
@override
void dispose() {
_tabLocations.dispose();
WidgetsBinding.instance.removeObserver(this);
_deliveryHandoff?.dispose();
_session.removeListener(_attentionSessionChanged);
@@ -502,21 +522,49 @@ class _PipelinesAppState extends State<PipelinesApp>
setState(() => _pendingRunSearch = null);
}
/// Drops a pending request once the shell leaves the run it names.
///
/// The mounted detail is the only consumer, and it exists only after the run's
/// detail has loaded. Backing out while that read is still pending, or leaving
/// a failed detail, would otherwise keep the request for the next unrelated
/// visit to the same run. Search/Templates/Schedules pages above the run keep
/// it, because the shell route underneath them still names that run.
/// The last route each tab showed, so switching tabs returns to where the
/// operator left it; tapping the open tab again goes to its root.
final Map<AppDestination, AppRoute> _tabRoutes = {};
/// The last location within each tab, including Settings under Pipelines.
/// Explicit Back is separate from tab selection and same-tab retaps.
String get _navigationScope =>
widget.serverId ?? widget.server.uri?.toString() ?? '';
late final TabLocations _tabLocations;
Map<AppDestination, AppRoute> get _tabRoutes => _tabLocations.routes;
// A Settings visit owns the Pipelines tab's return location, but must not
// clear the still-mounted Pipelines body's selection or editor underneath.
final _bodyRoutes = <AppDestination, AppRoute>{};
void _rememberBodyRoute(AppRoute route) {
_bodyRoutes[_destinationOf(route.kind)] = route;
}
Future<void> _restoreTabLocations(bool restoreActive) async {
final revision = _tabLocations.revision;
final restored = await _tabLocations.restore(restoreActive: restoreActive);
if (!mounted) return;
// The Router first consumes its boot URL. Apply saved navigation afterward,
// and never jump over a user move that happened while preferences loaded.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
if (restored != null && revision == _tabLocations.revision) {
_delegate.goTo(restored);
} else {
setState(() {});
}
});
WidgetsBinding.instance.ensureVisualUpdate();
}
void _rememberChatRoute(AppRoute route) {
if (route.kind == AppRouteKind.chat && route.chatSessionId != null) {
_chatWorkspaceRoute = route;
}
}
AppRoute? _chatWorkspaceRoute;
Set<String>? _availableChatSessionIds;
void _selectDestination(AppDestination destination) {
final current = _destinationOf(_delegate.shellRoute.kind);
final current = tabForRoute(_delegate.route);
final last = _tabRoutes[destination];
if (destination == AppDestination.chat && current == destination) {
final reopened = chatRouteForRetap(
@@ -529,17 +577,14 @@ class _PipelinesAppState extends State<PipelinesApp>
_delegate.goTo(reopened ?? _routeOf(destination));
return;
}
_delegate.goTo(
destination == current || last == null ? _routeOf(destination) : last,
);
_delegate.goTo(last ?? _routeOf(destination));
}
void _routeChanged() {
final shown = _delegate.shellRoute;
_tabRoutes[_destinationOf(shown.kind)] = shown;
if (shown.kind == AppRouteKind.chat && shown.chatSessionId != null) {
_chatWorkspaceRoute = shown;
}
final shown = _delegate.route;
_tabLocations.record(shown);
_rememberBodyRoute(_delegate.shellRoute);
_rememberChatRoute(shown);
final pending = _pendingRunSearch;
if (!mounted || pending == null) return;
final route = _delegate.shellRoute;
@@ -603,10 +648,14 @@ class _PipelinesAppState extends State<PipelinesApp>
Widget _shellFor(AppRoute route, int attentionCount) {
// Each tab is built from the route it last showed, so switching tabs keeps
// an open run, pipeline or chat instead of resetting it.
AppRoute tab(AppDestination destination) =>
_destinationOf(route.kind) == destination
? route
: _tabRoutes[destination] ?? _routeOf(destination);
AppRoute tab(AppDestination destination) {
if (_destinationOf(route.kind) == destination) return route;
final saved = _tabRoutes[destination];
return saved != null && _destinationOf(saved.kind) == destination
? saved
: _bodyRoutes[destination] ?? _routeOf(destination);
}
final pipelinesRoute = tab(AppDestination.pipelines);
final runsRoute = tab(AppDestination.runs);
final chatRoute = tab(AppDestination.chat);
@@ -615,6 +664,7 @@ class _PipelinesAppState extends State<PipelinesApp>
cupertino: _cupertino,
destination: _destinationOf(route.kind),
onDestinationSelected: _selectDestination,
onClosePage: () => _delegate.goTo(AppRoute.pipelines),
destinationBodies: {
AppDestination.pipelines: (_) => PipelinesDestination(
session: _session,
@@ -0,0 +1,17 @@
import '../shell/destination.dart';
import 'app_route.dart';
/// Settings and its pages occupy the Pipelines tab, not an independent tab.
AppDestination tabForRoute(AppRoute route) => switch (route.kind) {
AppRouteKind.pipelines ||
AppRouteKind.settings ||
AppRouteKind.templates ||
AppRouteKind.schedules => AppDestination.pipelines,
AppRouteKind.runs => AppDestination.runs,
AppRouteKind.chat => AppDestination.chat,
AppRouteKind.search => AppDestination.search,
};
/// Remembers navigation without retaining modal actions such as run decisions.
AppRoute durableTabRoute(AppRoute route) =>
route.decide ? AppRoute.run(route.runId!) : route;
+77
View File
@@ -0,0 +1,77 @@
import 'dart:async';
import '../shell/destination.dart';
import 'app_route.dart';
import 'tab_locations_store.dart';
import 'tab_location_routes.dart';
export 'tab_location_routes.dart';
class TabLocations {
TabLocations(this.store);
final TabLocationsStore store;
final routes = <AppDestination, AppRoute>{};
final _touched = <AppDestination>{};
AppDestination active = AppDestination.pipelines;
int revision = 0;
bool _loaded = false;
bool _disposed = false;
bool persistenceFailed = false;
Future<void> _writes = Future<void>.value();
void record(AppRoute route, {bool visited = true}) {
if (_disposed) return;
active = tabForRoute(route);
routes[active] = route;
if (visited) {
_touched.add(active);
revision++;
}
if (_loaded) _save();
}
/// Slow storage never overwrites navigation made while it was loading.
Future<AppRoute?> restore({required bool restoreActive}) async {
TabLocationsSnapshot saved;
try {
saved = await store.load();
} catch (_) {
// Keep in-memory navigation, but never overwrite unread stored history.
persistenceFailed = true;
return null;
}
if (_disposed) return null;
for (final entry in saved.routes.entries) {
if (!_touched.contains(entry.key)) routes[entry.key] = entry.value;
}
AppRoute? restored;
if (restoreActive && _touched.isEmpty) {
active = saved.active;
restored = routes[active];
}
_loaded = true;
_save();
return restored;
}
void _save() {
final snapshot = TabLocationsSnapshot(
active: active,
routes: {
for (final entry in routes.entries)
entry.key: durableTabRoute(entry.value),
},
);
_writes = _writes.then((_) async {
try {
persistenceFailed = !await store.save(snapshot);
} catch (_) {
persistenceFailed = true;
}
});
}
void dispose() => _disposed = true;
Future<void> get settled => _writes;
}
@@ -0,0 +1,83 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../core/servers/server_scope.dart';
import '../shell/destination.dart';
import 'app_route.dart';
import 'tab_location_routes.dart';
class TabLocationsSnapshot {
const TabLocationsSnapshot({
this.active = AppDestination.pipelines,
this.routes = const {},
});
final AppDestination active;
final Map<AppDestination, AppRoute> routes;
Map<String, Object> toJson() => {
'version': 1,
'active': active.name,
'routes': {
for (final entry in routes.entries) entry.key.name: entry.value.path,
},
};
static TabLocationsSnapshot decode(String? encoded) {
if (encoded == null) return const TabLocationsSnapshot();
try {
final data = jsonDecode(encoded);
if (data is! Map || data['version'] != 1 || data['routes'] is! Map) {
return const TabLocationsSnapshot();
}
final routes = <AppDestination, AppRoute>{};
for (final entry in (data['routes'] as Map).entries) {
final tab = shellTabDestinations
.where((tab) => tab.name == entry.key)
.firstOrNull;
final path = entry.value;
if (tab == null || path is! String || !path.startsWith('/')) continue;
final route = AppRoute.parse(path);
if (route.path != path || tabForRoute(route) != tab) continue;
routes[tab] = durableTabRoute(route);
}
final active =
shellTabDestinations
.where((tab) => tab.name == data['active'])
.firstOrNull ??
AppDestination.pipelines;
return TabLocationsSnapshot(active: active, routes: routes);
} on FormatException {
return const TabLocationsSnapshot();
}
}
}
abstract interface class TabLocationsStore {
Future<TabLocationsSnapshot> load();
Future<bool> save(TabLocationsSnapshot value);
}
class SharedPreferencesTabLocationsStore implements TabLocationsStore {
const SharedPreferencesTabLocationsStore({required this.scope});
final String scope;
String get key => scopedServerKey('pipelines.next.tabLocations.v1', scope);
@override
Future<TabLocationsSnapshot> load() async {
// Throw on an unreadable store: the controller then preserves stored data
// rather than mistaking it for absent history and writing a partial map.
final preferences = await SharedPreferences.getInstance();
return TabLocationsSnapshot.decode(preferences.getString(key));
}
@override
Future<bool> save(TabLocationsSnapshot value) async {
try {
final preferences = await SharedPreferences.getInstance();
return await preferences.setString(key, jsonEncode(value.toJson()));
} catch (_) {
return false;
}
}
}
+10 -1
View File
@@ -21,6 +21,7 @@ class AdaptiveShell extends StatefulWidget {
this.cupertino = false,
this.destination,
this.onDestinationSelected,
this.onClosePage,
this.onSearch,
this.attentionCount = 0,
this.listPaneWidthStore = const SharedPreferencesListPaneWidthStore(),
@@ -36,6 +37,7 @@ class AdaptiveShell extends StatefulWidget {
/// selection, which preserves the plain-shell tests and native composition.
final AppDestination? destination;
final ValueChanged<AppDestination>? onDestinationSelected;
final VoidCallback? onClosePage;
/// Opens the transient Search page. Null hides the action, so the plain
/// shell tests and compositions without routing keep their tab set only.
@@ -265,7 +267,14 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
}
/// Leaves a page destination (Settings) for the tab it belongs to.
void _closePage() => _select(shellTabFor(_selected));
void _closePage() {
final close = widget.onClosePage;
if (close != null) {
close();
} else {
_select(shellTabFor(_selected));
}
}
/// The system Back the shell handles: it closes a page, or else returns to
/// the previous tab unless the open item's own pane closes a page first.
+39
View File
@@ -0,0 +1,39 @@
# Persistent tab locations
Settings, Templates and Schedules belong to the Pipelines tab. Selecting another
main tab and returning restores that tab's last canonical route, including
Settings. Same-tab selection preserves the current location; explicit Back
still exits Settings. The existing Chats retap-to-workspace behavior remains.
The owning tab's return route is separate from each mounted body's runtime
route, so visiting Settings does not clear a hidden Pipelines detail/editor.
Settings State stays mounted when switching tabs. Restored Templates/Schedules
always retain Settings as their parent.
A scoped SharedPreferences snapshot records per-tab routes and the last active
tab. Logical server identity is the scope; an endpoint is used only when there
is no identity. Ordinary `/` / native-default launches can restore the active
location; explicit launch URLs, including `/pipelines`, take priority. Pipeline
versions/stages, run visits/filters and chat IDs survive canonical serialization;
run decision actions are omitted from durable storage.
Storage loading never saves a partial default map. User-touched slots win over
a slow load, untouched slots merge, and writes serialize so the final move wins.
Unreadable history remains untouched, write failures do not poison subsequent
saves, and disposing the app cancels late read-back persistence. Navigation
stays responsive throughout.
Focused acceptance: 40 tests passed across tab locations, full-app navigation,
router, Settings Back and existing Chats retap (`/tmp/memwatch/out.A1UrLy`).
The subsequent disposal regression and navigation cases passed (16 cases,
`/tmp/memwatch/out.eUiZcl`), bringing distinct covered cases to 41.
Analyzer clean (`flutter-analyze.Klkp0D`). Full-app tests cover both native hosts,
exact Pipelines → Settings → Chat → Pipelines restoration with identical
Settings State, explicit Back, preserved hidden Pipelines selection, actual app
recreation via SharedPreferences, explicit URL priority and delayed load races.
This change persists route locations; arbitrary dialogs, unsaved editor content
and scroll offsets are not serialized by this store. Their existing mounted
state remains intact within a session. Settings inner-topic persistence is a
separate companion change. Manager-owned integrated browser capture/build and
publication are still required; this lane did not deploy or restart anything.
+16
View File
@@ -36,6 +36,22 @@ Future<AppRouterDelegate> pumpRouter(
}
void main() {
test(
'restoring Settings subpages from another tab preserves their parent',
() async {
final router = delegate(AppRoute.chat);
addTearDown(router.dispose);
router.goTo(AppRoute.template('release'));
expect(router.shellRoute, AppRoute.settings);
router.closeTemplates();
expect(router.route, AppRoute.settings);
router.goTo(AppRoute.chat);
await router.setNewRoutePath(AppRoute.schedules);
expect(router.shellRoute, AppRoute.settings);
router.closeSchedules();
expect(router.route, AppRoute.settings);
},
);
TestWidgetsFlutterBinding.ensureInitialized();
test('with nothing pushed the router leaves Back to the platform', () async {
for (final route in [
@@ -0,0 +1,202 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pipelines_app/application/app_route.dart';
import 'package:pipelines_app/application/pipelines_app.dart';
import 'package:pipelines_app/application/tab_locations_store.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:pipelines_app/features/settings/settings_screen.dart';
import 'package:pipelines_app/features/pipelines/screen.dart';
import 'package:pipelines_app/shell/destination.dart';
import '../bar_action.dart';
import '../core/transport/pipelines_client_test.dart' show FakeChannel;
import '../features/pipelines/fixtures.dart';
import 'pipelines_app_test.dart' show webServer;
import 'pipelines_replies.dart';
import 'tab_locations_test.dart' show MemoryTabLocationsStore;
Future<({PlatformRouteInformationProvider provider, FakeChannel channel})>
mount(
WidgetTester tester, {
String route = '/pipelines',
bool cupertino = false,
TabLocationsStore? store,
}) async {
tester.view.physicalSize = const Size(560, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse(route)),
);
addTearDown(provider.dispose);
addTearDown(client.dispose);
await tester.pumpWidget(
PipelinesApp(
server: webServer(),
client: client,
cupertino: cupertino,
serverId: 'navigation-test',
routeInformationProvider: provider,
tabLocationsStore: store,
),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
return (provider: provider, channel: channel);
}
Future<void> tab(WidgetTester tester, String name) async {
await tester.tap(find.byKey(ValueKey('shell.destination.$name')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
}
void main() {
setUp(() => SharedPreferences.setMockInitialValues({}));
for (final cupertino in [false, true]) {
testWidgets(
'Settings is retained inside Pipelines across tab switches ($cupertino)',
(tester) async {
final app = await mount(tester, cupertino: cupertino);
await replyPipelines(tester, app.channel, PipelineFixture());
await tester.pumpAndSettle();
await tapBarAction(
tester,
find.byKey(const Key('pipelines-open-settings')),
'Settings',
);
await tester.pumpAndSettle();
expect(app.provider.value.uri.path, '/settings');
final settingsState = tester.state(find.byType(SettingsScreen));
await tab(tester, 'chat');
expect(app.provider.value.uri.path, '/chat');
await tab(tester, 'pipelines');
expect(app.provider.value.uri.path, '/settings');
expect(tester.state(find.byType(SettingsScreen)), same(settingsState));
await tab(tester, 'pipelines');
expect(
app.provider.value.uri.path,
'/settings',
reason: 'tab retap is not Back',
);
await tester.tap(find.byKey(const ValueKey('shell.back')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
expect(
app.provider.value.uri.path,
'/pipelines',
reason: 'explicit Back still exits Settings',
);
expect(tester.takeException(), isNull);
},
);
}
testWidgets(
'per-tab locations survive app recreation; an explicit deep link wins',
(tester) async {
final first = await mount(tester, route: '/settings');
await tester.pumpAndSettle();
expect(first.provider.value.uri.path, '/settings');
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
final restored = await mount(tester, route: '/');
await tester.pumpAndSettle();
expect(restored.provider.value.uri.path, '/settings');
expect(find.byType(SettingsScreen), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
final linked = await mount(tester, route: '/runs/8/stage/plan?visit=2');
expect(
linked.provider.value.uri.toString(),
'/runs/8/stage/plan?visit=2',
);
await tab(tester, 'chat');
await tab(tester, 'runs');
expect(
linked.provider.value.uri.toString(),
'/runs/8/stage/plan?visit=2',
);
await tab(tester, 'pipelines');
expect(linked.provider.value.uri.path, '/settings');
expect(tester.takeException(), isNull);
},
);
testWidgets(
'a delayed read merges locations without redirecting a user move',
(tester) async {
final store = MemoryTabLocationsStore()..read = Completer();
final app = await mount(tester, route: '/', store: store);
await tab(tester, 'chat');
expect(store.writes, isEmpty);
store.read!.complete(
const TabLocationsSnapshot(
active: AppDestination.pipelines,
routes: {AppDestination.pipelines: AppRoute.settings},
),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
expect(app.provider.value.uri.path, '/chat');
await tab(tester, 'pipelines');
expect(app.provider.value.uri.path, '/settings');
expect(tester.takeException(), isNull);
},
);
testWidgets('an explicit root URL does not restore a different active tab', (
tester,
) async {
final store = MemoryTabLocationsStore()
..value = TabLocationsSnapshot(
active: AppDestination.runs,
routes: {
AppDestination.runs: AppRoute.run(9),
AppDestination.pipelines: AppRoute.settings,
},
);
final app = await mount(tester, route: '/pipelines', store: store);
expect(app.provider.value.uri.path, '/pipelines');
await tab(tester, 'runs');
expect(app.provider.value.uri.path, '/runs/9');
await tab(tester, 'pipelines');
expect(app.provider.value.uri.path, '/pipelines');
expect(tester.takeException(), isNull);
});
testWidgets('Settings does not clear the mounted Pipelines detail', (
tester,
) async {
final app = await mount(tester);
tester.view.physicalSize = const Size(1100, 1000);
await tester.pump();
final fixture = PipelineFixture();
await replyPipelines(tester, app.channel, fixture);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('pipeline-row-1')));
await tester.pump();
await replyPipelineDetail(tester, app.channel, fixture);
await tester.pumpAndSettle();
expect(app.provider.value.uri.path, '/pipelines/1');
final before = tester.widget<PipelinesScreen>(find.byType(PipelinesScreen));
expect(before.initialPipelineId, 1);
final pipelineState = tester.state(find.byType(PipelinesScreen));
await tapBarAction(
tester,
find.byKey(const Key('pipelines-open-settings')),
'Settings',
);
await tester.pumpAndSettle();
expect(app.provider.value.uri.path, '/settings');
final hidden = find.byType(PipelinesScreen, skipOffstage: false);
expect(tester.widget<PipelinesScreen>(hidden).initialPipelineId, 1);
expect(tester.state(hidden), same(pipelineState));
await tab(tester, 'chat');
await tab(tester, 'pipelines');
expect(app.provider.value.uri.path, '/settings');
expect(tester.widget<PipelinesScreen>(hidden).initialPipelineId, 1);
expect(tester.takeException(), isNull);
});
}
@@ -0,0 +1,250 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pipelines_app/application/app_route.dart';
import 'package:pipelines_app/application/tab_locations.dart';
import 'package:pipelines_app/application/tab_locations_store.dart';
import 'package:pipelines_app/shell/destination.dart';
class MemoryTabLocationsStore implements TabLocationsStore {
TabLocationsSnapshot value = const TabLocationsSnapshot();
Completer<TabLocationsSnapshot>? read;
final writes = <TabLocationsSnapshot>[];
Completer<bool>? write;
@override
Future<TabLocationsSnapshot> load() async =>
read == null ? value : read!.future;
@override
Future<bool> save(TabLocationsSnapshot snapshot) async {
writes.add(snapshot);
if (write case final pending?) {
write = null;
await pending.future;
}
value = snapshot;
return true;
}
}
class UnreadableTabLocationsStore extends MemoryTabLocationsStore {
@override
Future<TabLocationsSnapshot> load() async => throw StateError('unavailable');
}
class FailingTabLocationsStore extends MemoryTabLocationsStore {
bool fails = true;
@override
Future<bool> save(TabLocationsSnapshot snapshot) async {
if (fails) {
fails = false;
throw StateError('temporary write failure');
}
return super.save(snapshot);
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('Settings and nested pages retain Pipelines ownership', () async {
final store = MemoryTabLocationsStore();
final tabs = TabLocations(store);
tabs.record(AppRoute.settings);
tabs.record(AppRoute.chat);
await tabs.restore(restoreActive: false);
await tabs.settled;
expect(tabs.routes[AppDestination.pipelines], AppRoute.settings);
expect(tabs.routes[AppDestination.chat], AppRoute.chat);
expect(store.value.routes[AppDestination.pipelines], AppRoute.settings);
tabs.record(AppRoute.template('release'));
await tabs.settled;
expect(
store.value.routes[AppDestination.pipelines],
AppRoute.template('release'),
);
});
test('canonical details survive serialization, decisions do not replay', () {
final snapshot = TabLocationsSnapshot.decode(
jsonEncode({
'version': 1,
'active': 'runs',
'routes': {
'pipelines': '/pipelines/7/3/stage/build',
'runs': '/runs/8/stage/review?visit=2',
'chat': '/chat/session-2',
'search': '/search',
},
}),
);
expect(
snapshot.routes[AppDestination.runs],
AppRoute.run.stage(8, 'review', visit: 2),
);
expect(
snapshot.routes[AppDestination.pipelines],
AppRoute.pipelineStage(7, 'build', version: 3),
);
expect(
TabLocationsSnapshot.decode(
jsonEncode({
'version': 1,
'routes': {'runs': '/runs/8?action=decide'},
}),
).routes[AppDestination.runs],
AppRoute.run(8),
);
});
test('malformed, cross-owner and external stored routes are ignored', () {
for (final value in ['no json', '[]', '{"version":2,"routes":{}}']) {
expect(TabLocationsSnapshot.decode(value).routes, isEmpty);
}
final saved = TabLocationsSnapshot.decode(
jsonEncode({
'version': 1,
'routes': {
'runs': '/settings',
'pipelines': 'https://example.com/settings',
'chat': '/chat/invalid/id',
'settings': '/settings',
'search': '/unknown',
},
}),
);
expect(saved.routes, isEmpty);
});
test(
'delayed restore merges untouched tabs but never overwrites user navigation',
() async {
final store = MemoryTabLocationsStore()..read = Completer();
final tabs = TabLocations(store)
..record(AppRoute.pipelines, visited: false);
final restoring = tabs.restore(restoreActive: true);
tabs.record(AppRoute.run(12));
expect(
store.writes,
isEmpty,
reason: 'never erase storage before reading it',
);
store.read!.complete(
TabLocationsSnapshot(
active: AppDestination.pipelines,
routes: {
AppDestination.pipelines: AppRoute.settings,
AppDestination.runs: AppRoute.run(5),
},
),
);
expect(await restoring, isNull);
await tabs.settled;
expect(tabs.routes[AppDestination.runs], AppRoute.run(12));
expect(tabs.routes[AppDestination.pipelines], AppRoute.settings);
expect(store.value.active, AppDestination.runs);
},
);
test(
'ordinary boot restores active location; explicit boot wins its slot',
() async {
final store = MemoryTabLocationsStore()
..value = const TabLocationsSnapshot(
active: AppDestination.pipelines,
routes: {AppDestination.pipelines: AppRoute.settings},
);
final ordinary = TabLocations(store)
..record(AppRoute.pipelines, visited: false);
expect(await ordinary.restore(restoreActive: true), AppRoute.settings);
await ordinary.settled;
final explicit = TabLocations(store)
..record(AppRoute.pipeline(3, version: 2));
expect(await explicit.restore(restoreActive: false), isNull);
expect(
explicit.routes[AppDestination.pipelines],
AppRoute.pipeline(3, version: 2),
);
await explicit.settled;
},
);
test(
'writes serialize and last move wins even with a slow first write',
() async {
final first = Completer<bool>();
final store = MemoryTabLocationsStore()..write = first;
final tabs = TabLocations(store)..record(AppRoute.settings);
await tabs.restore(restoreActive: false);
await Future<void>.delayed(Duration.zero);
tabs.record(AppRoute.chat);
tabs.record(AppRoute.run(9));
expect(store.writes, hasLength(1));
first.complete(true);
await tabs.settled;
expect(store.value.active, AppDestination.runs);
expect(store.value.routes[AppDestination.pipelines], AppRoute.settings);
expect(store.value.routes[AppDestination.runs], AppRoute.run(9));
},
);
test(
'SharedPreferences survives recreation and isolates logical servers',
() async {
SharedPreferences.setMockInitialValues({});
const a = SharedPreferencesTabLocationsStore(scope: 'server-a');
const b = SharedPreferencesTabLocationsStore(scope: 'server-b');
expect(
await a.save(
const TabLocationsSnapshot(
routes: {AppDestination.pipelines: AppRoute.settings},
),
),
isTrue,
);
expect(
(await const SharedPreferencesTabLocationsStore(
scope: 'server-a',
).load()).routes[AppDestination.pipelines],
AppRoute.settings,
);
expect((await b.load()).routes, isEmpty);
},
);
test(
'unreadable history is never replaced by a partial new snapshot',
() async {
final store = UnreadableTabLocationsStore();
final tabs = TabLocations(store)..record(AppRoute.settings);
expect(await tabs.restore(restoreActive: false), isNull);
tabs.record(AppRoute.chat);
await tabs.settled;
expect(tabs.persistenceFailed, isTrue);
expect(store.writes, isEmpty);
expect(tabs.routes[AppDestination.pipelines], AppRoute.settings);
},
);
test('a failed write does not prevent a later navigation save', () async {
final store = FailingTabLocationsStore();
final tabs = TabLocations(store)..record(AppRoute.settings);
await tabs.restore(restoreActive: false);
await tabs.settled;
expect(tabs.persistenceFailed, isTrue);
tabs.record(AppRoute.chat);
await tabs.settled;
expect(tabs.persistenceFailed, isFalse);
expect(store.value.active, AppDestination.chat);
});
test(
'a disposed app never writes a late storage read back over newer history',
() async {
final store = MemoryTabLocationsStore()..read = Completer();
final tabs = TabLocations(store)
..record(AppRoute.pipelines, visited: false);
final restoring = tabs.restore(restoreActive: true);
tabs.dispose();
store.read!.complete(
const TabLocationsSnapshot(
routes: {AppDestination.pipelines: AppRoute.settings},
),
);
expect(await restoring, isNull);
await tabs.settled;
expect(store.writes, isEmpty);
},
);
}