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;
}
}
}