Keep settings and delivery updates together

Preserve the reviewed grouped Settings page while fixing its embedded phone safe area, and land the accompanying notification, walkthrough, terminal, and documentation updates captured by this run.
This commit is contained in:
2026-11-12 03:27:37 +00:00
88 changed files with 3633 additions and 639 deletions
+3 -46
View File
@@ -1,54 +1,11 @@
part of 'screen.dart';
/// How many chats the visit remembers for Ctrl+Tab over a single pane.
const chatRecentSessionLimit = 8;
/// Keys the Chat destination answers from anywhere in it, also while the
/// sidebar or a toolbar owns focus: a bare `/` puts the keyboard in the open
/// chat's composer, and Ctrl+Tab over a single pane returns to the chat shown
/// before it (and back again). Both are handled before the focus tree, like
/// the workspace's pane cycling, and leave other destinations, popups,
/// dialogs and any focused text field alone.
/// chat's composer. It is handled before the focus tree, like the workspace's
/// pane cycling, and leaves other destinations, popups, dialogs and any
/// focused text field alone.
mixin _ChatScreenKeys on State<ChatScreen>, _ChatScreenWorkspace {
void _open(JsonMap session, {bool focusComposer});
/// The chats this visit has shown in the workspace, most recent first; the
/// active one leads it. In memory only: a reopened app starts afresh.
final List<String> _recentSessions = [];
/// Moves the active pane's chat to the front. Called on every workspace
/// change, including a restored layout, so the chat opened before the
/// current one is always the second entry.
@override
void _noteRecentSession() {
final id = _workspace.activePane?.sessionId;
if (id == null || id.isEmpty || _recentSessions.firstOrNull == id) return;
_recentSessions
..remove(id)
..insert(0, id);
if (_recentSessions.length > chatRecentSessionLimit) {
_recentSessions.removeLast();
}
}
/// Drops [id]: a closed chat, or one `/new` moved to a fresh session.
void _forgetRecentSession(String id) => _recentSessions.remove(id);
/// Drops every remembered chat: ids belong to one server.
@override
void _forgetRecentSessions() => _recentSessions.clear();
/// Over a single pane, opens the chat shown before the active one with its
/// composer focused; false when this visit has shown no other chat.
@override
bool _toggleRecentChat() {
final current = _workspace.activePane?.sessionId;
final previous = _recentSessions.where((id) => id != current).firstOrNull;
if (previous == null) return false;
_open(_rowFor(previous) ?? {'id': previous}, focusComposer: true);
return true;
}
/// Whether the shown destination is Chat with no popup, dialog or other
/// route over it, so a key pressed now is meant for the open chat.
@override
@@ -5,9 +5,6 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
Map<String, JsonMap> get _openedSessions;
ChatComposerFocusRequests get _composerFocus;
bool _chatOwnsKeyboard();
bool _toggleRecentChat();
void _noteRecentSession();
void _forgetRecentSessions();
JsonMap? _rowFor(String id);
void _back();
bool get _pageOpen;
@@ -130,7 +127,6 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
_workspaceBinding = null;
if (_workspaceScope != null && scope != _workspaceScope) {
_workspace.restoreLayout(ChatWorkspaceSnapshot.fromLayout(null, null)!);
_forgetRecentSessions();
_workspaceVisible = false;
_usedWorkspace = true;
_sidebarMode = ChatSidebarMode.expanded;
@@ -152,29 +148,29 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
String? _publishedWorkspaceSession;
String _workspaceSignature = '';
/// Ctrl+Tab cycles retained panes even when the sidebar or toolbar owns
/// focus. Over a single pane it swaps in the chat shown before this one
/// instead, and back again (see [_toggleRecentChat]). Command+Tab stays
/// with the operating system's application switcher. While the app's
/// terminal is shown, Ctrl+Tab moves between its tabs instead. While a
/// floating chat window holds the keyboard, Ctrl+Tab cycles those windows
/// (see [ChatWindows]).
/// Ctrl+Tab cycles the floating chat windows while any is shown, from the
/// tiling as well (see [ChatWindows]). With none shown it cycles the
/// retained panes, even when the sidebar or toolbar owns focus, and over a
/// single pane it does nothing: it never brings up a chat that is not
/// visible in the tiling. Command+Tab stays with the operating system's
/// application switcher. While the app's terminal is shown, Ctrl+Tab moves
/// between its tabs instead. A floating window that is not a chat, or any
/// other window holding the keyboard, keeps the key.
bool _cycleChatKey(KeyEvent event) {
final keyboard = HardwareKeyboard.instance;
if (event is! KeyDownEvent ||
TerminalScope.peek(context)?.claimsTabKeys == true ||
keyboardWindow()?.entry.kind == chatWindowKind ||
keyboardWindow() != null ||
event.logicalKey != LogicalKeyboardKey.tab ||
!keyboard.isControlPressed ||
keyboard.isMetaPressed ||
keyboard.isAltPressed ||
!_workspaceVisible ||
_workspace.paneCount == 0 ||
!_chatOwnsKeyboard()) {
return false;
}
if (widget.windows?.raiseTopFromTiling() ?? false) return true;
if (!_workspaceVisible || _workspace.paneCount < 2) return false;
final panes = _workspace.panes;
if (panes.length == 1 && _toggleRecentChat()) return true;
final active = panes.indexWhere(
(pane) => pane.id == _workspace.activePaneId,
);
@@ -199,7 +195,6 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
void _workspaceChanged() {
if (!mounted) return;
_noteRecentSession();
if (_workspaceBinding?.isRestoring == true) return;
final signature =
'${_workspace.activePaneId}:${_workspace.panes.map((p) => '${p.id}=${p.sessionId}').join(',')}';
@@ -1476,6 +1476,9 @@ class _ChatThreadViewState extends State<ChatThreadView> {
onPressed: _toggleFiles,
materialIcon: _filesVisible ? Icons.folder : Icons.folder_outlined,
),
// A narrow layout's terminal button, beside Files; wide keeps the
// shell bar's.
?terminalChatBarAction(context),
],
moreActions: [
?widget.sidebarControl,
-4
View File
@@ -159,7 +159,6 @@ class _ChatScreenState extends State<ChatScreen>
_workspace.open(initial);
_workspaceVisible = true;
_publishedWorkspaceSession = initial;
_noteRecentSession();
}
_workspace.addListener(_workspaceChanged);
_bindWorkspacePersistence();
@@ -238,7 +237,6 @@ class _ChatScreenState extends State<ChatScreen>
void _openBySelection(JsonMap session) =>
_open(session, focusComposer: chatSelectionFocusesComposer(session));
@override
void _open(JsonMap session, {bool focusComposer = false}) {
final id = '${session['id'] ?? ''}';
if (id.isEmpty) return;
@@ -285,7 +283,6 @@ class _ChatScreenState extends State<ChatScreen>
/// A model switch accepted here in this visit moved with the chat.
void _followNewSession(String previousId, JsonMap session, String notice) {
_runtime.movedToSession(previousId, session, notice);
_forgetRecentSession(previousId);
_workspace.replaceSession(previousId, '${session['id'] ?? ''}');
if (_workspace.paneCount == 0) _open(session);
}
@@ -293,7 +290,6 @@ class _ChatScreenState extends State<ChatScreen>
/// `/close` was accepted: the conversation leaves, back to the list, which
/// re-reads the closed row.
void _closed(String sessionId) {
_forgetRecentSession(sessionId);
for (final pane
in _workspace.panes
.where((pane) => pane.sessionId == sessionId)
@@ -194,6 +194,7 @@ class ChatWindows {
/// session list, which nothing else reads while the Chat destination is
/// not built.
void _rowsChanged() {
_noteOpenOrder();
final ids = {for (final w in windows) w.contentId};
if (ids.isEmpty || !ready) return;
final sessions = runtime.sessions;
@@ -232,7 +233,7 @@ class ChatWindows {
}
/// Ctrl+Tab and Ctrl+Shift+Tab while a floating chat window holds the
/// keyboard: the next (previous) visible chat window, in stacking order and
/// keyboard: the next (previous) shown chat window, in open order and
/// wrapping, comes to the top. The window host then gives it the keyboard,
/// its composer. Left alone when another window or the tiling has the
/// keyboard, when the terminal claims tab keys, or with one window.
@@ -245,16 +246,47 @@ class ChatWindows {
_terminalClaimsTabs()) {
return KeyEventResult.ignored;
}
final target = chatWindowAfter(
windows.where(manager.isVisible).toList(),
scope.entry.id,
step,
);
final target = chatWindowAfter(shownInOpenOrder(), scope.entry.id, step);
if (target == null) return KeyEventResult.ignored;
manager.raise(target.id);
return KeyEventResult.handled;
}
/// The ids of the chat windows in the order they were opened; a window
/// restored from a saved layout keeps its saved place. Raising a window
/// changes the stacking order, not this one, so the Ctrl+Tab cycle is
/// stable. Kept in step on every change of the windows (see [_rowsChanged]).
final List<String> _openOrder = [];
void _noteOpenOrder() {
final ids = {for (final w in windows) w.id};
_openOrder.removeWhere((id) => !ids.contains(id));
for (final w in windows) {
if (!_openOrder.contains(w.id)) _openOrder.add(w.id);
}
}
/// The shown chat windows (not minimised, their group shown), in open order.
List<WindowEntry> shownInOpenOrder() {
_noteOpenOrder();
final shown = {
for (final w in windows)
if (manager.isVisible(w)) w.id: w,
};
return [for (final id in _openOrder) ?shown[id]];
}
/// Ctrl+Tab from the tiling or the chat list while chat windows are shown:
/// the top-most shown chat window comes to the top and its composer takes
/// the keyboard. False, doing nothing, when no chat window is shown.
bool raiseTopFromTiling() {
final top = windows.where(manager.isVisible).lastOrNull;
if (top == null) return false;
manager.raise(top.id);
kind.focusContent(top);
return true;
}
bool _terminalClaimsTabs() {
final context = FocusManager.instance.primaryFocus?.context;
return context != null &&
@@ -4,8 +4,10 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'host_platform_stub.dart' if (dart.library.io) 'host_platform_io.dart';
import 'notification_service_events.dart';
import 'notification_service_status.dart';
export 'notification_service_events.dart';
export 'notification_service_status.dart';
/// The app's handle on Android background delivery: a native foreground
@@ -35,6 +37,9 @@ abstract interface class NotificationServiceBridge {
/// Opens Android's "ignore battery optimisations" prompt.
Future<bool> requestBatteryExemption();
/// The service's recent connection events, newest first (at most 50).
Future<List<NotificationConnectionEvent>> connectionEvents();
}
/// The bridge for this platform. One instance owns the channel's handler.
@@ -104,6 +109,16 @@ class MethodChannelNotificationServiceBridge
@override
Future<bool> requestBatteryExemption() async =>
await _channel.invokeMethod<bool>('requestBatteryExemption') ?? false;
@override
Future<List<NotificationConnectionEvent>> connectionEvents() async {
final reply = await _channel.invokeListMethod<Object?>('connectionEvents');
return [
for (final item in reply ?? const <Object?>[])
if (item is Map<Object?, Object?>)
NotificationConnectionEvent.fromMap(item),
];
}
}
/// Web, iOS and desktop: no background service; nothing is pretended.
@@ -136,4 +151,8 @@ class UnsupportedNotificationServiceBridge
@override
Future<bool> requestBatteryExemption() async => false;
@override
Future<List<NotificationConnectionEvent>> connectionEvents() async =>
const [];
}
@@ -21,22 +21,52 @@ class NotificationServiceController extends ChangeNotifier {
late final StreamSubscription<NotificationServiceStatus> _changes;
NotificationServiceStatus? _status;
List<NotificationConnectionEvent> _events = const [];
bool _busy = false;
String _error = '';
bool _disposed = false;
NotificationServiceStatus? get status => _status;
/// The service's connection log, newest first.
List<NotificationConnectionEvent> get events => _events;
bool get busy => _busy;
String get error => _error;
bool _askedForExemption = false;
Future<void> load() => _run(bridge.status);
/// Opens Settings: reads the status and, when delivery is already on but the
/// battery exemption is missing (existing users, upgrades), asks for it once
/// per controller. The warning row stays if the prompt is declined.
Future<void> open() async {
await load();
final current = _status;
if (current != null &&
current.enabled &&
!current.batteryExempt &&
!_askedForExemption) {
_askedForExemption = true;
await allowBackgroundDelivery();
}
}
/// Re-reads after returning from a system screen (permission, battery).
/// Never prompts again: a declined prompt is shown as the warning row.
Future<void> refresh() => load();
/// Switching delivery on first asks for the battery exemption, so the
/// service starts with the prompt answered: delivery should not pause while
/// the phone is idle.
Future<void> setEnabled(bool enabled) => _run(() async {
if (enabled && _status?.notificationsAllowed == false) {
await requestNotificationPermission?.call();
if (enabled) {
if (_status?.notificationsAllowed == false) {
await requestNotificationPermission?.call();
}
if (_status?.batteryExempt == false) {
await bridge.requestBatteryExemption();
}
}
return bridge.setEnabled(enabled);
});
@@ -58,6 +88,7 @@ class NotificationServiceController extends ChangeNotifier {
_notify();
try {
_status = await action();
_events = await bridge.connectionEvents();
} catch (error) {
_error = 'Background delivery is unavailable: $error';
} finally {
@@ -69,6 +100,17 @@ class NotificationServiceController extends ChangeNotifier {
void _apply(NotificationServiceStatus status) {
_status = status;
_notify();
// The service logs its own transitions; re-read so the log stays current.
unawaited(_refreshEvents());
}
Future<void> _refreshEvents() async {
try {
_events = await bridge.connectionEvents();
} catch (error) {
_error = 'Background delivery is unavailable: $error';
}
_notify();
}
void _notify() {
@@ -0,0 +1,64 @@
/// One entry of the background service's connection log, as Settings shows
/// it for diagnosis. The service keeps the newest events first.
class NotificationConnectionEvent {
const NotificationConnectionEvent({
required this.time,
required this.event,
this.error,
this.code,
});
final DateTime time;
/// The service's wire name for what happened, e.g. `failed`.
final String event;
final String? error;
/// The HTTP status of a failed handshake, when there was one.
final int? code;
factory NotificationConnectionEvent.fromMap(Map<Object?, Object?> map) =>
NotificationConnectionEvent(
time: DateTime.fromMillisecondsSinceEpoch(
(map['time'] as num?)?.toInt() ?? 0,
),
event: map['event'] as String? ?? 'unknown',
error: map['error'] as String?,
code: (map['code'] as num?)?.toInt(),
);
/// A short, plain name for the event.
String get title => switch (event) {
'connecting' => 'Opening socket',
'connected' => 'Socket opened',
'closed' => 'Socket closed',
'failed' => 'Socket failed',
'retry_scheduled' => 'Retry scheduled',
'sign_in_required' => 'Session refused',
'refused' => 'Subscribe refused',
'network_available' => 'Network available',
'network_lost' => 'Network lost',
'invalid_endpoint' => 'Invalid address',
'watchdog_restart' => 'Watchdog restart',
'task_removed' => 'App closed from recents',
'stopped' => 'Stopped',
_ => event,
};
/// The HTTP code and error text, when there are any.
String? get detail {
final parts = [
if (code != null) 'HTTP $code',
if (error != null && error!.isNotEmpty) error!,
];
return parts.isEmpty ? null : parts.join(' · ');
}
/// Local time as `MM-DD HH:MM:SS`.
String get timeLabel {
String two(int value) => value.toString().padLeft(2, '0');
final local = time.toLocal();
return '${two(local.month)}-${two(local.day)} '
'${two(local.hour)}:${two(local.minute)}:${two(local.second)}';
}
}
@@ -5,7 +5,8 @@ enum DeliveryState {
connecting('connecting'),
connected('connected'),
reconnecting('reconnecting'),
waitingForNetwork('waiting_for_network');
waitingForNetwork('waiting_for_network'),
signInRequired('sign_in_required');
const DeliveryState(this.wire);
@@ -59,6 +60,8 @@ class NotificationServiceStatus {
DeliveryState.connecting => 'Connecting…',
DeliveryState.reconnecting => 'Reconnecting…',
DeliveryState.waitingForNetwork => 'Waiting for a network',
DeliveryState.signInRequired =>
'Sign in to Pipelines again to keep notifications',
DeliveryState.unconfigured => 'Starts after the app connects to a server',
DeliveryState.off => enabled ? 'Not running' : 'Off',
};
@@ -16,11 +16,24 @@ const deviceDeliveryNote =
'quiet "Pipelines is connected" notification while it runs.';
const deviceDeliveryBatteryLabel = 'Allow background delivery';
const deviceDeliveryNotificationsLabel = 'Allow notifications';
const deviceDeliveryWarningTitle = 'Delivery can pause while idle';
const deviceDeliveryWarningText =
'Android may pause Pipelines in the background, so notifications can '
'arrive late. Allow background delivery above.';
const deviceDeliverySamsungNote =
'Samsung phones: also add Pipelines under Settings › Battery › '
'Background usage limits › Never sleeping apps.';
const deviceDeliveryLogTitle = 'Connection log';
const deviceDeliveryLogEmpty = 'No connection events yet';
abstract final class DeviceDeliveryKeys {
static const toggle = ValueKey<String>('settings.deviceDelivery.toggle');
static const status = ValueKey<String>('settings.deviceDelivery.status');
static const battery = ValueKey<String>('settings.deviceDelivery.battery');
static const batteryWarning = ValueKey<String>(
'settings.deviceDelivery.batteryWarning',
);
static const log = ValueKey<String>('settings.deviceDelivery.log');
static const permission = ValueKey<String>(
'settings.deviceDelivery.permission',
);
@@ -66,7 +79,7 @@ class _SettingsDeviceDeliverySectionState
void initState() {
super.initState();
_lifecycle;
unawaited(_controller.load());
unawaited(_controller.open());
}
@override
@@ -136,7 +149,45 @@ class _SettingsDeviceDeliverySectionState
enabled: !status.batteryExempt && !_controller.busy,
onTap: () => unawaited(_controller.allowBackgroundDelivery()),
),
if (status != null && enabled && !status.batteryExempt)
SettingsRow(
key: DeviceDeliveryKeys.batteryWarning,
leading: Icon(
Icons.warning_amber_rounded,
color: settingsErrorColor(context),
),
title: const Text(deviceDeliveryWarningTitle),
subtitle: Text(
'$deviceDeliveryWarningText\n$deviceDeliverySamsungNote',
),
),
if (status != null)
ExpansionTile(
key: DeviceDeliveryKeys.log,
title: const Text(deviceDeliveryLogTitle),
children: _logRows(),
),
],
);
}
List<Widget> _logRows() {
final events = _controller.events;
if (events.isEmpty) {
return const <Widget>[ListTile(title: Text(deviceDeliveryLogEmpty))];
}
return [
for (final event in events)
ListTile(
dense: true,
title: Text(event.title),
subtitle: Text(
[
event.timeLabel,
if (event.detail != null) event.detail!,
].join('\n'),
),
),
];
}
}
+17 -6
View File
@@ -184,15 +184,26 @@ class _SettingsScreenState extends State<SettingsScreen> {
@override
Widget build(BuildContext context) {
final content = SafeArea(
bottom: false,
child: SettingsSearchPage(sections: _pageSections()),
);
if (widget.embedded) return content;
final page = SettingsSearchPage(sections: _pageSections());
if (widget.embedded) {
// The shell's floating tab bar sits over this body, and the body reads
// the bar's height as its bottom padding. The page's rows are controls
// and text, so they stop at the bar's top edge instead of scrolling
// under the glass where they cannot be read. The reserved space is
// removed from the page's own inset so it is not counted twice.
return Padding(
padding: EdgeInsets.only(bottom: MediaQuery.paddingOf(context).bottom),
child: MediaQuery.removePadding(
context: context,
removeBottom: true,
child: SafeArea(bottom: false, child: page),
),
);
}
return Scaffold(
extendBodyBehindAppBar: true,
appBar: const SegmentedBar(title: 'Settings'),
body: content,
body: SafeArea(bottom: false, child: page),
);
}
}
@@ -3,9 +3,12 @@ import 'dart:async';
import 'package:flutter/material.dart';
import '../../core/api_gateway.dart';
import '../../shell/list_detail_policy.dart';
import '../../ui/adaptive/segmented_bar_overflow.dart';
import '../chat/ui/sessions/chat_adaptive.dart';
import 'terminal_hub.dart';
import 'terminal_scope.dart';
import 'terminal_toggle_button.dart';
/// The first time the terminal is shown in an app run it starts one
/// terminal, as New terminal does (it shows the machine's login prompt),
@@ -49,6 +52,23 @@ void openInTerminal(
);
}
/// The open chat's own bar button that shows or hides the terminal, on a
/// narrow layout. It is a plain [ChatBarAction] like Files and More, so it
/// matches them in style, size and states. A wide layout returns null: its
/// shell bar keeps the terminal button over the list column. Null too with
/// no terminal surface.
Widget? terminalChatBarAction(BuildContext context) {
if (showsListBesideDetail(context)) return null;
final actions = TerminalScope.maybeOf(context);
if (actions == null) return null;
return ChatBarAction(
label: TerminalToggleButton.label,
identifier: 'chat-terminal-toggle',
onPressed: actions.toggle,
materialIcon: Icons.terminal,
);
}
/// The chat actions menu's "Open in terminal" for the chat's folder, or
/// null when the app has no terminal surface or the chat no folder.
Widget? terminalOpenMenuAction(
@@ -6,6 +6,9 @@ import 'terminal_shortcuts.dart';
/// The shell bar's Terminal button: shows or hides the terminal (also
/// Alt+T, Ctrl+T, Cmd+T and Ctrl+`, where the platform delivers them).
///
/// It is a plain bar IconButton like Files and More: no selected tint, so
/// its shown state is announced to assistive technology only.
class TerminalToggleButton extends StatelessWidget {
const TerminalToggleButton({super.key, required this.layout});
@@ -22,12 +25,14 @@ class TerminalToggleButton extends StatelessWidget {
listenable: layout,
builder: (context, _) {
final shown = layout.visible;
return IconButton(
key: const ValueKey('shell.terminal'),
tooltip: label,
isSelected: shown,
onPressed: actions.toggle,
icon: const Icon(Icons.terminal),
return Semantics(
toggled: shown,
child: IconButton(
key: const ValueKey('shell.terminal'),
tooltip: label,
onPressed: actions.toggle,
icon: const Icon(Icons.terminal),
),
);
},
);
@@ -0,0 +1,183 @@
import 'package:flutter/material.dart';
import '../../ui/adaptive/app_popups.dart';
import 'walkthrough_harness_command.dart';
import 'walkthrough_steps.dart';
/// Opens the walkthrough as a Material details sheet on phones and a dialog on
/// wide windows. [onClosed] runs once however it closes (Skip, Done, the close
/// button or a tap outside), so the caller can record it as seen.
Future<void> showFirstRunWalkthrough(
BuildContext context, {
Future<void> Function()? onClosed,
}) async {
await showAppDetails<void>(
context,
maxWidth: 560,
builder: (sheet) =>
FirstRunWalkthrough(onClose: () => Navigator.of(sheet).pop()),
);
await onClosed?.call();
}
/// The four-page stepper: Back and Next between pages, Skip on every page and
/// Done on the last. Every control is a standard Material button; the layout
/// wraps rather than clipping at large text scales.
class FirstRunWalkthrough extends StatefulWidget {
const FirstRunWalkthrough({
super.key,
required this.onClose,
this.steps = walkthroughSteps,
});
/// Called by Skip, Done and the close button.
final VoidCallback onClose;
final List<WalkthroughStep> steps;
@override
State<FirstRunWalkthrough> createState() => _FirstRunWalkthroughState();
}
class _FirstRunWalkthroughState extends State<FirstRunWalkthrough> {
int _index = 0;
bool get _last => _index == widget.steps.length - 1;
void _back() => setState(() => _index = _index > 0 ? _index - 1 : 0);
void _next() => setState(() => _index = _last ? _index : _index + 1);
@override
Widget build(BuildContext context) {
final step = widget.steps[_index];
final theme = Theme.of(context);
final content = Semantics(
scopesRoute: true,
namesRoute: true,
explicitChildNodes: true,
label: 'Pipelines walkthrough',
child: Padding(
padding: const EdgeInsets.fromLTRB(24, 8, 24, 24),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'Step ${_index + 1} of ${widget.steps.length}',
key: const ValueKey<String>('walkthrough.progress'),
style: theme.textTheme.labelLarge,
),
const SizedBox(height: 8),
LinearProgressIndicator(value: (_index + 1) / widget.steps.length),
const SizedBox(height: 20),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Icon(step.icon, color: theme.colorScheme.primary),
const SizedBox(width: 12),
Expanded(
child: Text(
step.title,
key: ValueKey<String>('walkthrough.title.$_index'),
style: theme.textTheme.headlineSmall,
),
),
],
),
const SizedBox(height: 12),
Text(step.body, style: theme.textTheme.bodyLarge),
for (final point in step.points) ...<Widget>[
const SizedBox(height: 8),
_Point(text: point),
],
if (step.showsHarnessCommand) ...<Widget>[
const SizedBox(height: 16),
const WalkthroughHarnessCommand(),
],
const SizedBox(height: 24),
_Footer(
last: _last,
canGoBack: _index > 0,
onBack: _back,
onNext: _last ? widget.onClose : _next,
onSkip: widget.onClose,
),
],
),
),
);
// A wide window wraps the sheet's content in its own scroll view; a phone
// sheet does not, so the page scrolls here at large text scales.
return usesDesktopPopups(context)
? content
: SingleChildScrollView(child: content);
}
}
class _Point extends StatelessWidget {
const _Point({required this.text});
final String text;
@override
Widget build(BuildContext context) => Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const Padding(
padding: EdgeInsets.only(top: 2),
child: Icon(Icons.circle, size: 6),
),
const SizedBox(width: 12),
Expanded(
child: Text(text, style: Theme.of(context).textTheme.bodyMedium),
),
],
);
}
class _Footer extends StatelessWidget {
const _Footer({
required this.last,
required this.canGoBack,
required this.onBack,
required this.onNext,
required this.onSkip,
});
final bool last;
final bool canGoBack;
final VoidCallback onBack;
final VoidCallback onNext;
final VoidCallback onSkip;
@override
Widget build(BuildContext context) => Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 8,
runSpacing: 8,
children: <Widget>[
TextButton(
key: const ValueKey<String>('walkthrough.skip'),
onPressed: onSkip,
child: const Text('Skip'),
),
Wrap(
spacing: 8,
runSpacing: 8,
children: <Widget>[
TextButton(
key: const ValueKey<String>('walkthrough.back'),
onPressed: canGoBack ? onBack : null,
child: const Text('Back'),
),
FilledButton(
key: const ValueKey<String>('walkthrough.next'),
onPressed: onNext,
child: Text(last ? 'Done' : 'Next'),
),
],
),
],
);
}
@@ -0,0 +1,200 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
import '../../core/api_gateway.dart';
import 'first_run_walkthrough.dart';
import 'walkthrough_store.dart';
/// Reports whether the server has no pipelines, runs or chats yet. Returns null
/// when any of the three lists cannot be read, so an unreadable server never
/// triggers the walkthrough.
Future<bool?> serverHasNoWorkYet(ApiGateway? gateway) async {
if (gateway == null) return null;
try {
final replies = await Future.wait(<Future<JsonMap>>[
gateway.call('list_pipelines', {'include_archived': true}),
gateway.call('list_runs'),
gateway.call('chat_sessions'),
]);
final lists = <Object?>[
replies[0]['pipelines'],
replies[1]['runs'],
replies[2]['chat_sessions'],
];
if (lists.any((list) => list is! List)) return null;
return lists.every((list) => (list as List).isEmpty);
} catch (_) {
return null;
}
}
/// Offers the walkthrough from the Pipelines page, which is the first screen a
/// new user sees. It is offered when:
///
/// * the device has not finished or skipped it yet (first launch, once); or
/// * the device already has, and the connected server has no pipelines, runs
/// or chats, and that server has not been offered it before.
///
/// The server check needs a connected session. While disconnected it waits, and
/// it runs again on each new connection until the server answers. A check that
/// cannot read the server leaves the gate open to retry; a decided check (the
/// walkthrough shown, or the server has work) ends it for this mount.
///
/// Nothing is shown while the store cannot be read, because an unavailable
/// store reports "seen". The check runs only while [enabled] (the Pipelines tab
/// is the one showing).
class FirstRunWalkthroughGate extends StatefulWidget {
const FirstRunWalkthroughGate({
super.key,
required this.child,
required this.store,
required this.enabled,
required this.serverScope,
required this.connection,
required this.connected,
this.gateway,
});
final Widget child;
final WalkthroughStore store;
/// Whether the Pipelines page is the one showing.
final bool enabled;
/// The connected server's scope, recorded when the walkthrough is offered.
final String serverScope;
/// Notifies when the connection may have changed; the gate re-reads
/// [connected] on each notification.
final Listenable connection;
/// Whether the server session is connected right now.
final bool Function() connected;
/// The connected server's gateway, used for the empty-server check.
final ApiGateway? gateway;
@override
State<FirstRunWalkthroughGate> createState() =>
_FirstRunWalkthroughGateState();
}
class _FirstRunWalkthroughGateState extends State<FirstRunWalkthroughGate> {
/// The offer is decided for this mount: shown, or nothing left to offer.
bool _decided = false;
/// An offer is in flight.
bool _running = false;
/// A new connection arrived while an offer was in flight.
bool _connectedAgain = false;
late bool _wasConnected;
@override
void initState() {
super.initState();
_wasConnected = widget.connected();
widget.connection.addListener(_onConnectionChanged);
_scheduleIfEnabled();
}
@override
void didUpdateWidget(FirstRunWalkthroughGate oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.connection != widget.connection) {
oldWidget.connection.removeListener(_onConnectionChanged);
widget.connection.addListener(_onConnectionChanged);
}
_scheduleIfEnabled();
}
@override
void dispose() {
widget.connection.removeListener(_onConnectionChanged);
super.dispose();
}
/// Acts only on a disconnected-to-connected transition, so frequent session
/// notifications while connected never repeat the server check.
void _onConnectionChanged() {
final connected = widget.connected();
final became = connected && !_wasConnected;
_wasConnected = connected;
if (!became || _decided) return;
if (_running) {
_connectedAgain = true;
return;
}
_scheduleIfEnabled();
}
void _scheduleIfEnabled() {
if (_decided || _running || !widget.enabled) return;
_running = true;
// A connection can arrive between frames; the post-frame callback needs a
// frame, so request one explicitly.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!_active) {
// Pipelines is hidden (or the gate is gone): release the flag so a
// later enable reschedules the offer through didUpdateWidget.
_running = false;
return;
}
unawaited(_runOffer());
});
WidgetsBinding.instance.ensureVisualUpdate();
}
/// The gate may offer only while mounted and while the Pipelines page is the
/// one showing. Checked after every await and before every show.
bool get _active => mounted && widget.enabled;
Future<void> _runOffer() async {
try {
await _offer();
} finally {
_running = false;
final again = _connectedAgain;
_connectedAgain = false;
if (again && !_decided) _scheduleIfEnabled();
}
}
Future<void> _offer() async {
final seen = await widget.store.isSeen();
if (!_active) return;
if (!seen) {
_decided = true;
await _showIfActive();
return;
}
if (await widget.store.wasOffered(widget.serverScope)) {
if (!_active) return;
_decided = true;
return;
}
// Wait for a connection; the connection listener runs the check again.
if (!widget.connected()) return;
final empty = await serverHasNoWorkYet(widget.gateway);
if (!_active) return;
// Unreadable: stay open so the next connection retries the check.
if (empty == null) return;
_decided = true;
if (!empty) return;
await widget.store.markOffered(widget.serverScope);
await _showIfActive();
}
Future<void> _showIfActive() async {
if (!_active) return;
await _show();
}
Future<void> _show() async {
await showFirstRunWalkthrough(context, onClosed: widget.store.markSeen);
}
@override
Widget build(BuildContext context) => widget.child;
}
@@ -0,0 +1,86 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'walkthrough_steps.dart';
/// The harness page's command: an agent picker and the one command it selects,
/// with a single copy button for that command.
class WalkthroughHarnessCommand extends StatefulWidget {
const WalkthroughHarnessCommand({super.key});
@override
State<WalkthroughHarnessCommand> createState() =>
_WalkthroughHarnessCommandState();
}
class _WalkthroughHarnessCommandState extends State<WalkthroughHarnessCommand> {
String _agent = harnessAgents.first;
bool _copied = false;
Future<void> _copy(String command) async {
try {
await Clipboard.setData(ClipboardData(text: command));
} catch (_) {
// The command stays selectable, so a failed copy never claims success.
return;
}
if (!mounted) return;
setState(() => _copied = true);
}
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final command = harnessSetupCommand(_agent);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text('Agent', style: Theme.of(context).textTheme.labelLarge),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: <Widget>[
for (final agent in harnessAgents)
ChoiceChip(
key: ValueKey<String>('walkthrough.agent.$agent'),
label: Text(agent),
selected: agent == _agent,
onSelected: (_) => setState(() {
_agent = agent;
_copied = false;
}),
),
],
),
const SizedBox(height: 12),
DecoratedBox(
decoration: BoxDecoration(
color: scheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(12),
),
child: Padding(
padding: const EdgeInsets.only(left: 12, right: 4),
child: Row(
children: <Widget>[
Expanded(
child: SelectableText(
command,
key: const ValueKey<String>('walkthrough.command'),
style: Theme.of(context).textTheme.bodyLarge,
),
),
IconButton(
key: const ValueKey<String>('walkthrough.copy'),
tooltip: _copied ? 'Command copied' : 'Copy command',
onPressed: () => _copy(command),
icon: Icon(_copied ? Icons.check : Icons.copy_outlined),
),
],
),
),
),
],
);
}
}
@@ -0,0 +1,79 @@
import 'package:flutter/material.dart';
/// One page of the first-run walkthrough. Pure content: no widgets, so the
/// copy can be checked without pumping a tree.
class WalkthroughStep {
const WalkthroughStep({
required this.icon,
required this.title,
required this.body,
this.points = const <String>[],
this.showsHarnessCommand = false,
});
final IconData icon;
final String title;
final String body;
/// Short labelled facts shown under the body, one per line.
final List<String> points;
/// Whether this page shows the harness setup command picker.
final bool showsHarnessCommand;
}
/// The agents `pipelines harness setup` accepts, in the order they are offered.
const harnessAgents = <String>['claude', 'codex', 'opencode', 'pi'];
/// The command for [agent], exactly as a terminal should run it.
String harnessSetupCommand(String agent) => 'pipelines harness setup $agent';
/// The four walkthrough pages, in order.
const walkthroughSteps = <WalkthroughStep>[
WalkthroughStep(
icon: Icons.hub_outlined,
title: 'Welcome to Pipelines',
body:
'Pipelines runs reusable AI workflows and holds chats with coding '
'agents. Both live on your server, so start by connecting this app '
'to it.',
points: <String>[
'Pipelines: workflows you define once and run again.',
'Chats: conversations with coding agents on the server.',
'Connect: open Settings, then Connection, enter the Server URL and '
'choose Connect.',
],
),
WalkthroughStep(
icon: Icons.build_circle_outlined,
title: 'Set up an agent harness',
body:
'A harness lets Pipelines drive a coding agent. Choose the agent you '
'use, then run its setup command in a terminal.',
showsHarnessCommand: true,
),
WalkthroughStep(
icon: Icons.play_circle_outline,
title: 'Start a run',
body:
'Pipelines shows your workflows. Runs shows every run with its '
'progress and results.',
points: <String>[
'Pipelines tab: open a workflow and fill in its inputs.',
'Runs tab: follow a run as it works, then read what it produced.',
'Choose Run on a workflow to start one.',
],
),
WalkthroughStep(
icon: Icons.forum_outlined,
title: 'Chat with an agent',
body:
'The Chat tab lists your conversations. Open one to read the thread '
'and reply.',
points: <String>[
'Float: pop a chat into its own window while you work elsewhere.',
'Terminal: open a terminal beside the Chat tab for direct commands.',
'New chat starts a conversation with an agent.',
],
),
];
@@ -0,0 +1,118 @@
import 'package:shared_preferences/shared_preferences.dart';
/// The device-level key for "the first-run walkthrough was finished or skipped".
/// It is per device, not per server, so a new server never repeats it.
const String walkthroughSeenKey = 'pipelines.next.firstRunWalkthrough.v1';
/// The key listing the server scopes that were already offered the walkthrough
/// because they had no pipelines, runs or chats yet.
const String walkthroughOfferedKey = 'pipelines.next.walkthroughOffered.v1';
/// The persistence seam for the walkthrough. A store that cannot be read or
/// written reports "seen" and "offered", so an unavailable store never nags.
abstract interface class WalkthroughStore {
Future<bool> isSeen();
Future<void> markSeen();
Future<bool> wasOffered(String serverScope);
Future<void> markOffered(String serverScope);
}
Future<SharedPreferences?> _openPreferences() async {
try {
return await SharedPreferences.getInstance();
} catch (_) {
return null;
}
}
/// `shared_preferences`-backed storage under the `pipelines.next` keys.
///
/// [open] is the seam for an unavailable platform store (tests pass one that
/// yields null); production opens the real preferences.
class SharedPreferencesWalkthroughStore implements WalkthroughStore {
const SharedPreferencesWalkthroughStore({this.open = _openPreferences});
final Future<SharedPreferences?> Function() open;
Future<SharedPreferences?> _preferences() => open();
@override
Future<bool> isSeen() async {
final preferences = await _preferences();
if (preferences == null) return true;
try {
return preferences.getBool(walkthroughSeenKey) ?? false;
} catch (_) {
return true;
}
}
@override
Future<void> markSeen() async {
final preferences = await _preferences();
if (preferences == null) return;
try {
await preferences.setBool(walkthroughSeenKey, true);
} catch (_) {
// Nothing to report: the walkthrough is still dismissed for this run.
}
}
@override
Future<bool> wasOffered(String serverScope) async {
final preferences = await _preferences();
if (preferences == null) return true;
try {
final offered = preferences.getStringList(walkthroughOfferedKey);
return offered?.contains(serverScope) ?? false;
} catch (_) {
return true;
}
}
@override
Future<void> markOffered(String serverScope) async {
final preferences = await _preferences();
if (preferences == null) return;
try {
final offered = <String>{
...?preferences.getStringList(walkthroughOfferedKey),
serverScope,
};
await preferences.setStringList(walkthroughOfferedKey, offered.toList());
} catch (_) {
// A failed write only means the offer may show again later.
}
}
}
/// An in-memory store for tests and previews. It never touches the platform
/// store, so a fixture cannot mark a real device as seen.
class MemoryWalkthroughStore implements WalkthroughStore {
MemoryWalkthroughStore({this.seen = false, Set<String>? offered})
: _offered = {...?offered};
/// Whether the walkthrough is marked seen.
bool seen;
final Set<String> _offered;
/// The server scopes already offered the walkthrough.
Set<String> get offered => Set.unmodifiable(_offered);
@override
Future<bool> isSeen() async => seen;
@override
Future<void> markSeen() async => seen = true;
@override
Future<bool> wasOffered(String serverScope) async =>
_offered.contains(serverScope);
@override
Future<void> markOffered(String serverScope) async =>
_offered.add(serverScope);
}