Merge main into unexpected failure notifications

This commit is contained in:
2026-11-12 11:16:13 +00:00
40 changed files with 2012 additions and 393 deletions
@@ -0,0 +1,11 @@
import '../core/api_gateway.dart';
import '../core/servers/server_scope.dart';
import 'server_endpoint.dart';
/// The scope that isolates a server's pending launch intents. Pipelines and
/// Runs must compute the same scope, or a lost reply could be retried under a
/// different key from the one the Pipelines tab would check.
String pendingRunScope(ApiGateway gateway, ServerEndpoint server) {
final identity = serverIdentity(gateway);
return identity == null ? server.uri?.toString() ?? '' : 'profile:$identity';
}
+3 -3
View File
@@ -41,7 +41,6 @@ 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';
@@ -855,9 +854,10 @@ class _PipelinesAppState extends State<PipelinesApp>
// The terminal button sits on the Chat tab's shell bar on wide layouts;
// a narrow layout has it in the chat's own bar instead. The keyboard
// shortcut still toggles the terminal everywhere.
// The Windows button (shown on every tab while the app has floating
// windows) is the shell's: it lists the manager's windows.
windowManager: _windows,
barActions: [
// Shown on every tab while the app has floating windows.
WindowsMenuButton(manager: _windows),
if (_destinationOf(route.kind) == AppDestination.chat)
?_terminals.barToggle(context),
],
@@ -1,10 +1,10 @@
import 'package:flutter/material.dart';
import '../core/servers/server_scope.dart';
import '../features/pipelines/screen.dart';
import '../ui/adaptive/top_bar_notices.dart';
import 'app_session.dart';
import 'connection_status.dart';
import 'pending_run_scope.dart';
import 'server_endpoint.dart';
/// The Pipelines destination: the read-only browser plus honest status.
@@ -82,9 +82,7 @@ class PipelinesDestination extends StatelessWidget {
Widget _pipelinesScreen() => PipelinesScreen(
gateway: session.gateway,
endpoint: serverIdentity(session.gateway) == null
? server.uri?.toString() ?? ''
: 'profile:${serverIdentity(session.gateway)}',
endpoint: pendingRunScope(session.gateway, server),
legacyEndpoints: legacyPendingEndpoints,
embedded: true,
active: active,
@@ -2,11 +2,13 @@ import 'package:flutter/material.dart';
import '../features/attention/notify/notification_controller.dart';
import '../features/attention/runtime/attention_controller.dart';
import '../features/pipelines/pending_run_store.dart';
import '../features/runs/screen.dart';
import '../features/runs/ui/run_pipeline_link.dart';
import '../ui/adaptive/top_bar_notices.dart';
import 'app_session.dart';
import 'connection_status.dart';
import 'pending_run_scope.dart';
import 'server_endpoint.dart';
/// The Runs destination: the loaded screen plus an honest connection status.
@@ -100,6 +102,9 @@ class RunsDestination extends StatelessWidget {
listRefreshToken: listRefreshToken,
notifications: notifications,
attention: attention,
pendingRunStore: SharedPreferencesPendingRunStore(
pendingRunScope(session.gateway, server),
),
onRunSelected: onRunSelected,
onBack: onBack,
onPipelineFilterChanged: onPipelineFilterChanged,
@@ -147,13 +147,11 @@ class _ChatBackgroundTasksState extends State<ChatBackgroundTasks> {
visualDensity: VisualDensity.compact,
),
onPressed: _open,
// The layers turn only while a task runs; automations stay still.
// A ring around the running count while tasks run; automations stay
// on their static schedule icon.
icon: automationOnly
? const Icon(Icons.schedule, size: 16)
: ChatTaskSpinner(
spinning: count > 0,
child: const Icon(Icons.layers_outlined, size: 16),
),
: ChatTaskSpinner(running: count),
label: caption(),
);
return Padding(
@@ -170,7 +168,7 @@ class _ChatBackgroundTasksState extends State<ChatBackgroundTasks> {
: 'Background work, $label; task list unavailable')
: 'Background work, $label',
child: Tooltip(
message: label,
message: count > 0 ? 'Background tasks ($count running)' : label,
excludeFromSemantics: true,
child: button,
),
@@ -1,71 +1,50 @@
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
/// Turns [child] once every [period] while [spinning]; static otherwise. With
/// reduced motion it never turns. Hidden UI is silenced by TickerMode.
class ChatTaskSpinner extends StatefulWidget {
const ChatTaskSpinner({
super.key,
required this.spinning,
required this.child,
});
/// Background-task glyph for the composer. While [running] is above zero it
/// shows a thin Material progress ring around the count; with reduced motion
/// the ring holds one static quarter segment instead of spinning. With no
/// running task it is the plain layers icon, with no ring. Always [size] square
/// so the button keeps the same dimensions in every state.
class ChatTaskSpinner extends StatelessWidget {
const ChatTaskSpinner({super.key, required this.running, this.size = 16});
final bool spinning;
final Widget child;
final int running;
final double size;
/// One full turn while tasks run.
static const Duration period = Duration(milliseconds: 2500);
/// Fraction of the ring drawn while reduced motion holds it still.
static const double reducedSegment = 0.25;
@override
State<ChatTaskSpinner> createState() => _ChatTaskSpinnerState();
}
class _ChatTaskSpinnerState extends State<ChatTaskSpinner>
with SingleTickerProviderStateMixin {
late final AnimationController _turns = AnimationController(
vsync: this,
duration: ChatTaskSpinner.period,
);
bool _reduced = false;
@override
void initState() {
super.initState();
_sync();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
_sync();
}
@override
void didUpdateWidget(covariant ChatTaskSpinner oldWidget) {
super.didUpdateWidget(oldWidget);
_sync();
}
void _sync() {
if (widget.spinning && !_reduced) {
if (!_turns.isAnimating) _turns.repeat();
} else {
_turns
..stop()
..value = 0;
}
}
@override
void dispose() {
_turns.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => RotationTransition(
key: const Key('chat-background-tasks-spinner'),
turns: _turns,
child: widget.child,
);
Widget build(BuildContext context) {
final theme = Theme.of(context);
final reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
final content = running > 0
? Stack(
alignment: Alignment.center,
children: [
SizedBox.square(
dimension: size,
child: CircularProgressIndicator(
strokeWidth: 2,
color: theme.colorScheme.primary,
value: reduced ? reducedSegment : null,
),
),
FittedBox(
fit: BoxFit.scaleDown,
child: Text(
'$running',
key: const Key('chat-background-tasks-count'),
style: theme.textTheme.labelSmall,
),
),
],
)
: Icon(Icons.layers_outlined, size: size);
return SizedBox.square(
key: const Key('chat-background-tasks-spinner'),
dimension: size,
child: content,
);
}
}
@@ -1,20 +1,36 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../../../core/servers/server_context.dart';
import '../../../ui/adaptive/app_popups.dart';
import '../../../ui/adaptive/segmented_bar.dart';
import '../../../ui/adaptive/segmented_bar_overflow.dart';
import 'chat_bar_tint.dart';
import '../workspace/chat_workspace_pane_scope.dart';
/// Below this width (in text-scaled logical pixels) the selectors leave the
/// bar for its More menu's settings entry, so the title keeps
/// [chatHeaderTitleShare].
const double chatHeaderNarrowWidth = 600;
/// The share of a narrow bar the conversation's title always keeps.
const double chatHeaderTitleShare = 0.6;
/// The open conversation's bar: the app's [SegmentedBar] above the
/// transcript.
///
/// From the leading edge: a round Back (only where the page can go back), a
/// pill with the conversation's title and folder that opens the chat's
/// information, a selector island holding [controls] (model and mode),
/// then the Files action and a native More menu in a separate island.
/// Narrow panes keep the model/mode selectors as compact icons in the same row;
/// their semantic labels and native pickers continue to expose the values.
/// information, a selector island holding [controls] (model, mode and
/// thinking), then the Files action and a native More menu in a separate
/// island.
///
/// A narrow bar ([chatHeaderNarrowWidth]) keeps the title at
/// [chatHeaderTitleShare] of the bar: the [controls] join the More menu as one
/// "Chat settings" entry that opens them in a sheet, and the overflowable
/// actions join it too. A floating chat passes [showTitle] false, since its window bar names
/// the chat.
///
/// A chat with a [chatColor] carries it in the bar: each glass piece is
/// filled with its shade over the raised surface and its labels and icons
@@ -26,6 +42,7 @@ class ChatThreadHeader extends StatelessWidget {
required this.title,
required this.folder,
required this.onInfo,
this.showTitle = true,
this.showBack = false,
this.onBack,
this.controls = const [],
@@ -41,6 +58,10 @@ class ChatThreadHeader extends StatelessWidget {
final String folder;
final VoidCallback onInfo;
/// Whether the title pill (and its folder) shows; false in a floating
/// window, whose own bar names the chat.
final bool showTitle;
/// Whether the bar shows Back at all.
final bool showBack;
@@ -62,21 +83,36 @@ class ChatThreadHeader extends StatelessWidget {
return LayoutBuilder(
builder: (context, constraints) {
final textScale = MediaQuery.textScalerOf(context).scale(14) / 14;
final compact = constraints.maxWidth / textScale < 800;
final scaledWidth = constraints.maxWidth / textScale;
final compact = scaledWidth < 800;
final narrow = scaledWidth < chatHeaderNarrowWidth;
// A narrow bar moves the selectors, and the overflowable actions, into
// its More menu; the others stay in the bar.
final menuActions = [
if (narrow) ...actions.whereType<SegmentedOverflowable>(),
...moreActions.whereType<SegmentedOverflowable>(),
];
final settingsEntry = narrow && controls.isNotEmpty
? SegmentedOverflowEntry(
label: 'Chat settings',
icon: Icons.tune,
onPressed: () => unawaited(_showSettings(context, controls)),
)
: null;
final actionChildren = [
...actions,
for (final action in actions)
if (!narrow || action is! SegmentedOverflowable) action,
for (final action in moreActions)
if (action is! SegmentedOverflowable) action,
if (moreActions.whereType<SegmentedOverflowable>().isNotEmpty)
if (settingsEntry != null || menuActions.isNotEmpty)
SegmentedMoreButton(
entries: [
for (final action
in moreActions.whereType<SegmentedOverflowable>())
action.overflowEntry,
?settingsEntry,
for (final action in menuActions) action.overflowEntry,
],
),
];
final Widget bar = SegmentedBar(
final bar = SegmentedBar(
pillColor: tint?.fill,
foregroundColor: tint?.foreground,
automaticallyImplyLeading: false,
@@ -88,16 +124,17 @@ class ChatThreadHeader extends StatelessWidget {
onPressed: onBack,
)
: null,
title: title.isEmpty ? 'Chat' : title,
titleLeading: identity,
subtitle: ServerContext.metadata(context, folder),
title: !showTitle ? '' : (title.isEmpty ? 'Chat' : title),
titleLeading: showTitle ? identity : null,
subtitle: showTitle ? ServerContext.metadata(context, folder) : null,
subtitleIcon: Icons.folder_outlined,
onTitlePressed: onInfo,
onTitlePressed: showTitle ? onInfo : null,
titleSemanticLabel: 'Chat information',
titleKey: const Key('chat-info'),
separateActionIslands: true,
titleShare: narrow && showTitle ? chatHeaderTitleShare : null,
actions: [
if (controls.isNotEmpty)
if (controls.isNotEmpty && !narrow)
ChatWorkspacePaneActionBar(
child: _ControlIsland(
key: const Key('chat-model-permission-island'),
@@ -105,7 +142,7 @@ class ChatThreadHeader extends StatelessWidget {
children: controls,
),
),
if (actions.isNotEmpty || moreActions.isNotEmpty)
if (actionChildren.isNotEmpty)
ChatWorkspacePaneActionBar(
child: Row(
key: const Key('chat-actions-island'),
@@ -136,6 +173,24 @@ class ChatThreadHeader extends StatelessWidget {
}
}
/// A narrow bar's selectors (model, mode and thinking), each with its label,
/// in a sheet opened from the More menu.
Future<void> _showSettings(BuildContext context, List<Widget> controls) =>
showAppChoiceMenu<void>(
context,
semanticLabel: 'Chat settings',
builder: (_) => SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: controls,
),
),
),
);
/// Related selectors share the available width. Each remains a real control;
/// they never migrate into the unrelated actions menu.
class _ControlIsland extends StatelessWidget {
@@ -1428,15 +1428,23 @@ class _ChatThreadViewState extends State<ChatThreadView> {
? ModalRoute.of(context)?.impliesAppBarDismissal ?? false
: true);
final answeredBy = latestReplyModel(_controller.messages);
return _chrome.widgetFor('header', answeredBy, [
widget,
inShellBar,
canGoBack,
// The thinking control says when a turn is running.
_controller.running,
// The More menu offers Dismiss all finished commands only with one.
_shellRuns.finishedIds.isNotEmpty,
], () => _buildHeader(session, inShellBar, canGoBack, answeredBy));
// A floating window's own bar names the chat, so the header omits it.
final inWindow = WindowScope.maybeOf(context) != null;
return _chrome.widgetFor(
'header',
answeredBy,
[
widget,
inShellBar,
canGoBack,
inWindow,
// The thinking control says when a turn is running.
_controller.running,
// The More menu offers Dismiss all finished commands only with one.
_shellRuns.finishedIds.isNotEmpty,
],
() => _buildHeader(session, inShellBar, canGoBack, answeredBy, inWindow),
);
}
Widget _buildHeader(
@@ -1444,6 +1452,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
bool inShellBar,
bool canGoBack,
String answeredBy,
bool inWindow,
) {
final hasModel =
session != null && supportsChatModels('${session['backend'] ?? ''}');
@@ -1466,6 +1475,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
? null
: ChatSessionAvatar(session: session, selected: true),
onInfo: _openInfo,
showTitle: !inWindow,
showBack: canGoBack,
// A pushed page keeps the platform's stock Back (pop this route); a
// standalone conversation calls its owner.
@@ -1518,6 +1528,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
),
],
controls: [
// Labelled, so a narrow bar's settings sheet shows their names.
if (hasModel)
ChatModelControl(
key: ValueKey<String>('chat-model-${widget.sessionId}'),
@@ -1526,6 +1537,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
session: session,
onChanged: widget.onModelChanged,
answeredBy: answeredBy,
showLabel: true,
),
if (hasMode) _modeControl(),
// Only a model with levels gets the control (and its pill).
@@ -1537,6 +1549,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
session: session,
running: _controller.running,
onChanged: widget.onEffortChanged,
showLabel: true,
),
],
);
@@ -1551,6 +1564,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
mode: '${widget.session?['mode'] ?? ''}'.trim(),
modeName: '${widget.session?['mode_name'] ?? ''}'.trim(),
onChanged: widget.onModeChanged,
showLabel: true,
);
/// Stops the running turn, as the composer's `/stop` does.
@@ -0,0 +1,42 @@
import 'package:flutter/material.dart';
import '../../../ui/motion/motion.dart';
/// The opacity of the surface scrim over an inactive split pane. The pane's
/// transcript and bars keep reading through it at about two thirds emphasis.
const double chatPaneDimOpacity = 0.35;
/// Covers a pane that is not the active one with the theme's surface colour,
/// so the active pane reads as the one in focus. The scrim ignores pointers:
/// taps reach the pane's content, and its activation listener still runs.
/// Reduced motion switches the scrim at once; otherwise it fades briefly.
class ChatPaneDim extends StatelessWidget {
const ChatPaneDim({super.key, required this.dimmed, required this.child});
final bool dimmed;
final Widget child;
@override
Widget build(BuildContext context) {
final surface = Theme.of(context).colorScheme.surface;
return Stack(
fit: StackFit.passthrough,
children: [
child,
Positioned.fill(
child: IgnorePointer(
child: AnimatedContainer(
key: const ValueKey('chat-pane-dim-scrim'),
duration: Motion.of(context, Motion.standard),
curve: Motion.curve,
// The clear end keeps the surface hue, so the fade never greys.
color: dimmed
? surface.withValues(alpha: chatPaneDimOpacity)
: surface.withValues(alpha: 0),
),
),
),
],
);
}
}
@@ -15,6 +15,7 @@ import 'chat_pane_move_motion.dart';
import 'chat_pane_move_shortcuts.dart';
import 'chat_pane_switch_motion.dart';
import 'chat_pane_backdrop.dart';
import 'chat_pane_dim.dart';
import 'chat_workspace_pane_scope.dart';
import 'chat_workspace_surface.dart';
import '../../../ui/input/keyboard_owner.dart';
@@ -509,8 +510,11 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
onPreferredWidthChanged: (width) =>
_reportPaneExtraWidth(pane.id, width),
child: Builder(
builder: (paneContext) =>
widget.paneBuilder(paneContext, pane, active),
builder: (paneContext) => ChatPaneDim(
// A single pane is always the active one, so it never dims.
dimmed: widget.controller.paneCount > 1 && !active,
child: widget.paneBuilder(paneContext, pane, active),
),
),
),
),
@@ -1,21 +1,16 @@
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../core/transport/connection_state.dart';
import '../../runs/data/runs_repository.dart';
import '../../../ui/adaptive/segmented_bar_overflow.dart';
import '../pipeline_models.dart';
import '../pipelines_controller.dart';
import '../run_pipeline_intent.dart';
import '../widgets/pipeline_bar_buttons.dart';
import 'run_pipeline_dialog.dart';
import 'run_pipeline_flow.dart';
import 'run_pipeline_wording.dart';
/// The pipeline detail's Run action.
///
/// Nothing is requested until the dialog's confirm. A confirmed attempt sends
/// the web's exact `run_pipeline` body against the pinned resolved version; a
/// lost reply keeps the intent so the next deliberate press checks by the same
/// request key before resending. Only the id the server names is opened.
const _runIcon = Icons.play_arrow_rounded;
/// The pipeline detail's Run action: a labelled button that opens the shared
/// start flow ([openRunPipelineFlow]).
class RunPipelineAction extends StatefulWidget {
const RunPipelineAction({
super.key,
@@ -26,8 +21,8 @@ class RunPipelineAction extends StatefulWidget {
this.inBar = false,
});
/// The compact icon-and-word button of a top bar's actions pill instead
/// of an inline button.
/// The compact button of a top bar's actions pill instead of an inline
/// button. A narrow bar moves it into its More menu, labelled.
final bool inBar;
final PipelinesController controller;
@@ -45,143 +40,38 @@ class RunPipelineAction extends StatefulWidget {
class _RunPipelineActionState extends State<RunPipelineAction> {
bool _dialogOpen = false;
int get _pipelineId => widget.detail.id;
int get _version => widget.detail.resolvedVersion;
Future<void> _open() async {
if (_dialogOpen) return;
_dialogOpen = true;
try {
final pending = await widget.controller.loadPendingRun(
_pipelineId,
_version,
);
if (!mounted) return;
await showRunPipelineDialog(
await openRunPipelineFlow(
context: context,
controller: widget.controller,
detail: widget.detail,
gateway: widget.gateway,
pending: pending,
onSubmit: _submit,
onPendingChanged: (intent) {
if (intent == null) {
widget.controller.clearPendingRun(_pipelineId, _version);
} else {
widget.controller.rememberPendingRun(intent);
}
},
onAccepted: _accepted,
onRunStarted: widget.onRunStarted,
);
} finally {
_dialogOpen = false;
}
}
void _accepted(JsonMap run) {
final id = runPipelineRunId(run);
if (id == null) return;
widget.controller.clearPendingRun(_pipelineId, _version);
widget.onRunStarted?.call(id);
}
Future<RunPipelineOutcome> _submit(RunPipelineIntent intent) async {
final repository = RunsRepository(widget.gateway);
final pending = widget.controller.pendingRunFor(
intent.pipelineId,
intent.version,
);
if (pending?.requestKey == intent.requestKey) {
// A previous send may have been admitted even though its reply was lost.
// Check before resending the same key; the server dedupes either way.
try {
final existing = await repository.runByRequestKey(intent.requestKey);
if (existing != null) return _accept(existing);
} catch (error) {
widget.controller.rememberPendingRun(intent);
return RunPipelineRefused(
'${describeRunPipelineError(error)}$runPipelineUnknownSuffix',
admissionUnknown: true,
);
}
}
try {
final run = await repository.startRun(
pipelineId: intent.pipelineId,
version: intent.version,
prompt: intent.prompt,
workspace: intent.workspace,
requestKey: intent.requestKey,
notifyMode: intent.notifyMode.wireValue,
outputFormat: intent.outputFormat.wireValue,
);
final accepted = _accept(run);
if (accepted is RunPipelineAccepted) return accepted;
// A reply without a usable run id is not navigable: read the admitted run
// by key rather than inventing an id or starting another run.
return _refuse(repository, intent, 'The server returned no run id.');
} on ProtocolError catch (error) {
return _refuse(repository, intent, describeRunPipelineError(error));
} on RunsRepositoryException catch (error) {
return _refuse(repository, intent, describeRunPipelineError(error));
} catch (error) {
widget.controller.rememberPendingRun(intent);
return RunPipelineRefused(
'${describeRunPipelineError(error)}$runPipelineUnknownSuffix',
admissionUnknown: true,
);
}
}
/// A reply is only accepted when it names a usable run id.
RunPipelineOutcome _accept(JsonMap run) {
if (runPipelineRunId(run) == null) {
return const RunPipelineRefused(
'The server returned no run id.',
admissionUnknown: false,
);
}
widget.controller.clearPendingRun(widget.detail.id, _version);
return RunPipelineAccepted(run);
}
/// A confirmed refusal: prove by key that no run was admitted before letting
/// the operator correct the fields and try with a fresh key.
Future<RunPipelineOutcome> _refuse(
RunsRepository repository,
RunPipelineIntent intent,
String message,
) async {
try {
final existing = await repository.runByRequestKey(intent.requestKey);
if (existing != null) return _accept(existing);
widget.controller.clearPendingRun(intent.pipelineId, intent.version);
return RunPipelineRefused(message, admissionUnknown: false);
} catch (_) {
// Admission cannot be proven either way: keep the intent immutable.
widget.controller.rememberPendingRun(intent);
return RunPipelineRefused(
'$message$runPipelineUnknownSuffix',
admissionUnknown: true,
);
}
}
@override
Widget build(BuildContext context) {
final label = const Text(runPipelineActionLabel);
if (widget.inBar) {
return pipelineBarIconButton(
context,
key: runPipelineActionKey,
label: 'Run ${widget.detail.displayName}',
icon: Icons.play_arrow_rounded,
onPressed: _open,
);
}
return FilledButton(
final button = FilledButton.icon(
key: runPipelineActionKey,
onPressed: _open,
child: label,
icon: const Icon(_runIcon),
label: const Text(runPipelineActionLabel),
);
if (!widget.inBar) return button;
return SegmentedOverflowAction(
overflowEntry: SegmentedOverflowEntry(
label: runPipelineActionLabel,
icon: _runIcon,
onPressed: _open,
),
child: button,
);
}
}
@@ -0,0 +1,155 @@
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../core/transport/connection_state.dart';
import '../../runs/data/runs_repository.dart';
import '../pipeline_models.dart';
import '../pipelines_controller.dart';
import '../run_pipeline_intent.dart';
import 'run_pipeline_dialog.dart';
import 'run_pipeline_wording.dart';
/// The one Run start flow, shared by a pipeline's Run action and the Runs
/// tab's New run picker.
///
/// Nothing is requested until the dialog's confirm. A confirmed attempt sends
/// the web's exact `run_pipeline` body against the pinned resolved version; a
/// lost reply keeps the intent so the next deliberate press checks by the same
/// request key before resending. Only the id the server names is reported.
Future<void> openRunPipelineFlow({
required BuildContext context,
required PipelinesController controller,
required PipelineDetail detail,
required ApiGateway gateway,
ValueChanged<int>? onRunStarted,
}) async {
final pipelineId = detail.id;
final version = detail.resolvedVersion;
final pending = await controller.loadPendingRun(pipelineId, version);
if (!context.mounted) return;
await showRunPipelineDialog(
context: context,
detail: detail,
gateway: gateway,
pending: pending,
onSubmit: (intent) => _submit(controller, gateway, intent),
onPendingChanged: (intent) {
if (intent == null) {
controller.clearPendingRun(pipelineId, version);
} else {
controller.rememberPendingRun(intent);
}
},
onAccepted: (run) {
final id = runPipelineRunId(run);
if (id == null) return;
controller.clearPendingRun(pipelineId, version);
onRunStarted?.call(id);
},
);
}
Future<RunPipelineOutcome> _submit(
PipelinesController controller,
ApiGateway gateway,
RunPipelineIntent intent,
) async {
final repository = RunsRepository(gateway);
final pending = controller.pendingRunFor(intent.pipelineId, intent.version);
if (pending?.requestKey == intent.requestKey) {
// A previous send may have been admitted even though its reply was lost.
// Check before resending the same key; the server dedupes either way.
try {
final existing = await repository.runByRequestKey(intent.requestKey);
if (existing != null) {
return _accept(controller, intent, existing);
}
} catch (error) {
controller.rememberPendingRun(intent);
return RunPipelineRefused(
'${describeRunPipelineError(error)}$runPipelineUnknownSuffix',
admissionUnknown: true,
);
}
}
try {
final run = await repository.startRun(
pipelineId: intent.pipelineId,
version: intent.version,
prompt: intent.prompt,
workspace: intent.workspace,
requestKey: intent.requestKey,
notifyMode: intent.notifyMode.wireValue,
outputFormat: intent.outputFormat.wireValue,
);
final accepted = _accept(controller, intent, run);
if (accepted is RunPipelineAccepted) return accepted;
// A reply without a usable run id is not navigable: read the admitted run
// by key rather than inventing an id or starting another run.
return _refuse(
controller,
repository,
intent,
'The server returned no run id.',
);
} on ProtocolError catch (error) {
return _refuse(
controller,
repository,
intent,
describeRunPipelineError(error),
);
} on RunsRepositoryException catch (error) {
return _refuse(
controller,
repository,
intent,
describeRunPipelineError(error),
);
} catch (error) {
controller.rememberPendingRun(intent);
return RunPipelineRefused(
'${describeRunPipelineError(error)}$runPipelineUnknownSuffix',
admissionUnknown: true,
);
}
}
/// A reply is only accepted when it names a usable run id.
RunPipelineOutcome _accept(
PipelinesController controller,
RunPipelineIntent intent,
JsonMap run,
) {
if (runPipelineRunId(run) == null) {
return const RunPipelineRefused(
'The server returned no run id.',
admissionUnknown: false,
);
}
controller.clearPendingRun(intent.pipelineId, intent.version);
return RunPipelineAccepted(run);
}
/// A confirmed refusal: prove by key that no run was admitted before letting
/// the operator correct the fields and try with a fresh key.
Future<RunPipelineOutcome> _refuse(
PipelinesController controller,
RunsRepository repository,
RunPipelineIntent intent,
String message,
) async {
try {
final existing = await repository.runByRequestKey(intent.requestKey);
if (existing != null) return _accept(controller, intent, existing);
controller.clearPendingRun(intent.pipelineId, intent.version);
return RunPipelineRefused(message, admissionUnknown: false);
} catch (_) {
// Admission cannot be proven either way: keep the intent immutable.
controller.rememberPendingRun(intent);
return RunPipelineRefused(
'$message$runPipelineUnknownSuffix',
admissionUnknown: true,
);
}
}
+88 -13
View File
@@ -11,10 +11,15 @@ import '../attention/notify/notification_controller.dart';
import '../../ui/layout/content_width.dart';
import '../attention/runtime/attention_controller.dart';
import '../attention/runtime/attention_store.dart';
import '../pipelines/pending_run_store.dart';
import '../pipelines/pipeline_repository.dart';
import '../pipelines/pipelines_controller.dart';
import 'actions/decision_action.dart';
import 'data/runs_repository.dart';
import 'data/runs_sort_store.dart';
import 'domain/run_decisions.dart';
import 'ui/new_run_button.dart';
import 'ui/new_run_flow.dart';
import 'ui/run_pipeline_link.dart';
import 'ui/run_detail_view.dart';
import 'ui/run_search_selection.dart';
@@ -47,6 +52,7 @@ class RunsScreen extends StatefulWidget {
this.notifications,
this.attention,
this.sortStore = const SharedPreferencesRunsSortStore(),
this.pendingRunStore = const SharedPreferencesPendingRunStore(''),
});
final ApiGateway gateway;
@@ -94,12 +100,24 @@ class RunsScreen extends StatefulWidget {
/// Where the list's sort choice persists; tests inject a memory store.
final RunsSortStore sortStore;
/// Where a New run's pending launch intent persists, under the same endpoint
/// scope the Pipelines tab uses. Tests inject a memory store.
final PendingRunStore pendingRunStore;
@override
State<RunsScreen> createState() => _RunsScreenState();
}
/// The vertical band the New run button occupies over the list's bottom edge:
/// its margin, the extended button's height and its margin again.
const double _newRunBand = 88;
class _RunsScreenState extends State<RunsScreen> {
late final RunsController controller;
/// Starts a run from the New run picker. Its state is only the pending
/// launch intent; the pipeline itself is read when the operator picks one.
late final PipelinesController _launches;
num? _shownRunId;
int? _reportedPipelineId;
bool _applyingRoutePipeline = false;
@@ -118,6 +136,10 @@ class _RunsScreenState extends State<RunsScreen> {
RunsRepository(widget.gateway),
sortStore: widget.sortStore,
);
_launches = PipelinesController(
PipelinesRepository(widget.gateway),
pendingRunStore: widget.pendingRunStore,
);
// A deleted open run closes its detail; the route returns to the list.
controller.onOpenRunRemoved = () =>
widget.onBack?.call(controller.pipelineId);
@@ -234,6 +256,23 @@ class _RunsScreenState extends State<RunsScreen> {
widget.onBack?.call(controller.pipelineId);
}
/// The New run picker, then the same start flow a pipeline's Run opens.
void _startNewRun() => unawaited(
startNewRunFlow(
context: context,
controller: _launches,
gateway: widget.gateway,
onRunStarted: _newRunStarted,
),
);
/// An accepted launch re-reads the list so its row appears, then opens the
/// run the same way a row tap does.
void _newRunStarted(int id) {
unawaited(controller.resync());
_select(id);
}
@override
void dispose() {
controller.removeListener(_selectionChanged);
@@ -241,6 +280,7 @@ class _RunsScreenState extends State<RunsScreen> {
controller.removeListener(_detailChanged);
_page.dispose();
controller.dispose();
_launches.dispose();
super.dispose();
}
@@ -285,20 +325,55 @@ class _RunsScreenState extends State<RunsScreen> {
onClosed: _back,
builder: (context) => _detail(() => Navigator.of(context).maybePop()),
);
final list = AnimatedBuilder(
animation: controller,
builder: (context, _) => ContentWidth(
child: RunsList(
active: narrow ? !selected : true,
controller: controller,
onSelected: _select,
syncToken: widget.syncToken,
attentionStore: widget.attentionStore,
attentionNow: widget.attentionNow,
notifications: widget.notifications,
attention: widget.attention,
// The New run button floats over the list's bottom-right corner while the
// list is the visible view. The list reserves the button's band in its
// bottom padding, so its last row rests above the button, and the overlay
// lifts clear of the shell's bar like the list's own clearance does.
final list = Stack(
fit: StackFit.expand,
children: [
AnimatedBuilder(
animation: controller,
builder: (context, _) {
final showsButton = !(narrow && selected);
final media = MediaQuery.of(context);
return MediaQuery(
data: media.copyWith(
padding: media.padding.copyWith(
bottom:
media.padding.bottom + (showsButton ? _newRunBand : 0),
),
),
child: ContentWidth(
child: RunsList(
active: narrow ? !selected : true,
controller: controller,
onSelected: _select,
syncToken: widget.syncToken,
attentionStore: widget.attentionStore,
attentionNow: widget.attentionNow,
notifications: widget.notifications,
attention: widget.attention,
),
),
);
},
),
),
AnimatedBuilder(
animation: controller,
builder: (context, _) => narrow && selected
? const SizedBox.shrink()
: Positioned(
left: 16,
right: 16,
bottom: 16 + MediaQuery.paddingOf(context).bottom,
child: Align(
alignment: AlignmentDirectional.bottomEnd,
child: NewRunButton(onPressed: _startNewRun),
),
),
),
],
);
if (narrow) return list;
return ListDetailPanes(
@@ -0,0 +1,17 @@
import 'package:flutter/material.dart';
/// The Runs tab's New run action: an extended floating button that opens the
/// pipeline picker. It is labelled, so it needs no tooltip of its own.
class NewRunButton extends StatelessWidget {
const NewRunButton({super.key, required this.onPressed});
final VoidCallback onPressed;
@override
Widget build(BuildContext context) => FloatingActionButton.extended(
key: const Key('runs-new-run'),
onPressed: onPressed,
icon: const Icon(Icons.add),
label: const Text('New run'),
);
}
@@ -0,0 +1,40 @@
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../pipelines/pipeline_models.dart';
import '../../pipelines/pipeline_repository.dart';
import '../../pipelines/pipelines_controller.dart';
import '../../pipelines/ui/run_pipeline_flow.dart';
import '../../pipelines/ui/run_pipeline_wording.dart';
import 'new_run_picker.dart';
/// The Runs tab's New run: pick an active pipeline, read its latest version,
/// then the same start flow a pipeline's Run action opens.
Future<void> startNewRunFlow({
required BuildContext context,
required PipelinesController controller,
required ApiGateway gateway,
ValueChanged<int>? onRunStarted,
}) async {
final repository = PipelinesRepository(gateway);
final pipelineId = await pickPipelineForNewRun(context, repository);
if (pipelineId == null || !context.mounted) return;
final PipelineDetail detail;
try {
detail = await repository.getPipeline(pipelineId, 0);
} catch (error) {
if (!context.mounted) return;
ScaffoldMessenger.maybeOf(
context,
)?.showSnackBar(SnackBar(content: Text(describeRunPipelineError(error))));
return;
}
if (!context.mounted) return;
await openRunPipelineFlow(
context: context,
controller: controller,
detail: detail,
gateway: gateway,
onRunStarted: onRunStarted,
);
}
@@ -0,0 +1,143 @@
import 'package:flutter/material.dart';
import '../../pipelines/pipeline_models.dart';
import '../../pipelines/pipeline_repository.dart';
import '../../pipelines/ui/run_pipeline_wording.dart';
/// Whether an active pipeline matches a picker search by name. An empty query
/// matches every pipeline.
bool pipelineMatchesQuery(PipelineSummary pipeline, String query) {
final needle = query.trim().toLowerCase();
if (needle.isEmpty) return true;
return pipeline.displayName.toLowerCase().contains(needle);
}
/// Opens the searchable list of active pipelines. Resolves to the chosen
/// pipeline's id, or null when the picker is dismissed.
Future<int?> pickPipelineForNewRun(
BuildContext context,
PipelinesRepository repository,
) => showDialog<int>(
context: context,
builder: (_) => _PipelinePicker(repository: repository),
);
class _PipelinePicker extends StatefulWidget {
const _PipelinePicker({required this.repository});
final PipelinesRepository repository;
@override
State<_PipelinePicker> createState() => _PipelinePickerState();
}
class _PipelinePickerState extends State<_PipelinePicker> {
late Future<List<PipelineSummary>> _pipelines = _loadActive();
String _query = '';
/// Archived pipelines cannot run, so the picker offers only active ones.
Future<List<PipelineSummary>> _loadActive() async {
final all = await widget.repository.listPipelines();
return all.where((pipeline) => !pipeline.archived).toList(growable: false);
}
void _retry() => setState(() => _pipelines = _loadActive());
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Dialog(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 480, maxHeight: 560),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('Choose a pipeline', style: theme.textTheme.titleLarge),
const Padding(padding: EdgeInsets.only(top: 12)),
TextField(
key: const Key('new-run-search'),
decoration: const InputDecoration(
hintText: 'Search pipelines',
prefixIcon: Icon(Icons.search),
),
onChanged: (value) => setState(() => _query = value),
),
const Padding(padding: EdgeInsets.only(top: 8)),
Flexible(child: _body(context)),
],
),
),
),
);
}
Widget _body(BuildContext context) {
return FutureBuilder<List<PipelineSummary>>(
future: _pipelines,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Padding(
padding: EdgeInsets.all(24),
child: Center(child: CircularProgressIndicator()),
);
}
if (snapshot.hasError) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
describeRunPipelineError(snapshot.error!),
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
TextButton(onPressed: _retry, child: const Text('Retry')),
],
);
}
final active = snapshot.data ?? const <PipelineSummary>[];
if (active.isEmpty) {
return const _Notice('No active pipelines.');
}
final matches = active
.where((pipeline) => pipelineMatchesQuery(pipeline, _query))
.toList(growable: false);
if (matches.isEmpty) {
return const _Notice('No pipeline matches the search.');
}
return ListView(
shrinkWrap: true,
children: [
for (final pipeline in matches)
ListTile(
key: ValueKey<String>('new-run-pipeline-${pipeline.id}'),
title: Text(
pipeline.displayName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
subtitle: Text(
'v${pipeline.version} · ${pipeline.stages} stages',
),
onTap: () => Navigator.of(context).pop(pipeline.id),
),
],
);
},
);
}
}
class _Notice extends StatelessWidget {
const _Notice(this.message);
final String message;
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.all(16),
child: Text(message, style: TextStyle(color: Theme.of(context).hintColor)),
);
}
@@ -61,7 +61,7 @@ const walkthroughSteps = <WalkthroughStep>[
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.',
'Press Run on a workflow, or New run on the Runs tab, to start one.',
],
),
WalkthroughStep(
+18 -1
View File
@@ -17,6 +17,8 @@ import 'shell_list_shortcuts.dart';
import 'shell_runs_pipelines_shortcut.dart';
import 'shell_search_shortcut_labels.dart';
import 'tab_history.dart';
import 'windows/window_manager.dart';
import 'windows/windows_menu_button.dart';
import '../ui/input/keyboard_owner.dart';
class AdaptiveShell extends StatefulWidget {
@@ -33,12 +35,18 @@ class AdaptiveShell extends StatefulWidget {
this.runningRunCount,
this.listPaneWidthStore = const SharedPreferencesListPaneWidthStore(),
this.barActions = const [],
this.windowManager,
});
/// Actions every destination's bar ends with (the Terminal toggle), after
/// the screen's own or Search.
final List<Widget> barActions;
/// The floating windows the bar's Windows button lists. The button is shown
/// only while one is open, so the bar draws no empty action island; null
/// (plain shells) shows none.
final WindowManager? windowManager;
/// Where each destination's dragged list-pane width is kept on this device.
final ListPaneWidthStore listPaneWidthStore;
@@ -268,7 +276,11 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
SegmentedBar currentBar() =>
_segmentedBar(_bar.specFor(_selected), details.label, page: page);
final topBar = _ListPaneBar(
listenable: Listenable.merge([_bar.bar, _paneWidths]),
listenable: Listenable.merge([
_bar.bar,
_paneWidths,
?widget.windowManager,
]),
initial: currentBar(),
split: () => _bar.split(_selected),
preferredWidth: () => _paneWidths.widthFor(_selected.name),
@@ -472,6 +484,7 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
spec?.onBack ?? (page && _settingsPushed ? _closePage : null);
final published = spec?.actions ?? const <Widget>[];
final onSearch = widget.onSearch;
final windows = widget.windowManager;
return SegmentedBar(
automaticallyImplyLeading: false,
leading: onBack == null
@@ -506,6 +519,10 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
tooltip: 'Search (${shellSearchShortcutLabels().join(', ')})',
icon: const Icon(Icons.search),
),
// The Windows button leads the shell's own actions, only while a
// floating window is listed; an empty button would draw an empty island.
if (windows != null && WindowsMenuButton.hasWindows(windows))
WindowsMenuButton(manager: windows),
...widget.barActions,
],
);
+36 -27
View File
@@ -56,35 +56,44 @@ class ShellNavigationRail extends StatelessWidget {
@override
Widget build(BuildContext context) {
final index = shellTabDestinations.indexOf(selected);
return Padding(
padding: padding,
child: SizedBox(
width: kNavigationRailWidth,
child: NavigationRail(
key: const ValueKey('shell.navigation-rail'),
minWidth: kNavigationRailWidth,
labelType: NavigationRailLabelType.all,
selectedIndex: index < 0 ? null : index,
onDestinationSelected: (value) =>
onSelected(shellTabDestinations[value]),
destinations: [
for (final destination in shellTabDestinations)
NavigationRailDestination(
icon: KeyedSubtree(
key: ValueKey('shell.destination.${destination.name}'),
// The bar it replaces named each tab in a tooltip too.
child: Tooltip(
message: destinationDetails(destination).label,
child: icon(destination),
final surface = Theme.of(context).colorScheme.surface;
// The surface runs under the top inset too: the padding only moves the
// rail's content below the system's top, so no unpainted strip shows above
// the rail's background.
return ColoredBox(
key: const ValueKey('shell.navigation-rail.surface'),
color: surface,
child: Padding(
padding: padding,
child: SizedBox(
width: kNavigationRailWidth,
child: NavigationRail(
key: const ValueKey('shell.navigation-rail'),
backgroundColor: surface,
minWidth: kNavigationRailWidth,
labelType: NavigationRailLabelType.all,
selectedIndex: index < 0 ? null : index,
onDestinationSelected: (value) =>
onSelected(shellTabDestinations[value]),
destinations: [
for (final destination in shellTabDestinations)
NavigationRailDestination(
icon: KeyedSubtree(
key: ValueKey('shell.destination.${destination.name}'),
// The bar it replaces named each tab in a tooltip too.
child: Tooltip(
message: destinationDetails(destination).label,
child: icon(destination),
),
),
label: Text(destinationDetails(destination).label),
),
label: Text(destinationDetails(destination).label),
),
],
trailingAtBottom: true,
trailing: _SettingsRailItem(
selected: selected == AppDestination.settings,
onTap: () => onSelected(AppDestination.settings),
],
trailingAtBottom: true,
trailing: _SettingsRailItem(
selected: selected == AppDestination.settings,
onTap: () => onSelected(AppDestination.settings),
),
),
),
),
@@ -12,6 +12,11 @@ class WindowsMenuButton extends StatelessWidget {
final WindowManager manager;
/// Whether [manager] has a window to list: the shell bar keeps the button
/// out of its actions otherwise, so no empty action island is drawn.
static bool hasWindows(WindowManager manager) =>
manager.windows.any((w) => manager.kinds[w.kind] != null);
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: Listenable.merge([
+12 -3
View File
@@ -69,8 +69,14 @@ class SegmentedBar extends StatefulWidget implements PreferredSizeWidget {
this.foregroundColor,
this.bottomPadding = 8,
this.backdrop,
this.titleShare,
});
/// The share of the bar the title always keeps beside the actions, when it
/// must hold more than the default (a long conversation name in a narrow
/// bar). Null keeps the default shares.
final double? titleShare;
/// The title; empty shows no title pill unless there is a [subtitle].
final String title;
@@ -390,8 +396,11 @@ class _SegmentedBarState extends State<SegmentedBar> {
// width (a destination's name) up to [SegmentedBar.maxTitleShare];
// actions that do not fit beside it move into the More menu.
final width = constraints.maxWidth;
final titleShare = widget.titleShare;
final titleMinimum = titleWidget != null || !showTitle
? width * SegmentedBar.minTitleShare
: titleShare != null
? width * titleShare
: math.max(
width * SegmentedBar.minTitleShare,
math.min(
@@ -405,9 +414,9 @@ class _SegmentedBarState extends State<SegmentedBar> {
width * SegmentedBar.maxTitleShare,
),
);
final minimumTitleShare = widget.separateActionIslands
? .10
: SegmentedBar.minTitleShare;
final minimumTitleShare =
titleShare ??
(widget.separateActionIslands ? .10 : SegmentedBar.minTitleShare);
final besideTitle =
width - (leading == null ? 0 : segmentedPieceHeight() + 8) - 8;
// Actions that cannot move (a model picker) may take the room down