Files
pipelines/app/lib/application/pipelines_app.dart
T
alan 9e218f755a Consolidate startup and shell on Material
Remove alternate application hosts, page scaffolds, connection controls and icon metadata while preserving Material routing. Isolate navigation fixtures from native update plugins and retain separate startup-update regressions.
2026-11-11 20:11:17 +00:00

958 lines
37 KiB
Dart

import '../core/servers/chat/chat_server_pool.dart';
import '../core/servers/server_context.dart';
import '../core/servers/elevation/elevation_dialog.dart';
import '../core/servers/elevation/machine_elevation.dart';
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
import '../core/api_gateway.dart';
import '../core/servers/server_scope.dart';
import '../core/transport/pipelines_client.dart';
import '../shell/adaptive_shell.dart';
import '../shell/destination.dart';
import '../features/attention/notify/notification_controller.dart';
import '../features/attention/notify/chat_question_notices.dart';
import '../features/attention/notify/notification_store.dart';
import '../features/notification_service/notification_service_bridge.dart';
import '../features/notification_service/notification_service_controller.dart';
import '../features/notification_service/notification_service_handoff.dart';
import '../features/attention/runtime/attention_ack_queue.dart';
import '../features/attention/runtime/attention_ack_sync.dart';
import '../features/attention/runtime/attention_controller.dart';
import '../features/attention/runtime/attention_store.dart';
import '../features/runs/ui/run_search_selection.dart';
import '../features/search/domain/search_target.dart';
import '../features/settings/settings_screen.dart';
import '../features/settings/settings_store.dart';
import '../features/updates/app_updates.dart';
import '../features/updates/launch_update.dart';
import '../features/updates/launch_update_dialog.dart';
import '../features/updates/web_release.dart';
import '../features/settings/server_connections.dart';
import 'app.dart';
import '../shell/windows/window_host.dart';
import '../shell/windows/window_kind.dart';
import '../shell/windows/window_manager.dart';
import '../shell/windows/window_store.dart';
import '../shell/windows/windows_menu_button.dart';
import 'app_terminals.dart';
import '../features/chat/chat_runtime.dart';
import '../features/chat/windows/chat_windows.dart';
import '../features/chat/workspace/chat_float_store.dart';
import '../features/terminal/terminal_layout.dart';
import 'app_route.dart';
import 'app_router.dart';
import 'app_session.dart';
import 'chat_destination.dart';
import 'pipelines_destination.dart';
import 'runs_destination.dart';
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';
import '../ui/input/keyboard_owner.dart';
/// The application's return-to-foreground policy for the shared socket.
///
/// Only a socket the client dropped (disconnected) is reopened. Idle is a
/// deliberate Disconnect the operator made, so returning never undoes it, and
/// connected/connecting already have their own answer — foregrounding neither
/// churns a live socket nor restarts an attempt already in flight.
bool shouldReconnectOnForeground(ConnectionKind kind) =>
kind == ConnectionKind.disconnected;
/// Composes the live application around one [AppSession] and one [Router].
///
/// Tests may inject the client and route-information provider; the session
/// owns the socket either way, so there is never a second app-level connection.
class PipelinesApp extends StatefulWidget {
const PipelinesApp({
super.key,
required this.server,
this.client,
this.cupertino,
this.routeInformationProvider,
this.knownServer = false,
this.serverAddresses,
this.serverId,
this.servers,
this.chatPool,
this.resetRoute = false,
this.legacyPendingEndpoints = const [],
this.webPlatform = kIsWeb,
this.webBuildId = compiledWebBuildId,
this.webPageUri,
this.androidSupported,
this.webReleaseReader = fetchLatestWebBuild,
this.installedVersionReader = installedVersionCode,
this.androidFeedReader = fetchLatestUpdate,
this.androidInstaller = downloadAndInstall,
this.webRefresher = refreshWebPage,
this.tabLocationsStore,
this.terminalLayout,
this.windows,
});
final TabLocationsStore? tabLocationsStore;
/// The terminal surface's saved layout; null is the device's own.
final TerminalLayout? terminalLayout;
/// The floating windows; the app keeps its own (saved on this device)
/// when null.
final WindowManager? windows;
final ServerEndpoint server;
final PipelinesClient? client;
final bool? cupertino;
/// Test seam: the Router's initial and subsequent route information.
final RouteInformationProvider? routeInformationProvider;
/// The device has signed in to [server] before (see [AppSession]).
final bool knownServer;
final List<Uri>? serverAddresses;
final String? serverId;
final ServerConnections? servers;
final ChatServerPool? chatPool;
final bool resetRoute;
final List<String> legacyPendingEndpoints;
final bool webPlatform;
final String webBuildId;
final Uri? webPageUri;
final bool? androidSupported;
final Future<String?> Function(Uri) webReleaseReader;
final Future<int?> Function() installedVersionReader;
final Future<AppUpdate> Function(Uri) androidFeedReader;
final UpdateInstaller androidInstaller;
final Future<void> Function() webRefresher;
@override
State<PipelinesApp> createState() => _PipelinesAppState();
}
class _PipelinesAppState extends State<PipelinesApp>
with WidgetsBindingObserver {
late final AppSession _session;
late final AppRouterDelegate _delegate;
late final ElevationPrompt _elevationPrompt = elevationDialogPrompt(
() => _delegate.navigatorContext,
);
late final RouteInformationProvider _provider;
late final bool _ownsProvider;
late final RouterConfig<AppRoute> _config;
late final bool _cupertino;
/// Advances when a template create is accepted. The Pipelines destination
/// uses it to re-read through its mounted controller; no row is inserted
/// locally, so the next list reply is the only source of the new pipeline.
int _pipelinesRefresh = 0;
/// Advances when a launch was accepted. The Runs destination re-reads its
/// list once; the run itself is then opened from its route.
int _runsRefresh = 0;
/// Prevents duplicate resumed notifications from refreshing twice before
/// the next background transition starts another foreground visit.
bool _foregroundVisitHandled = false;
final _launchUpdates = LaunchUpdateChecker();
bool _launchUpdateBusy = false;
Uri? _launchUpdateEndpoint;
/// One run detail request from Search, delivered through the shell so the
/// mounted run detail can resolve it once the named run's steps have loaded.
/// A field or artifact hit names no addressable URL of its own, so the request
/// is not route state; it is cleared after the detail applies it or when the
/// shell leaves that run, so an abandoned hit never replays later.
RunSearchSelection? _pendingRunSearch;
/// One notification capability for the app: the Runs attention surface
/// publishes live transitions and Settings renders the same permission.
late final NotificationController _notifications = NotificationController(
store: SharedPreferencesNotificationStore(
serverId: serverStorageScope(widget.serverId),
),
serviceController: _deliveryController,
);
ChatQuestionNotices? _chatQuestionNotices;
/// One attention surface for the app: the Runs heading's bell draws from it
/// and the shell mirrors its count on the Runs tab, so the badge is visible
/// from every destination. The Runs list seeds the rows when it loads; pushed
/// `run_event` frames are folded here so the count moves while another
/// destination is shown, and a replaced socket drops the status baseline.
late final AttentionController _attention = AttentionController(
store: SharedPreferencesAttentionStore(
serverId: serverStorageScope(widget.serverId),
),
sync: _ackSync,
);
/// Shares Needs-you dismissals and chat read watermarks with every device
/// through the server. Bound to the gateway so the chat list (created by its
/// destination) uses the same channel; refreshed on every connection.
late final AttentionAckSync _ackSync = AttentionAckSync(
gateway: _session.gateway,
sendOnly: _session.client.sendOnly,
queue: SharedPreferencesAttentionAckQueue(
serverId: serverStorageScope(widget.serverId),
),
);
StreamSubscription<JsonMap>? _attentionFrames;
int _attentionEpoch = 0;
/// The count the shell's Runs tab shows; only a changed count rebuilds it.
final ValueNotifier<int> _attentionCount = ValueNotifier<int>(0);
/// Android background delivery (no service elsewhere).
final NotificationServiceBridge _deliveryService =
createNotificationServiceBridge();
late final NotificationServiceController _deliveryController =
NotificationServiceController(
_deliveryService,
requestNotificationPermission: () async {
await _notifications.requestPermission();
},
);
NotificationServiceHandoff? _deliveryHandoff;
late final AppTerminals _terminals;
late final WindowManager _windows;
late final ChatRuntime _chatRuntime;
late final ChatWindows _chatWindows;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_session = AppSession(
endpoint: widget.server.uri,
client: widget.client,
knownServer: widget.knownServer,
addresses: widget.serverAddresses,
);
// The service authenticates like the app: hand over each proven server.
_deliveryHandoff = NotificationServiceHandoff(
bridge: _deliveryService,
client: _session.client,
serverId: widget.serverId,
);
bindServerIdentity(_session.gateway, widget.serverId);
bindServerIdentity(_session.client, widget.serverId);
// One server for now: windows are kept per server, and this one's show.
_windows =
(widget.windows ??
WindowManager(
kinds: WindowKinds(),
store: const SharedPreferencesWindowStore(),
))
..server = widget.serverId ?? 'server';
final chatGateway = widget.chatPool?.gateway ?? _session.gateway;
final chatScope = widget.chatPool != null
? 'all-saved-servers'
: serverStorageScope(serverIdentity(chatGateway));
_chatRuntime = ChatRuntime(gateway: chatGateway, serverKey: chatScope);
_chatWindows = ChatWindows(
manager: _windows,
runtime: _chatRuntime,
openInChat: (id) => _delegate.goTo(AppRoute.chatSession(id)),
ready: _chatReady,
readiness: Listenable.merge([_session, ?widget.chatPool]),
)..start();
_session.addListener(_chatSyncChanged);
widget.chatPool?.addListener(_chatSyncChanged);
_chatSyncChanged();
_terminals = AppTerminals(
pool: widget.chatPool,
connection: _session,
connected: () => _session.connected,
gateway: _session.gateway,
machineId: widget.serverId ?? 'server',
machineName:
widget.servers?.catalog.active?.name ??
widget.server.uri?.host ??
'This server',
layout: widget.terminalLayout ?? TerminalLayout.instance,
windows: _windows,
);
// Every kind is registered: saved windows can be restored. Then the
// terminal may open its window, and the floating chats an older build
// saved are brought over once.
unawaited(
_windows.restore().then((_) {
if (!mounted) return null;
_terminals.floating?.ready();
return _chatWindows.migrate(
SharedPreferencesChatFloatStore(serverScope: chatScope),
);
}),
);
_ownsProvider = widget.routeInformationProvider == null;
_provider =
widget.routeInformationProvider ??
PlatformRouteInformationProvider(
initialRouteInformation: widget.resetRoute
? RouteInformation(uri: Uri.parse('/pipelines'))
: initialRouteInformation(),
);
// A malformed or unknown boot path renders Pipelines, so make the address
// bar agree with the rendered destination instead of showing a dead link.
// The comparison includes the query: `?visit=N` is part of the route, while
// a dropped or unknown query is canonicalised away.
final location = routeLocation(_provider.value.uri);
var initial =
widget.servers?.newChatServerId == widget.serverId &&
widget.serverId != null
? AppRoute.chat
: AppRoute.parse(location);
if (widget.chatPool != null) {
final id = initial.chatSessionId;
if (id != null) {
initial = AppRoute.chatSession(
widget.chatPool!.gateway.normalizeId(id),
);
}
}
final nativeDefault =
widget.routeInformationProvider == null &&
!kIsWeb &&
const [
'',
'/',
].contains(WidgetsBinding.instance.platformDispatcher.defaultRouteName);
final restoreTab =
!widget.resetRoute &&
(Uri.tryParse(location)?.path == '/' || 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)),
type: RouteInformationReportingType.neglect,
);
}
// Kept as a compatibility field on the widget; composition is Material-only.
_cupertino = false;
_notifications.onOpenRun = (id) {
if (mounted) _delegate.goTo(AppRoute.run(id));
};
unawaited(_notifications.load());
bindAttentionAckSync(_session.gateway, _ackSync);
unawaited(_ackSync.load());
unawaited(_attention.load());
_attentionFrames = _session.gateway.frames
.where((frame) => frame['type'] == 'run_event')
.listen(_attention.observeFrame);
_session.addListener(_attentionSessionChanged);
_session.addListener(_updateEndpointChanged);
_attention.addListener(_attentionChanged);
MachineElevation.defaultPrompt = _elevationPrompt;
_delegate = AppRouterDelegate(
initial: initial,
cupertino: _cupertino,
templatesBuilder: _buildTemplates,
schedulesBuilder: _buildSchedules,
builder: _buildShell,
);
_delegate.addListener(_routeChanged);
// Seed retained destinations for deep links as well as later navigation.
_rememberChatRoute(initial);
_rememberBodyRoute(_delegate.shellRoute);
unawaited(_restoreTabLocations(restoreTab));
_chatQuestionNotices = ChatQuestionNotices(
gateway: _session.gateway,
canNotify: () => _notifications.canNotify,
activeChatSessionId: () {
final route = _delegate.shellRoute;
return route.kind == AppRouteKind.chat ? route.chatSessionId : null;
},
sessionTitle: _chatSessionTitle,
openChat: (id) {
if (mounted) _delegate.goTo(AppRoute.chatSession(id));
},
bridge: _notifications.bridge,
);
_config = RouterConfig<AppRoute>(
routeInformationParser: const AppRouteParser(),
routerDelegate: _delegate,
routeInformationProvider: _provider,
// Android's Back button and back gesture go through the router, so
// they close a page or step up a level instead of leaving the app.
backButtonDispatcher: RootBackButtonDispatcher(),
);
unawaited(_session.start());
WidgetsBinding.instance.addPostFrameCallback((_) {
unawaited(_checkLaunchUpdate());
});
}
void _updateEndpointChanged() {
if (_launchUpdateEndpoint == _session.endpoint) return;
_launchUpdateEndpoint = _session.endpoint;
WidgetsBinding.instance.addPostFrameCallback((_) {
unawaited(_checkLaunchUpdate());
});
WidgetsBinding.instance.ensureVisualUpdate();
}
Future<void> _checkLaunchUpdate() async {
if (!mounted || _launchUpdateBusy) return;
final dialogContext = _delegate.navigatorContext;
if (dialogContext == null || !dialogContext.mounted) return;
_launchUpdateBusy = true;
final endpoint = _session.endpoint;
try {
final update = await _launchUpdates.check(
web: widget.webPlatform,
android: widget.androidSupported ?? appUpdatesSupported,
webBuildId: widget.webBuildId,
page: widget.webPageUri ?? Uri.base,
endpoint: endpoint,
readWeb: widget.webReleaseReader,
installedVersion: widget.installedVersionReader,
readAndroid: widget.androidFeedReader,
readNative: widget.servers == null
? null
: () => newestServerUpdate(
widget.servers!.catalog.servers,
stillTrusted: (source, uri) => updateSourceStillTrusted(
widget.servers!.catalog.servers,
source,
uri,
),
),
nativeScope:
widget.servers?.catalog.servers
.map((s) => '${s.id}:${s.endpoints.join(',')}')
.join(';') ??
'',
);
if (!mounted || update == null || !dialogContext.mounted) return;
if (!widget.webPlatform && endpoint != _session.endpoint) return;
_launchUpdates.markOffered(update);
final accepted = await showLaunchUpdateDialog(
dialogContext,
web: update is WebLaunchUpdate,
sourceName: update is AndroidLaunchUpdate
? update.update.sourceName
: '',
nativePlatform: update is AndroidLaunchUpdate
? update.update.platform
: '',
cupertino: _cupertino,
);
if (accepted != true || !mounted || !dialogContext.mounted) return;
if (!widget.webPlatform && endpoint != _session.endpoint) return;
try {
if (update is WebLaunchUpdate) {
await widget.webRefresher();
} else {
await installLaunchUpdate(
dialogContext,
(update as AndroidLaunchUpdate).update,
installer: widget.androidInstaller,
cupertino: _cupertino,
);
}
} catch (error) {
if (mounted && dialogContext.mounted) {
await showLaunchUpdateFailure(
dialogContext,
error,
cupertino: _cupertino,
);
}
}
} catch (_) {
// An offline or signed-out update feed never interrupts opening the app.
} finally {
_launchUpdateBusy = false;
if (mounted && endpoint != _session.endpoint) {
unawaited(_checkLaunchUpdate());
}
}
}
@override
void dispose() {
_tabLocations.dispose();
WidgetsBinding.instance.removeObserver(this);
_deliveryHandoff?.dispose();
_session.removeListener(_attentionSessionChanged);
_session.removeListener(_updateEndpointChanged);
unawaited(_attentionFrames?.cancel());
_attention.removeListener(_attentionChanged);
_attention.dispose();
bindAttentionAckSync(_session.gateway, null);
_ackSync.dispose();
_attentionCount.dispose();
_notifications.dispose();
_deliveryController.dispose();
_chatQuestionNotices?.dispose();
if (identical(MachineElevation.defaultPrompt, _elevationPrompt)) {
MachineElevation.defaultPrompt = null;
}
_delegate.removeListener(_routeChanged);
_delegate.dispose();
if (_ownsProvider) {
(_provider as PlatformRouteInformationProvider).dispose();
}
_terminals.dispose();
_session.removeListener(_chatSyncChanged);
widget.chatPool?.removeListener(_chatSyncChanged);
_chatWindows.dispose();
_chatRuntime.dispose();
if (widget.windows == null) _windows.dispose();
_session.dispose();
super.dispose();
}
/// Returning to the foreground recovers a socket the client dropped while
/// the app was hidden. A deliberate Disconnect reaches idle and is left
/// alone, and a connected or connecting socket is not churned: only the
/// disconnected state reopens the validated endpoint now, cancelling the
/// pending backoff delay. The session's connected transition then re-sends
/// the send-only run watch (and Settings re-pings for its build/protocol
/// facts), so no screen re-subscribes on its own.
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state != AppLifecycleState.resumed) {
_foregroundVisitHandled = false;
return;
}
if (_foregroundVisitHandled) return;
_foregroundVisitHandled = true;
_launchUpdates.beginVisit();
unawaited(_checkLaunchUpdate());
final connection = _session.connection.kind;
if (shouldReconnectOnForeground(connection)) {
unawaited(_session.retry());
return;
}
if (connection != ConnectionKind.connected) return;
// Foreground return refreshes the visible Runs list and selected detail.
// Pipeline definitions retain their current data while being inspected.
if (_delegate.hasTransientRoute || _isEditingText) return;
final route = _delegate.route;
if (route.kind == AppRouteKind.pipelines &&
route.pipelineId == null &&
route.stageKey == null) {
setState(() => _pipelinesRefresh++);
} else if (route.kind == AppRouteKind.runs) {
setState(() => _runsRefresh++);
}
}
bool get _isEditingText => primaryFocusTakesTyping();
/// A replaced socket drops the attention status baseline so the gap cannot
/// replay a transition; the Runs list's next read reseeds the rows.
void _attentionSessionChanged() {
final epoch = _session.connectionEpoch;
if (epoch == _attentionEpoch) return;
_attentionEpoch = epoch;
_attention.resetForReconnect();
// Every connected transition sends acknowledgements queued while offline
// and re-reads the shared set, so a gap cannot leave this device stale.
if (_session.connected) unawaited(_ackSync.connected());
}
/// Mirrors the controller's entry count for the shell. The Runs list seeds
/// the rows from inside its own build, and the shell sits above that layout
/// scope, so a count that changes mid-build lands after the frame; a pushed
/// frame arrives outside any build and applies at once.
void _attentionChanged() {
if (!mounted) return;
final count = _attention.entries.length;
if (count == _attentionCount.value) return;
if (SchedulerBinding.instance.schedulerPhase ==
SchedulerPhase.persistentCallbacks) {
SchedulerBinding.instance.addPostFrameCallback(
(_) => _attentionChanged(),
);
return;
}
_attentionCount.value = count;
}
@override
Widget build(BuildContext context) => widget.servers == null
? MyApp.router(cupertino: _cupertino, routerConfig: _config)
: ServerContext(
connections: widget.servers!,
serverId: widget.serverId,
child: MyApp.router(cupertino: _cupertino, routerConfig: _config),
);
/// Open a result through the exact identity the hit records. An unresolvable
/// hit navigates nowhere: the screen already presents it read-only rather than
/// guessing a destination.
///
/// A field or artifact hit has no URL of its own: both open the run and leave
/// a resolved-once request for the mounted detail, which selects the recorded
/// Summary section or visit as soon as that run's steps are available. A
/// sequence or field the run did not record leaves the plain detail.
void _openSearchResult(JsonMap hit) {
final resolved = searchTargetFor(hit);
if (resolved is! ResolvedSearchTarget) return;
AppRoute? route;
RunSearchSelection? selection;
switch (resolved.target) {
case SearchPipelineTarget(:final pipelineId):
route = AppRoute.pipeline(pipelineId);
case SearchVersionTarget(:final pipelineId, :final version):
route = AppRoute.pipeline(pipelineId, version: version);
case SearchRunTarget(:final runId):
route = AppRoute.run(runId);
case SearchStepTarget(:final runId, :final stage, :final visit):
// The server records a 1-based visit number; the route's `visit` is the
// zero-based index into the recorded timeline.
final index = visit == null || visit < 1 ? null : visit - 1;
route = stage == null
? AppRoute.run(runId)
: AppRoute.run.stage(runId, stage, visit: index);
case SearchFieldTarget(:final runId, :final sequence, :final field):
selection = RunSearchSelection(
runId: runId,
sequence: sequence,
field: field,
);
route = AppRoute.run(runId);
case SearchArtifactTarget(:final runId, :final sequence, :final url):
if (runId != null) {
selection = RunSearchSelection(
runId: runId,
sequence: sequence,
artifactUrl: url,
);
route = AppRoute.run(runId);
}
case SearchChatTarget(:final sessionId):
// The Chat tab selects the routed session in its list and shows its
// thread, exactly as a chat notification opens it.
route = AppRoute.chatSession(sessionId);
}
if (route == null) return;
setState(() => _pendingRunSearch = selection);
_delegate.goTo(route);
}
/// The mounted run detail applied the pending request; reopening the same run
/// later starts from its plain detail and never replays the search selection.
void _runSearchConsumed() {
if (!mounted || _pendingRunSearch == null) return;
setState(() => _pendingRunSearch = null);
}
/// 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 = tabForRoute(_delegate.route);
final last = _tabRoutes[destination];
if (destination == AppDestination.chat && current == destination) {
final reopened = chatRouteForRetap(
_delegate.shellRoute,
_chatWorkspaceRoute,
isValidSession: (id) =>
_availableChatSessionIds == null ||
_availableChatSessionIds!.contains(id),
);
_delegate.goTo(reopened ?? _routeOf(destination));
return;
}
_delegate.goTo(last ?? _routeOf(destination));
}
void _routeChanged() {
final shown = _delegate.route;
final id = shown.chatSessionId;
if (id != null && widget.chatPool != null) {
final scoped = widget.chatPool!.gateway.normalizeId(id);
if (scoped != id) {
_delegate.goTo(AppRoute.chatSession(scoped));
return;
}
}
_tabLocations.record(shown);
_rememberBodyRoute(_delegate.shellRoute);
_rememberChatRoute(shown);
final pending = _pendingRunSearch;
if (!mounted || pending == null) return;
final route = _delegate.shellRoute;
if (route.kind == AppRouteKind.runs && route.runId == pending.runId) return;
setState(() => _pendingRunSearch = null);
}
Future<String?> _chatSessionTitle(String id) async {
id = widget.chatPool?.gateway.normalizeId(id) ?? id;
final reply = await (widget.chatPool?.gateway ?? _session.gateway).call(
'chat_sessions',
);
final sessions = reply['chat_sessions'];
if (sessions is! List) return null;
for (final value in sessions) {
if (value is Map && value['id'] == id) return '${value['title'] ?? ''}';
}
return null;
}
/// The Templates page above Settings. Closing it restores the same Settings
/// screen instance, so an edited field or an open connection state survives.
Widget _buildSchedules(BuildContext context) => SchedulesDestination(
session: _session,
server: widget.server,
onBack: _delegate.closeSchedules,
onOpenPipeline: (id) => _delegate.goTo(AppRoute.pipeline(id)),
);
Widget _buildTemplates(BuildContext context) => TemplatesDestination(
session: _session,
server: widget.server,
onBack: _delegate.closeTemplates,
onCreated: _templateCreated,
initialKey: _delegate.route.templateKey,
);
/// An accepted create only invalidates Pipelines; the list is re-read and the
/// new row appears from the server's reply, never from an optimistic insert.
void _templateCreated(JsonMap _) {
if (!mounted) return;
setState(() => _pipelinesRefresh++);
}
/// Opens the run id an accepted launch named and invalidates the Runs list.
///
/// The order is deliberate: the list token is already advanced when the Runs
/// screen mounts for the first time, so it performs one fresh `list_runs`
/// read and then opens the route's run. No row is inserted locally.
void _runStarted(int id) {
if (!mounted) return;
setState(() => _runsRefresh++);
_delegate.goTo(AppRoute.run(id));
}
/// Whether a chat can be read: the server has been reached (or saved
/// machines connect on their own).
bool _chatReady() {
final pool = widget.chatPool;
if (pool != null && pool.servers.catalog.servers.isNotEmpty) return true;
return _session.everConnected || _session.connected;
}
/// A replaced socket makes open chats re-subscribe, also in windows.
void _chatSyncChanged() => _chatRuntime.syncToken.value =
widget.chatPool?.revision ?? _session.connectionEpoch;
/// The shell rebuilds its Runs tab badge from the attention count alone; the
/// destination bodies keep their state through it.
Widget _buildShell(BuildContext context, AppRoute route) =>
ValueListenableBuilder<int>(
valueListenable: _attentionCount,
builder: (context, count, _) => _terminals.surround(
_shellFor(route, count),
cupertino: _cupertino,
onChat: route.kind == AppRouteKind.chat,
windows: WindowHost(manager: _windows),
),
);
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) {
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);
return AdaptiveShell(
// The terminal button sits on the Chat tab only; the keyboard
// shortcut still toggles the terminal everywhere.
barActions: [
// Shown on every tab while the app has floating windows.
WindowsMenuButton(manager: _windows),
if (_destinationOf(route.kind) == AppDestination.chat)
_terminals.toggle(cupertino: _cupertino),
],
attentionCount: attentionCount,
cupertino: _cupertino,
destination: _destinationOf(route.kind),
onDestinationSelected: _selectDestination,
onClosePage: () => _delegate.goTo(
_bodyRoutes[AppDestination.pipelines] ?? AppRoute.pipelines,
),
destinationBodies: {
AppDestination.pipelines: (_) => PipelinesDestination(
session: _session,
server: widget.server,
active: _destinationOf(route.kind) == AppDestination.pipelines,
legacyPendingEndpoints: widget.legacyPendingEndpoints,
refreshToken: _pipelinesRefresh,
onRunStarted: _runStarted,
onViewPipelineRuns: (id) =>
_delegate.goTo(AppRoute.runsForPipeline(id)),
onOpenSchedules: _delegate.openSchedules,
onOpenSettings: () => _delegate.goTo(AppRoute.settings),
// The open pipeline is part of the route, so Back steps out of it.
onSelectionChanged: (id) {
final current = _delegate.route;
if (current.kind != AppRouteKind.pipelines) return;
if (id == null) {
if (current.pipelineId != null) {
_delegate.goTo(AppRoute.pipelines);
}
} else if (current.pipelineId != id) {
_delegate.goTo(AppRoute.pipeline(id));
}
},
initialPipelineId: pipelinesRoute.pipelineId,
initialVersion: pipelinesRoute.version,
initialStageKey: pipelinesRoute.stageKey,
),
// The one place a field or artifact hit's selection can be resolved: the
// run detail owns the recorded visit and Summary section.
AppDestination.runs: (_) => RunSearchSelectionScope(
selection: _pendingRunSearch,
onConsumed: _runSearchConsumed,
child: RunsDestination(
session: _session,
server: widget.server,
initialRunId: runsRoute.runId,
initialPipelineId: runsRoute.pipelineId,
initialStageKey: runsRoute.stageKey,
initialVisit: runsRoute.visit,
initialDecide: runsRoute.decide,
listRefreshToken: _runsRefresh,
notifications: _notifications,
attention: _attention,
onRunSelected: (id) => _delegate.goTo(AppRoute.run(id)),
onBack: (id) => _delegate.goTo(
id == null ? AppRoute.runs : AppRoute.runsForPipeline(id),
),
onPipelineFilterChanged: (id) => _delegate.goTo(
id == null ? AppRoute.runs : AppRoute.runsForPipeline(id),
),
onOpenPipeline: (id, version) =>
_delegate.goTo(AppRoute.pipeline(id, version: version)),
),
),
AppDestination.chat: (_) => ChatDestination(
pool: widget.chatPool,
session: _session,
server: widget.server,
initialSessionId: chatRoute.chatSessionId,
onSessionSelected: (id) => _delegate.goTo(AppRoute.chatSession(id)),
onBack: () => _delegate.goTo(AppRoute.chat),
runtime: _chatRuntime,
windows: _chatWindows,
onWorkspaceEmpty: () => _chatWorkspaceRoute = null,
onAvailableSessionsChanged: (ids) {
_availableChatSessionIds = ids;
final retained = _chatWorkspaceRoute?.chatSessionId;
if (retained != null && !ids.contains(retained)) {
_chatWorkspaceRoute = null;
}
},
),
// Search is the fourth tab; a result opens its destination.
AppDestination.search: (_) => SearchDestination(
session: _session,
server: widget.server,
onOpen: _openSearchResult,
embedded: true,
),
// Settings is a page of the Pipelines tab (its bar's gear), not a
// tab; the shell shows it with Back to Pipelines.
AppDestination.settings: (_) => SettingsScreen(
terminalLayout: _terminals.layout,
navigationScope: _navigationScope,
client: _session.client,
// A phone signs in at the web login; a browser has its own.
showSignIn: !kIsWeb,
showAndroidDownload: kIsWeb,
initialEndpoint: _session.endpoint,
embedded: true,
servers: widget.servers,
store: SharedPreferencesSettingsStore(
serverId: widget.serverId ?? '',
),
onOpenTemplates: _delegate.openTemplates,
notifications: _notifications,
deliveryService: _deliveryService,
deliveryServiceController: _deliveryController,
),
},
);
}
AppDestination _destinationOf(AppRouteKind kind) => switch (kind) {
AppRouteKind.pipelines => AppDestination.pipelines,
AppRouteKind.runs => AppDestination.runs,
AppRouteKind.chat => AppDestination.chat,
AppRouteKind.search => AppDestination.search,
AppRouteKind.settings => AppDestination.settings,
// Templates and Schedules are Settings sub-pages, not a fifth tab.
AppRouteKind.templates => AppDestination.settings,
AppRouteKind.schedules => AppDestination.settings,
};
AppRoute _routeOf(AppDestination destination) => switch (destination) {
AppDestination.pipelines => AppRoute.pipelines,
AppDestination.runs => AppRoute.runs,
AppDestination.chat => AppRoute.chat,
AppDestination.search => AppRoute.search,
AppDestination.settings => AppRoute.settings,
};
}