Merge branch 'main' into worktree-agent-a7c8c1a6937e97e84
Resolve chat_room.go: keep main's bounded chatSub queue (ready channel, no ch) in attachSub; the subscribe live-turn marker is still queued at attach under h.mu through enqueueChatLocked, and an existing subscriber whose queue is full is overflowed (resync) after the hub lock is released. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -53,6 +53,7 @@ class AppSession extends ChangeNotifier {
|
||||
bool _subscribed = false, _disposed = false;
|
||||
bool _everConnected;
|
||||
int _connectionEpoch = 0;
|
||||
int _runsResyncs = 0;
|
||||
RunSubscriptionState _subscription = RunSubscriptionState.pending;
|
||||
String _subscriptionError = '';
|
||||
String? _subscribeRequest;
|
||||
@@ -79,6 +80,11 @@ class AppSession extends ChangeNotifier {
|
||||
/// detail without remounting the screen or losing its selection.
|
||||
int get connectionEpoch => _connectionEpoch;
|
||||
|
||||
/// Advances on every connected transition and whenever the server detached
|
||||
/// this connection's run watch for falling behind (`runs_resync`). The Runs
|
||||
/// screen keys its re-read with this: frames were discarded either way.
|
||||
int get runsEpoch => _connectionEpoch + _runsResyncs;
|
||||
|
||||
/// Connects the shared socket. A missing endpoint is a configuration state,
|
||||
/// so this is a no-op rather than a guessed endpoint.
|
||||
Future<void> start() async {
|
||||
@@ -140,6 +146,13 @@ class AppSession extends ChangeNotifier {
|
||||
|
||||
void _onFrame(JsonMap frame) {
|
||||
if (_disposed) return;
|
||||
if (frame['type'] == 'runs_resync') {
|
||||
// The server dropped this watch because the connection fell behind and
|
||||
// discarded the frames it still held: watch again and re-read the runs.
|
||||
_runsResyncs++;
|
||||
resubscribe();
|
||||
return;
|
||||
}
|
||||
final id = frame['id'];
|
||||
if (id is! String || id != _subscribeRequest) return;
|
||||
switch (frame['type']) {
|
||||
|
||||
@@ -15,6 +15,7 @@ import '../core/servers/server_scope.dart';
|
||||
import '../core/transport/pipelines_client.dart';
|
||||
import '../shell/adaptive_shell.dart';
|
||||
import '../shell/destination.dart';
|
||||
import '../shell/shell_chat_actions_shortcut.dart';
|
||||
import '../features/attention/notify/notification_controller.dart';
|
||||
import '../features/attention/notify/notification_models.dart';
|
||||
import '../features/attention/notify/chat_question_notices.dart';
|
||||
@@ -55,6 +56,7 @@ import '../shell/windows/window_store.dart';
|
||||
import 'app_terminals.dart';
|
||||
import '../features/chat/chat_run_opener.dart';
|
||||
import '../features/chat/chat_runtime.dart';
|
||||
import '../features/chat/data/chat_recency.dart';
|
||||
import '../features/changes/windows/diff_windows.dart';
|
||||
import '../features/chat/windows/chat_windows.dart';
|
||||
import 'open_in_chat.dart';
|
||||
@@ -359,7 +361,13 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
final chatScope = widget.chatPool != null
|
||||
? 'all-saved-servers'
|
||||
: serverStorageScope(serverIdentity(chatGateway));
|
||||
_chatRuntime = ChatRuntime(gateway: chatGateway, serverKey: chatScope);
|
||||
_chatRuntime = ChatRuntime(
|
||||
gateway: chatGateway,
|
||||
serverKey: chatScope,
|
||||
recency: ChatRecency(
|
||||
store: SharedPreferencesChatRecencyStore(serverScope: chatScope),
|
||||
),
|
||||
);
|
||||
_chatWindows = ChatWindows(
|
||||
manager: _windows,
|
||||
runtime: _chatRuntime,
|
||||
@@ -868,6 +876,19 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
if (!_chatRuntime.quickSwitch.toggle()) _focusOpenChatComposer();
|
||||
}
|
||||
|
||||
/// Alt+N / Alt+J: the shell has shown Chat; once it has built (a first
|
||||
/// visit mounts the chat screen), the chat screen acts.
|
||||
void _chatAction(ShellChatAction action) {
|
||||
final requests = switch (action) {
|
||||
ShellChatAction.newChat => _chatRuntime.newChat,
|
||||
ShellChatAction.nextAttention => _chatRuntime.nextAttention,
|
||||
};
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) requests.toggle();
|
||||
});
|
||||
WidgetsBinding.instance.ensureVisualUpdate();
|
||||
}
|
||||
|
||||
void _selectDestination(AppDestination destination) {
|
||||
// Settings is shown from its own nav item and has no Back, so its route
|
||||
// (filed under the Pipelines tab) must not trap the Pipelines item: that
|
||||
@@ -1130,6 +1151,7 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
onDestinationReselected: _reselectDestination,
|
||||
onOpenChat: _focusOpenChatComposer,
|
||||
onChatQuickSwitch: _toggleChatQuickSwitch,
|
||||
onChatAction: _chatAction,
|
||||
destinationBodies: {
|
||||
AppDestination.pipelines: (_) => FirstRunWalkthroughGate(
|
||||
store: _walkthroughStore,
|
||||
|
||||
@@ -103,7 +103,7 @@ class RunsDestination extends StatelessWidget {
|
||||
initialStageKey: initialStageKey,
|
||||
initialVisit: initialVisit,
|
||||
initialDecide: initialDecide,
|
||||
syncToken: session.connectionEpoch,
|
||||
syncToken: session.runsEpoch,
|
||||
listRefreshToken: listRefreshToken,
|
||||
notifications: notifications,
|
||||
attention: attention,
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../core/transport/pipelines_client.dart';
|
||||
import '../domain/artifact_chat_context.dart';
|
||||
import '../domain/artifact_groups.dart';
|
||||
import 'artifact_external_open.dart';
|
||||
import 'artifact_gallery_page.dart';
|
||||
|
||||
@@ -28,6 +29,12 @@ List<JsonMap> runDetailArtifactSteps(JsonMap run) {
|
||||
bool showRunArtifactsAction(JsonMap run) =>
|
||||
runDetailArtifactSteps(run).isNotEmpty;
|
||||
|
||||
/// How many recorded entries the run's gallery lists (stage files plus
|
||||
/// recorded turn documents), as the gallery header counts them.
|
||||
int runArtifactCount(JsonMap run) => galleryGroups(
|
||||
runDetailArtifactSteps(run),
|
||||
).fold<int>(0, (sum, group) => sum + group.recordedCount);
|
||||
|
||||
/// Whether the run is still executing, so the page can say capture pending
|
||||
/// instead of claiming nothing was recorded.
|
||||
bool runDetailExecuting(JsonMap run) => _runExecuting(run);
|
||||
|
||||
@@ -28,7 +28,15 @@ class ArtifactVisitReveal {
|
||||
final row = target.currentContext;
|
||||
if (row != null && row.mounted) {
|
||||
Scrollable.ensureVisible(row, alignment: 0.5);
|
||||
onDone();
|
||||
// The lazy list's extent is an estimate until the rows past the
|
||||
// target are laid out; a row near the end, clamped to that estimate,
|
||||
// is centred again once the next frame has measured them.
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (generation != _generation) return;
|
||||
if (row.mounted) Scrollable.ensureVisible(row, alignment: 0.5);
|
||||
onDone();
|
||||
});
|
||||
WidgetsBinding.instance.scheduleFrame();
|
||||
return;
|
||||
}
|
||||
final anchorContext = anchor.currentContext;
|
||||
|
||||
@@ -32,33 +32,10 @@ class StageCaptureSection extends StatelessWidget {
|
||||
final status = stage.stepStatus.trim().toLowerCase();
|
||||
final pending =
|
||||
capture == null && (status == 'running' || status == 'waiting');
|
||||
final meta = [
|
||||
'Visit ${stage.visit}',
|
||||
if (stage.stepStatus.isNotEmpty) stage.stepStatus,
|
||||
].join(' · ');
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(meta, style: Theme.of(context).textTheme.bodySmall),
|
||||
if (capture != null) ...[
|
||||
Text(
|
||||
fileChangesSummary(capture),
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
if (capture.scope.isNotEmpty)
|
||||
Text(
|
||||
'Scope: ${capture.scope}',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
StageCaptureHeading(stage: stage),
|
||||
const Divider(height: 1),
|
||||
if (capture == null)
|
||||
_CaptureNote(
|
||||
@@ -99,6 +76,38 @@ class StageCaptureSection extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
/// A stage/visit capture's heading: the visit and step status, the capture's
|
||||
/// summary and its scope.
|
||||
class StageCaptureHeading extends StatelessWidget {
|
||||
const StageCaptureHeading({super.key, required this.stage});
|
||||
|
||||
final StageCapture stage;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final capture = stage.capture;
|
||||
final small = Theme.of(context).textTheme.bodySmall;
|
||||
final meta = [
|
||||
'Visit ${stage.visit}',
|
||||
if (stage.stepStatus.isNotEmpty) stage.stepStatus,
|
||||
].join(' · ');
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(meta, style: small),
|
||||
if (capture != null) ...[
|
||||
Text(fileChangesSummary(capture), style: small),
|
||||
if (capture.scope.isNotEmpty)
|
||||
Text('Scope: ${capture.scope}', style: small),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// One changed file: its kind, path and line counts; tapping opens its diff.
|
||||
/// [dense] draws it on one compact line (the path, then the counts), for a
|
||||
/// card that lists many files in little space.
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../domain/file_change.dart';
|
||||
import '../domain/unified_patch.dart';
|
||||
import '../domain/change_kind.dart';
|
||||
import '../domain/change_wording.dart';
|
||||
import 'capture_section.dart' show changeKindIcon;
|
||||
import 'change_style.dart';
|
||||
import 'file_diff_viewer.dart';
|
||||
|
||||
/// The window width from which the Changes surface shows its files beside
|
||||
/// the selected file's diff instead of one row per file.
|
||||
const double changesSplitMinWidth = 1000;
|
||||
|
||||
/// The narrowest pane that still fits the file list beside a readable diff;
|
||||
/// a desktop window's detail pane beside the run list is usually narrower
|
||||
/// than the window threshold.
|
||||
const double changesSplitMinPaneWidth = 720;
|
||||
|
||||
/// Whether a Changes pane [paneWidth] wide splits into list and diff.
|
||||
bool changesSplitFits(BuildContext context, double paneWidth) =>
|
||||
MediaQuery.sizeOf(context).width >= changesSplitMinWidth &&
|
||||
paneWidth >= changesSplitMinPaneWidth;
|
||||
|
||||
/// A desktop review layout: the changed files as a compact list on the left
|
||||
/// and the selected file's diff on the right, like a code review tool.
|
||||
///
|
||||
/// While the view has focus, `j`/ArrowDown select the next file and
|
||||
/// `k`/ArrowUp the previous one; Enter opens the selected file on its own
|
||||
/// page. Keys typed into a text field are never taken.
|
||||
class ChangesSplitView extends StatefulWidget {
|
||||
const ChangesSplitView({super.key, required this.files, this.heading});
|
||||
|
||||
/// The files to review, in list order. Must not be empty.
|
||||
final List<FileChange> files;
|
||||
|
||||
/// Shown above the file list (a visit's heading).
|
||||
final Widget? heading;
|
||||
|
||||
@override
|
||||
State<ChangesSplitView> createState() => _ChangesSplitViewState();
|
||||
}
|
||||
|
||||
class _ChangesSplitViewState extends State<ChangesSplitView> {
|
||||
final _focus = FocusNode(debugLabel: 'changes split');
|
||||
final _listScroll = ScrollController();
|
||||
List<GlobalKey> _rowKeys = const [];
|
||||
int _index = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_rowKeys = _keysFor(widget.files);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(ChangesSplitView oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (identical(oldWidget.files, widget.files)) return;
|
||||
// Keep the same file selected across a refreshed reply when it is still
|
||||
// listed; otherwise stay at the same position.
|
||||
final path = oldWidget.files.isEmpty
|
||||
? null
|
||||
: oldWidget.files[_index.clamp(0, oldWidget.files.length - 1)].path;
|
||||
final kept = widget.files.indexWhere((file) => file.path == path);
|
||||
_index = kept >= 0
|
||||
? kept
|
||||
: _index.clamp(0, widget.files.isEmpty ? 0 : widget.files.length - 1);
|
||||
_rowKeys = _keysFor(widget.files);
|
||||
}
|
||||
|
||||
static List<GlobalKey> _keysFor(List<FileChange> files) => [
|
||||
for (final file in files) GlobalKey(debugLabel: 'change row ${file.path}'),
|
||||
];
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_focus.dispose();
|
||||
_listScroll.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _select(int index, {bool focus = false}) {
|
||||
if (focus) _focus.requestFocus();
|
||||
if (index < 0 || index >= widget.files.length) return;
|
||||
final forward = index > _index;
|
||||
if (index != _index) setState(() => _index = index);
|
||||
// Keep the selected row in view once it is laid out at its new state.
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
final row = _rowKeys[index].currentContext;
|
||||
if (row == null || !row.mounted) return;
|
||||
Scrollable.ensureVisible(
|
||||
row,
|
||||
alignmentPolicy: forward
|
||||
? ScrollPositionAlignmentPolicy.keepVisibleAtEnd
|
||||
: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
void _step(int delta) =>
|
||||
_select((_index + delta).clamp(0, widget.files.length - 1));
|
||||
|
||||
KeyEventResult _handle(FocusNode node, KeyEvent event) {
|
||||
if (event is KeyUpEvent) return KeyEventResult.ignored;
|
||||
final primary = FocusManager.instance.primaryFocus;
|
||||
final focused = primary?.context;
|
||||
if (primary != node &&
|
||||
focused != null &&
|
||||
(focused.widget is EditableText ||
|
||||
focused.findAncestorWidgetOfExactType<EditableText>() != null)) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
final keyboard = HardwareKeyboard.instance;
|
||||
if (keyboard.isControlPressed ||
|
||||
keyboard.isMetaPressed ||
|
||||
keyboard.isAltPressed) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
final key = event.logicalKey;
|
||||
if (key == LogicalKeyboardKey.arrowDown || key == LogicalKeyboardKey.keyJ) {
|
||||
_step(1);
|
||||
} else if (key == LogicalKeyboardKey.arrowUp ||
|
||||
key == LogicalKeyboardKey.keyK) {
|
||||
_step(-1);
|
||||
} else if (event is KeyDownEvent &&
|
||||
(key == LogicalKeyboardKey.enter ||
|
||||
key == LogicalKeyboardKey.numpadEnter)) {
|
||||
_openPage();
|
||||
} else {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
void _openPage() =>
|
||||
showFileDiffViewer(context, widget.files[_index], files: widget.files);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final files = widget.files;
|
||||
final index = _index.clamp(0, files.length - 1);
|
||||
final file = files[index];
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final listWidth = (constraints.maxWidth * 0.28).clamp(260.0, 380.0);
|
||||
return Focus(
|
||||
focusNode: _focus,
|
||||
onKeyEvent: _handle,
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: listWidth,
|
||||
child: Semantics(
|
||||
container: true,
|
||||
identifier: 'changes-file-list',
|
||||
label: 'Changed files',
|
||||
explicitChildNodes: true,
|
||||
child: SingleChildScrollView(
|
||||
key: const ValueKey('changes-split-list'),
|
||||
controller: _listScroll,
|
||||
padding: const EdgeInsets.only(bottom: 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
?widget.heading,
|
||||
for (var i = 0; i < files.length; i++)
|
||||
_SplitFileRow(
|
||||
key: _rowKeys[i],
|
||||
file: files[i],
|
||||
selected: i == index,
|
||||
onTap: () => _select(i, focus: true),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const VerticalDivider(width: 1),
|
||||
Expanded(
|
||||
child: FileDiffViewer(
|
||||
key: ValueKey<String>('changes-split-diff-${file.path}'),
|
||||
file: file,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// One file in the split list: its name with its folder below, so a long
|
||||
/// path never hides the file name, and its line counts.
|
||||
class _SplitFileRow extends StatelessWidget {
|
||||
const _SplitFileRow({
|
||||
super.key,
|
||||
required this.file,
|
||||
required this.selected,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
final FileChange file;
|
||||
final bool selected;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final mono = nativeDiffText(DefaultTextStyle.of(context).style);
|
||||
final slash = file.path.lastIndexOf('/');
|
||||
final name = slash < 0 ? file.path : file.path.substring(slash + 1);
|
||||
final folder = slash < 0 ? '' : file.path.substring(0, slash);
|
||||
return Semantics(
|
||||
container: true,
|
||||
button: true,
|
||||
selected: selected,
|
||||
label:
|
||||
'Show diff for ${file.path}. '
|
||||
'${changeKindTitle(file.kind)} · ${changeFileMeta(file)}',
|
||||
excludeSemantics: true,
|
||||
onTap: onTap,
|
||||
child: ListTile(
|
||||
dense: true,
|
||||
visualDensity: VisualDensity.compact,
|
||||
minLeadingWidth: 20,
|
||||
selected: selected,
|
||||
selectedTileColor: theme.colorScheme.secondaryContainer,
|
||||
selectedColor: theme.colorScheme.onSecondaryContainer,
|
||||
leading: Icon(changeKindIcon(file.kind), size: 20),
|
||||
title: Text(
|
||||
name,
|
||||
style: mono,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
subtitle: folder.isEmpty
|
||||
? null
|
||||
: Text(folder, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
trailing: ChangeStatText(changeStat(file.added, file.removed)),
|
||||
onTap: onTap,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import '../domain/change_wording.dart';
|
||||
import '../domain/file_change.dart';
|
||||
import '../domain/run_changes.dart';
|
||||
import 'capture_section.dart';
|
||||
import 'changes_split_view.dart';
|
||||
import 'change_style.dart';
|
||||
import 'file_diff_viewer.dart';
|
||||
import 'visit_pager.dart';
|
||||
@@ -97,7 +98,14 @@ class _ChangesViewerState extends State<ChangesViewer> {
|
||||
static const _query = '';
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
Widget build(BuildContext context) => LayoutBuilder(
|
||||
builder: (context, constraints) =>
|
||||
_build(context, split: changesSplitFits(context, constraints.maxWidth)),
|
||||
);
|
||||
|
||||
/// [split] shows the files beside the selected file's diff (a wide pane)
|
||||
/// rather than one row per file opening its own page.
|
||||
Widget _build(BuildContext context, {required bool split}) {
|
||||
final run = _run;
|
||||
final captures = _captures;
|
||||
final showSummary = widget.showSummary;
|
||||
@@ -106,6 +114,7 @@ class _ChangesViewerState extends State<ChangesViewer> {
|
||||
);
|
||||
final note = showSummary ? runChangesNote(run) : '';
|
||||
final visit = captures.isEmpty ? null : captures[_visitIndex];
|
||||
final visitFiles = visit?.capture?.files ?? const <FileChange>[];
|
||||
final hasVisitPager = !widget.finalOnly && captures.length > 1;
|
||||
final pager = hasVisitPager
|
||||
? ChangesVisitPager(
|
||||
@@ -158,7 +167,17 @@ class _ChangesViewerState extends State<ChangesViewer> {
|
||||
),
|
||||
if (showSummary) const Divider(height: 1),
|
||||
// The run's final changes: every changed path once, as it ended.
|
||||
if (widget.finalOnly)
|
||||
if (widget.finalOnly && split && run.files.isNotEmpty)
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: withBarClearance(context, EdgeInsets.zero),
|
||||
child: ChangesSplitView(
|
||||
key: const ValueKey<String>('changes-final-split'),
|
||||
files: run.files,
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (widget.finalOnly)
|
||||
Expanded(
|
||||
child: run.files.isEmpty
|
||||
? SingleChildScrollView(
|
||||
@@ -184,7 +203,31 @@ class _ChangesViewerState extends State<ChangesViewer> {
|
||||
],
|
||||
),
|
||||
),
|
||||
if (!widget.finalOnly)
|
||||
if (!widget.finalOnly &&
|
||||
split &&
|
||||
visit != null &&
|
||||
visitFiles.isNotEmpty)
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: hasVisitPager
|
||||
? withBarClearance(context, EdgeInsets.zero)
|
||||
: withTopBarClearance(context, EdgeInsets.zero),
|
||||
child: ChangesSplitView(
|
||||
key: ValueKey<String>(
|
||||
'changes-visit-split-${visit.stage}-${visit.sequence}',
|
||||
),
|
||||
files: visitFiles,
|
||||
heading: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
StageCaptureHeading(stage: visit),
|
||||
const Divider(height: 1),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (!widget.finalOnly)
|
||||
Expanded(
|
||||
child: visit == null
|
||||
? SingleChildScrollView(
|
||||
|
||||
@@ -13,6 +13,7 @@ import 'conversation/chat_transcript_cache.dart';
|
||||
import 'conversation/chat_composer_controller.dart';
|
||||
import 'conversation/chat_quick_switch_requests.dart';
|
||||
import 'conversation/composer_focus_request.dart';
|
||||
import 'data/chat_recency.dart';
|
||||
import 'data/chat_repository.dart';
|
||||
import 'ui/sessions/chat_sessions_body.dart';
|
||||
import 'ui/sessions/chat_sessions_controller.dart';
|
||||
@@ -24,9 +25,13 @@ import 'ui/sessions/chat_sessions_controller.dart';
|
||||
///
|
||||
/// It notifies when a row a conversation is drawn from changes.
|
||||
class ChatRuntime extends ChangeNotifier {
|
||||
ChatRuntime({required ApiGateway gateway, this.serverKey = ''})
|
||||
: _gateway = gateway,
|
||||
sessions = ChatSessionsController(ChatRepository(gateway)) {
|
||||
ChatRuntime({
|
||||
required ApiGateway gateway,
|
||||
this.serverKey = '',
|
||||
ChatRecency? recency,
|
||||
}) : _gateway = gateway,
|
||||
recency = recency ?? ChatRecency(),
|
||||
sessions = ChatSessionsController(ChatRepository(gateway)) {
|
||||
sessions.onSessionReplaced = (previousId, session) {
|
||||
for (final listener in _replaced.toList()) {
|
||||
listener(previousId, session);
|
||||
@@ -132,6 +137,15 @@ class ChatRuntime extends ChangeNotifier {
|
||||
/// The Chat destination's quick switcher, toggled by Ctrl+K / Alt+K there.
|
||||
final ChatQuickSwitchRequests quickSwitch = ChatQuickSwitchRequests();
|
||||
|
||||
/// New chat (Alt+N) and the next chat needing the operator (Alt+J), asked
|
||||
/// of the mounted Chat destination.
|
||||
final ChatQuickSwitchRequests newChat = ChatQuickSwitchRequests();
|
||||
final ChatQuickSwitchRequests nextAttention = ChatQuickSwitchRequests();
|
||||
|
||||
/// The chats this device used, most recent first (the quick switcher's
|
||||
/// order with no query).
|
||||
final ChatRecency recency;
|
||||
|
||||
/// Mounted composers are registered so external actions can append without
|
||||
/// sending. A selection made before a pane mounts is queued here.
|
||||
final Map<String, ChatComposerController> composers = {};
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
part of 'screen.dart';
|
||||
|
||||
/// The Chat destination's app-wide chat shortcuts, run through
|
||||
/// [ChatRuntime.newChat] and [ChatRuntime.nextAttention] (the shell shows
|
||||
/// Chat first): Alt+N starts a new chat with the list's own create dialog,
|
||||
/// and Alt+J opens the next chat needing the operator (waiting for an answer,
|
||||
/// unread, or a failed action), cycling in list order. Neither acts while a
|
||||
/// popup or dialog over the chat keeps the keyboard.
|
||||
mixin _ChatScreenAttention on State<ChatScreen>, _ChatScreenWorkspace {
|
||||
ChatRuntime get _runtime;
|
||||
|
||||
void _bindAttention() {
|
||||
_runtime.newChat.attach(_startNewChat);
|
||||
_runtime.nextAttention.attach(_openNextAttention);
|
||||
}
|
||||
|
||||
void _unbindAttention() {
|
||||
_runtime.newChat.detach(_startNewChat);
|
||||
_runtime.nextAttention.detach(_openNextAttention);
|
||||
}
|
||||
|
||||
void _startNewChat() {
|
||||
if (!mounted || !_chatOwnsKeyboard()) return;
|
||||
final state = _sessionsKey.currentState;
|
||||
if (state != null) unawaited(state.newChat());
|
||||
}
|
||||
|
||||
void _openNextAttention() {
|
||||
if (!mounted || !_chatOwnsKeyboard()) return;
|
||||
final sessions = _runtime.sessions;
|
||||
final current = _workspaceVisible ? _workspace.activePane?.sessionId : null;
|
||||
final next = chatNextNeedingAttention(
|
||||
sessions.sessions,
|
||||
current,
|
||||
(row) => chatNeedsAttention(
|
||||
row,
|
||||
unread: sessions.isUnseen(row),
|
||||
failed: sessions.errorFor('${row['id'] ?? ''}') != null,
|
||||
),
|
||||
);
|
||||
if (next != null) {
|
||||
_openByShortcut(next);
|
||||
return;
|
||||
}
|
||||
ScaffoldMessenger.maybeOf(context)
|
||||
?..hideCurrentSnackBar()
|
||||
..showSnackBar(
|
||||
const SnackBar(
|
||||
key: Key('chat-no-attention'),
|
||||
content: Text('No other chat needs you.'),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,21 @@
|
||||
part of 'screen.dart';
|
||||
|
||||
/// The quick switcher Ctrl+K / Alt+K (Cmd+K on a Mac) shows when pressed on
|
||||
/// the Chat destination: the open chats to jump to, filtered as the operator
|
||||
/// types (see [showChatQuickSwitch]). Pressing the shortcut again closes it.
|
||||
/// A chosen chat opens as a keyboard choice from the list does: its pane is
|
||||
/// reused when it is already open, and its composer takes the keyboard.
|
||||
/// the Chat destination: the open chats to jump to, most recently used first
|
||||
/// with the one used before the current chat selected, filtered as the
|
||||
/// operator types (see [showChatQuickSwitch]). Pressing the shortcut again
|
||||
/// closes it. A chosen chat opens as a keyboard choice from the list does:
|
||||
/// its pane is reused when it is already open, and its composer takes the
|
||||
/// keyboard. A closed chat a query found is reopened first.
|
||||
mixin _ChatScreenQuickSwitch on State<ChatScreen>, _ChatScreenWorkspace {
|
||||
ChatRuntime get _runtime;
|
||||
|
||||
ModalRoute<JsonMap>? _quickSwitchRoute;
|
||||
|
||||
void _bindQuickSwitch() => _runtime.quickSwitch.attach(_toggleQuickSwitch);
|
||||
void _bindQuickSwitch() {
|
||||
_runtime.quickSwitch.attach(_toggleQuickSwitch);
|
||||
unawaited(_runtime.recency.load());
|
||||
}
|
||||
|
||||
void _unbindQuickSwitch() {
|
||||
_runtime.quickSwitch.detach(_toggleQuickSwitch);
|
||||
@@ -24,6 +29,12 @@ mixin _ChatScreenQuickSwitch on State<ChatScreen>, _ChatScreenWorkspace {
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void _touchActiveChat() {
|
||||
final id = _workspaceVisible ? _workspace.activePane?.sessionId : null;
|
||||
if (id != null) _runtime.recency.touch(id);
|
||||
}
|
||||
|
||||
void _toggleQuickSwitch() {
|
||||
final open = _quickSwitchRoute;
|
||||
if (open != null && open.isActive) {
|
||||
@@ -36,9 +47,11 @@ mixin _ChatScreenQuickSwitch on State<ChatScreen>, _ChatScreenWorkspace {
|
||||
final route = showChatQuickSwitch(
|
||||
context,
|
||||
sessions: _runtime.sessions,
|
||||
recent: () => _runtime.recency.ids,
|
||||
currentId: _workspaceVisible ? _workspace.activePane?.sessionId : null,
|
||||
serverName: _quickSwitchServerName,
|
||||
onSelected: (row) {
|
||||
if (mounted) _openByShortcut(row);
|
||||
if (mounted) unawaited(_openSwitched(row));
|
||||
},
|
||||
);
|
||||
_quickSwitchRoute = route;
|
||||
@@ -47,6 +60,20 @@ mixin _ChatScreenQuickSwitch on State<ChatScreen>, _ChatScreenWorkspace {
|
||||
});
|
||||
}
|
||||
|
||||
/// Opens a chosen chat, reopening it first when it was closed. A refused
|
||||
/// reopen leaves it closed, with the list row showing the server's words.
|
||||
Future<void> _openSwitched(JsonMap row) async {
|
||||
if (chatQuickSwitchIsClosed(row)) {
|
||||
final id = '${row['id'] ?? ''}';
|
||||
await _runtime.sessions.reopen(id);
|
||||
if (!mounted || _runtime.sessions.errorFor(id) != null) return;
|
||||
row = {...row}
|
||||
..remove('closed_at')
|
||||
..remove('closed');
|
||||
}
|
||||
if (mounted) _openByShortcut(row);
|
||||
}
|
||||
|
||||
/// The machine a federated row is on, as the list names it.
|
||||
String? _quickSwitchServerName(JsonMap row) {
|
||||
final id = '${row['_server_id'] ?? ''}';
|
||||
|
||||
@@ -365,6 +365,7 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
||||
if (_workspaceSignature == signature) return;
|
||||
_workspaceSignature = signature;
|
||||
_syncOpenWorkspace();
|
||||
_touchActiveChat();
|
||||
void update() {
|
||||
if (!mounted) return;
|
||||
setState(() {});
|
||||
@@ -379,6 +380,10 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The active pane's chat, while shown, is the most recently used one (the
|
||||
/// quick switcher's order).
|
||||
void _touchActiveChat();
|
||||
|
||||
void _publishWorkspaceRoute() {
|
||||
if (!mounted) return;
|
||||
final id = _workspace.activePane?.sessionId;
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'chat_find_controller.dart';
|
||||
|
||||
/// The chat's find bar, like the terminal's: the query field, the match
|
||||
/// count, Match case, the older/newer and close buttons. Matches count from
|
||||
/// the newest; Enter moves to an older match and Shift+Enter to a newer one;
|
||||
/// Esc closes. [onStep] moves and reveals; [onClose] closes the bar and
|
||||
/// returns the keyboard to the composer.
|
||||
class ChatFindBar extends StatefulWidget {
|
||||
const ChatFindBar({
|
||||
super.key,
|
||||
required this.find,
|
||||
required this.focus,
|
||||
required this.onStep,
|
||||
required this.onClose,
|
||||
});
|
||||
|
||||
final ChatFindController find;
|
||||
final FocusNode focus;
|
||||
final ValueChanged<int> onStep;
|
||||
final VoidCallback onClose;
|
||||
|
||||
@override
|
||||
State<ChatFindBar> createState() => _ChatFindBarState();
|
||||
}
|
||||
|
||||
class _ChatFindBarState extends State<ChatFindBar> {
|
||||
late final TextEditingController _text = TextEditingController(
|
||||
text: widget.find.query,
|
||||
);
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_text.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
KeyEventResult _key(FocusNode node, KeyEvent event) {
|
||||
if (event is KeyUpEvent) return KeyEventResult.ignored;
|
||||
if (event.logicalKey == LogicalKeyboardKey.escape) {
|
||||
widget.onClose();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (event.logicalKey == LogicalKeyboardKey.enter ||
|
||||
event.logicalKey == LogicalKeyboardKey.numpadEnter) {
|
||||
widget.onStep(HardwareKeyboard.instance.isShiftPressed ? -1 : 1);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
String _count(ChatFindController find) {
|
||||
if (find.query.isEmpty) return '';
|
||||
if (find.count == 0) return find.capped ? 'Searching…' : 'No results';
|
||||
final total = find.capped ? '${find.count}+' : '${find.count}';
|
||||
return '${find.index + 1} of $total';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final find = widget.find;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
// The buttons count as part of the field, so clicking one keeps the
|
||||
// keyboard in it (Enter steps on from there).
|
||||
return TextFieldTapRegion(
|
||||
child: Material(
|
||||
elevation: 3,
|
||||
color: scheme.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.only(start: 12, end: 4),
|
||||
child: ListenableBuilder(
|
||||
listenable: find,
|
||||
builder: (context, _) => Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Flexible(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 240),
|
||||
child: Focus(
|
||||
onKeyEvent: _key,
|
||||
skipTraversal: true,
|
||||
child: TextField(
|
||||
key: const ValueKey('chat-find-field'),
|
||||
controller: _text,
|
||||
focusNode: widget.focus,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(
|
||||
hintText: 'Find in chat',
|
||||
border: InputBorder.none,
|
||||
isDense: true,
|
||||
),
|
||||
onChanged: (value) => find.query = value,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Semantics(
|
||||
liveRegion: true,
|
||||
child: Text(
|
||||
_count(find),
|
||||
key: const ValueKey('chat-find-count'),
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
key: const ValueKey('chat-find-case'),
|
||||
tooltip: 'Match case',
|
||||
isSelected: find.caseSensitive,
|
||||
onPressed: find.toggleCase,
|
||||
icon: const Text('Aa'),
|
||||
),
|
||||
IconButton(
|
||||
key: const ValueKey('chat-find-older'),
|
||||
tooltip: 'Older match (Enter)',
|
||||
onPressed: find.count == 0 ? null : () => widget.onStep(1),
|
||||
icon: const Icon(Icons.keyboard_arrow_up),
|
||||
),
|
||||
IconButton(
|
||||
key: const ValueKey('chat-find-newer'),
|
||||
tooltip: 'Newer match (Shift+Enter)',
|
||||
onPressed: find.count == 0 ? null : () => widget.onStep(-1),
|
||||
icon: const Icon(Icons.keyboard_arrow_down),
|
||||
),
|
||||
IconButton(
|
||||
key: const ValueKey('chat-find-close'),
|
||||
tooltip: 'Close find (Esc)',
|
||||
onPressed: widget.onClose,
|
||||
icon: const Icon(Icons.close),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/chat_find.dart';
|
||||
|
||||
/// A highlighted range in one rendered text, and whether it is the current
|
||||
/// match.
|
||||
typedef ChatFindHighlight = ({int start, int end, bool current});
|
||||
|
||||
/// Find in one chat: the query, whether case matters, the matches in the
|
||||
/// loaded transcript and, through the server's scoped search, those in older
|
||||
/// history not loaded yet.
|
||||
///
|
||||
/// Matches are numbered from the newest: "1 of N" is the newest match and
|
||||
/// stepping on (Enter) goes back in time, so finding never starts by jumping
|
||||
/// to the start of a long history. The loaded matches come first; the
|
||||
/// server's hits in unloaded messages, all older, follow in its order, so a
|
||||
/// match keeps its number when the page holding it loads.
|
||||
class ChatFindController extends ChangeNotifier {
|
||||
ChatFindController({
|
||||
required this.gateway,
|
||||
required this.sessionId,
|
||||
required this.history,
|
||||
this.debounce = const Duration(milliseconds: 250),
|
||||
});
|
||||
|
||||
final ApiGateway gateway;
|
||||
final String sessionId;
|
||||
final Duration debounce;
|
||||
|
||||
/// Whether the transcript has older history it has not loaded, and the
|
||||
/// cursor its next older page would be read with.
|
||||
final ({bool hasMore, String cursor}) Function() history;
|
||||
|
||||
String _query = '';
|
||||
bool _caseSensitive = false;
|
||||
List<ChatFindUnit> _units = const [];
|
||||
Set<String> _loadedIds = const {};
|
||||
|
||||
/// Loaded matches, newest first.
|
||||
List<ChatFindMatch> _local = const [];
|
||||
List<ChatFindRemoteHit> _remoteAll = const [];
|
||||
List<ChatFindRemoteHit> _remote = const [];
|
||||
bool _remoteMore = false;
|
||||
bool _searching = false;
|
||||
int _index = -1;
|
||||
ChatFindMatch? _currentLocal;
|
||||
int _generation = 0;
|
||||
Timer? _timer;
|
||||
Map<String, Map<String, List<ChatFindHighlight>>> _byRow = const {};
|
||||
bool _disposed = false;
|
||||
|
||||
String get query => _query;
|
||||
bool get caseSensitive => _caseSensitive;
|
||||
|
||||
/// How many matches are known: loaded ones and the server's in history
|
||||
/// that is not loaded.
|
||||
int get count => _local.length + _remote.length;
|
||||
|
||||
/// Whether there may be more matches than [count] (the server's search
|
||||
/// stopped at its cap, or is still running).
|
||||
bool get capped =>
|
||||
_remoteMore || _searching || _local.length >= chatFindLocalCap;
|
||||
|
||||
/// The current match's number from the newest (0-based), -1 with none.
|
||||
int get index => _index;
|
||||
|
||||
/// The current match when it is in the loaded transcript.
|
||||
ChatFindMatch? get current =>
|
||||
_index >= 0 && _index < _local.length ? _local[_index] : null;
|
||||
|
||||
/// The current match when it is in history not loaded yet.
|
||||
ChatFindRemoteHit? get currentRemote {
|
||||
final at = _index - _local.length;
|
||||
return at >= 0 && at < _remote.length ? _remote[at] : null;
|
||||
}
|
||||
|
||||
/// Bumped whenever the current match moves, so the view reveals it once.
|
||||
int get revealToken => _revealToken;
|
||||
int _revealToken = 0;
|
||||
|
||||
/// The highlights in [text] of row [rowKey].
|
||||
List<ChatFindHighlight> highlightsFor(String rowKey, String text) =>
|
||||
_byRow[rowKey]?[text] ?? const [];
|
||||
|
||||
set query(String value) {
|
||||
if (value == _query) return;
|
||||
_query = value;
|
||||
_restart();
|
||||
}
|
||||
|
||||
void toggleCase() {
|
||||
_caseSensitive = !_caseSensitive;
|
||||
_restart();
|
||||
}
|
||||
|
||||
/// Moves to an older match ([step] 1) or a newer one (-1), wrapping.
|
||||
void step(int step) {
|
||||
if (count == 0) return;
|
||||
_select((_index + step) % count);
|
||||
}
|
||||
|
||||
/// Takes the transcript as it is now. The current loaded match stays
|
||||
/// current; otherwise the current number does. Listeners hear of a change
|
||||
/// after this frame, since the transcript calls this while it builds.
|
||||
void updateTranscript(
|
||||
List<JsonMap> rows,
|
||||
List<String> keys,
|
||||
Iterable<String> loadedMessageIds,
|
||||
) {
|
||||
final units = chatFindUnits(rows, keys);
|
||||
_loadedIds = {...loadedMessageIds};
|
||||
final sameUnits = _sameUnits(units);
|
||||
_units = units;
|
||||
if (sameUnits && _remote.length == _filterRemote().length) return;
|
||||
_recompute(keepCurrent: true);
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) => _notify());
|
||||
}
|
||||
|
||||
bool _sameUnits(List<ChatFindUnit> units) {
|
||||
if (units.length != _units.length) return false;
|
||||
for (var i = 0; i < units.length; i++) {
|
||||
if (units[i].rowKey != _units[i].rowKey ||
|
||||
!identical(units[i].text, _units[i].text) &&
|
||||
units[i].text != _units[i].text) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
List<ChatFindRemoteHit> _filterRemote() => [
|
||||
for (final hit in _remoteAll)
|
||||
if (!_loadedIds.contains(hit.messageId)) hit,
|
||||
];
|
||||
|
||||
void _restart() {
|
||||
_generation++;
|
||||
_timer?.cancel();
|
||||
_remoteAll = const [];
|
||||
_remote = const [];
|
||||
_remoteMore = false;
|
||||
_searching = false;
|
||||
_currentLocal = null;
|
||||
_index = -1;
|
||||
_recompute(keepCurrent: false);
|
||||
_searchHistory();
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _recompute({required bool keepCurrent}) {
|
||||
final previous = keepCurrent ? _currentLocal : null;
|
||||
final previousIndex = _index;
|
||||
_local = _query.isEmpty
|
||||
? const []
|
||||
: chatFindMatches(
|
||||
_units,
|
||||
_query,
|
||||
caseSensitive: _caseSensitive,
|
||||
).reversed.toList();
|
||||
_remote = _filterRemote();
|
||||
var index = -1;
|
||||
if (previous != null) {
|
||||
index = _local.indexWhere(previous.sameAs);
|
||||
}
|
||||
if (index < 0 && keepCurrent && previousIndex >= 0 && count > 0) {
|
||||
index = previousIndex.clamp(0, count - 1);
|
||||
}
|
||||
if (index < 0 && count > 0) index = 0;
|
||||
_setIndex(index, reveal: !keepCurrent || index != previousIndex);
|
||||
_rebuildHighlights();
|
||||
}
|
||||
|
||||
void _select(int index) {
|
||||
_setIndex(index, reveal: true);
|
||||
_rebuildHighlights();
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _setIndex(int index, {required bool reveal}) {
|
||||
_index = index;
|
||||
_currentLocal = current;
|
||||
if (reveal && index >= 0) _revealToken++;
|
||||
}
|
||||
|
||||
void _rebuildHighlights() {
|
||||
final byRow = <String, Map<String, List<ChatFindHighlight>>>{};
|
||||
final now = current;
|
||||
for (final match in _local) {
|
||||
byRow
|
||||
.putIfAbsent(match.rowKey, () => {})
|
||||
.putIfAbsent(match.unit.text, () => [])
|
||||
.add((
|
||||
start: match.start,
|
||||
end: match.end,
|
||||
current: identical(match, now),
|
||||
));
|
||||
}
|
||||
_byRow = byRow;
|
||||
}
|
||||
|
||||
/// Asks the server for matches in the history before the transcript's
|
||||
/// loaded pages, after a short pause in typing. Without older history
|
||||
/// there is nothing to ask.
|
||||
void _searchHistory() {
|
||||
final older = history();
|
||||
if (_query.isEmpty || !older.hasMore) return;
|
||||
final generation = _generation;
|
||||
_searching = true;
|
||||
_timer = Timer(debounce, () {
|
||||
unawaited(_fetch(generation, '0|${older.cursor}'));
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _fetch(int generation, String cursor) async {
|
||||
var next = cursor;
|
||||
final hits = <ChatFindRemoteHit>[];
|
||||
try {
|
||||
while (true) {
|
||||
final reply = await gateway.call('search', {
|
||||
'search': {
|
||||
'query': _query,
|
||||
'kind': 'chat',
|
||||
'scope': 'chat:$sessionId',
|
||||
'cursor': next,
|
||||
'case_sensitive': _caseSensitive,
|
||||
'limit': 200,
|
||||
},
|
||||
});
|
||||
if (_disposed || generation != _generation) return;
|
||||
hits.addAll(ChatFindRemoteHit.fromReply(reply));
|
||||
final results = reply['search_results'];
|
||||
next = results is Map ? '${results['next_cursor'] ?? ''}' : '';
|
||||
_remoteAll = List.unmodifiable(hits);
|
||||
_remoteMore = next.isNotEmpty && hits.length >= chatFindRemoteCap;
|
||||
_recompute(keepCurrent: true);
|
||||
_notify();
|
||||
if (next.isEmpty || hits.length >= chatFindRemoteCap) break;
|
||||
}
|
||||
} catch (_) {
|
||||
// An older server without scoped search, or a dropped socket: the
|
||||
// loaded transcript's matches still stand.
|
||||
if (_disposed || generation != _generation) return;
|
||||
}
|
||||
_searching = false;
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_timer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../ui/input/keyboard_owner.dart';
|
||||
import '../shell/chat_shell_terminal_find_bar.dart';
|
||||
import '../ui/transcript/chat_find_highlight.dart';
|
||||
import 'chat_find_bar.dart';
|
||||
import 'chat_find_controller.dart';
|
||||
import 'chat_thread_controller.dart';
|
||||
import 'chat_thread_view.dart';
|
||||
import 'composer_focus_request.dart';
|
||||
|
||||
/// Whether [event] is find's key: Cmd+F on Apple platforms, Ctrl+F
|
||||
/// elsewhere, without Shift or Alt.
|
||||
bool chatFindShortcut(KeyEvent event, HardwareKeyboard keyboard) {
|
||||
if (event is! KeyDownEvent || event.logicalKey != LogicalKeyboardKey.keyF) {
|
||||
return false;
|
||||
}
|
||||
final apple =
|
||||
defaultTargetPlatform == TargetPlatform.macOS ||
|
||||
defaultTargetPlatform == TargetPlatform.iOS;
|
||||
final ctrl = keyboard.isControlPressed;
|
||||
final meta = keyboard.isMetaPressed;
|
||||
if (keyboard.isAltPressed || keyboard.isShiftPressed) return false;
|
||||
return apple ? meta && !ctrl : ctrl && !meta;
|
||||
}
|
||||
|
||||
/// Find in one open chat: Ctrl+F (Cmd+F) opens the bar over the transcript,
|
||||
/// matches are highlighted, the current one is scrolled into view (reading
|
||||
/// older pages until it is loaded), and Esc closes the bar and returns the
|
||||
/// keyboard to the composer.
|
||||
mixin ChatFindHost on State<ChatThreadView> {
|
||||
ScrollController get findScroll;
|
||||
ChatThreadController get findThread;
|
||||
|
||||
/// Stops the transcript following its end while find moves it.
|
||||
void findReleaseFollow();
|
||||
|
||||
/// Lets the transcript decide again whether it follows its end.
|
||||
void findSettleFollow();
|
||||
|
||||
final findTargets = ChatFindTargets();
|
||||
final FocusNode _findFocus = FocusNode(debugLabel: 'chat-find');
|
||||
ChatFindController? _find;
|
||||
int _revealed = 0;
|
||||
Map<String, int> _rowIndex = const {};
|
||||
|
||||
ChatFindController? get find => _find;
|
||||
|
||||
void disposeFind() {
|
||||
_find?.dispose();
|
||||
_findFocus.dispose();
|
||||
}
|
||||
|
||||
/// The pane's key handler: find's shortcut from anywhere in this chat,
|
||||
/// except a terminal (where Ctrl+F is the shell's) and its own find bar.
|
||||
KeyEventResult findKey(FocusNode node, KeyEvent event) {
|
||||
if (!chatFindShortcut(event, HardwareKeyboard.instance)) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
if (primaryFocusIsTypingSurface()) return KeyEventResult.ignored;
|
||||
final focused = FocusManager.instance.primaryFocus?.context;
|
||||
if (focused?.findAncestorWidgetOfExactType<ChatShellTerminalFindBar>() !=
|
||||
null) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
openFind();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
/// Opens the find bar, or focuses its field when it is open.
|
||||
void openFind() {
|
||||
if (_find == null) {
|
||||
final find = ChatFindController(
|
||||
gateway: widget.gateway,
|
||||
sessionId: widget.sessionId,
|
||||
history: () => (hasMore: findThread.hasMore, cursor: findThread.cursor),
|
||||
)..addListener(_findChanged);
|
||||
setState(() => _find = find);
|
||||
}
|
||||
// The field's autofocus would not take the keyboard from the composer,
|
||||
// which holds it in the same scope.
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted && _find != null) _findFocus.requestFocus();
|
||||
});
|
||||
}
|
||||
|
||||
void closeFind() {
|
||||
final find = _find;
|
||||
if (find == null) return;
|
||||
setState(() => _find = null);
|
||||
find.dispose();
|
||||
findSettleFollow();
|
||||
ChatComposerFocusScope.maybeOf(context)?.requests.request(widget.sessionId);
|
||||
}
|
||||
|
||||
void _findChanged() {
|
||||
final find = _find;
|
||||
if (find == null || find.revealToken == _revealed) return;
|
||||
_revealed = find.revealToken;
|
||||
unawaited(_reveal(find, _revealed));
|
||||
}
|
||||
|
||||
/// Hands the transcript as built to an open find.
|
||||
void findTranscript(List<JsonMap> rows, List<String> keys) {
|
||||
final find = _find;
|
||||
if (find == null) return;
|
||||
_rowIndex = {for (var i = 0; i < keys.length; i++) keys[i]: i};
|
||||
find.updateTranscript(rows, keys, [
|
||||
for (final message in findThread.messages)
|
||||
if ('${message['id'] ?? ''}'.isNotEmpty) '${message['id']}',
|
||||
]);
|
||||
}
|
||||
|
||||
/// [transcript] inside find's scope.
|
||||
Widget findScope(Widget transcript) =>
|
||||
ChatFindScope(controller: _find, targets: findTargets, child: transcript);
|
||||
|
||||
/// The bar over the transcript's top end while find is open.
|
||||
Widget? findBar({required double top, required double end}) {
|
||||
final find = _find;
|
||||
if (find == null) return null;
|
||||
return PositionedDirectional(
|
||||
top: top,
|
||||
start: 8,
|
||||
end: end,
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.topEnd,
|
||||
child: ChatFindBar(
|
||||
find: find,
|
||||
focus: _findFocus,
|
||||
onStep: find.step,
|
||||
onClose: closeFind,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Brings find's current match into view: reads older pages until it is
|
||||
/// loaded, scrolls toward its row until the row is built, then centres the
|
||||
/// match. A newer move ([token]) abandons this one.
|
||||
Future<void> _reveal(ChatFindController find, int token) async {
|
||||
bool stale() => !mounted || _find != find || find.revealToken != token;
|
||||
findReleaseFollow();
|
||||
for (var attempt = 0; attempt < 120; attempt++) {
|
||||
if (stale()) return;
|
||||
if (find.currentRemote != null) {
|
||||
if (!findThread.hasMore) return;
|
||||
if (!findThread.loading) await findThread.loadOlder();
|
||||
await WidgetsBinding.instance.endOfFrame;
|
||||
continue;
|
||||
}
|
||||
final match = find.current;
|
||||
if (match == null || !findScroll.hasClients) return;
|
||||
final rects = findTargets.textFor(match.rowKey, match.unit.text);
|
||||
final row = findTargets.rows[match.rowKey];
|
||||
if (rects != null && row != null && row.mounted) {
|
||||
if (_centre(row, rects, match.start, match.end)) break;
|
||||
} else if (!_stepToward(match.unit.rowIndex)) {
|
||||
return;
|
||||
}
|
||||
await WidgetsBinding.instance.endOfFrame;
|
||||
}
|
||||
if (!stale()) findSettleFollow();
|
||||
}
|
||||
|
||||
/// Scrolls so the match is in the middle of the viewport when it is not
|
||||
/// already comfortably in view; true once it is placed.
|
||||
bool _centre(BuildContext row, ChatFindRects rects, int start, int end) {
|
||||
final object = row.findRenderObject();
|
||||
if (object == null || !object.attached) return false;
|
||||
final viewport = RenderAbstractViewport.maybeOf(object);
|
||||
if (viewport is! RenderBox || !(viewport as RenderBox).hasSize) {
|
||||
return false;
|
||||
}
|
||||
final box = viewport as RenderBox;
|
||||
final boxes = rects(start, end, box);
|
||||
if (boxes.isEmpty) {
|
||||
unawaited(Scrollable.ensureVisible(row, alignment: 0.5));
|
||||
return false;
|
||||
}
|
||||
final match = boxes.reduce((a, b) => a.expandToInclude(b));
|
||||
final height = box.size.height;
|
||||
final margin = math.min(64.0, height / 4);
|
||||
if (match.top >= margin && match.bottom <= height - margin) return true;
|
||||
final position = findScroll.position;
|
||||
final target = (position.pixels + match.center.dy - height / 2).clamp(
|
||||
position.minScrollExtent,
|
||||
position.maxScrollExtent,
|
||||
);
|
||||
if ((target - position.pixels).abs() < 1) return true;
|
||||
position.jumpTo(target);
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Moves the transcript a screen toward row [index] when it is not built;
|
||||
/// false when it cannot move further.
|
||||
bool _stepToward(int index) {
|
||||
final built = [
|
||||
for (final entry in findTargets.rows.entries)
|
||||
if (entry.value.mounted && _rowIndex[entry.key] != null)
|
||||
_rowIndex[entry.key]!,
|
||||
];
|
||||
final position = findScroll.position;
|
||||
final older = built.isEmpty || index < built.reduce(math.min);
|
||||
final distance = position.viewportDimension * 0.8;
|
||||
final target = (position.pixels + (older ? -distance : distance)).clamp(
|
||||
position.minScrollExtent,
|
||||
position.maxScrollExtent,
|
||||
);
|
||||
if ((target - position.pixels).abs() < 1) return false;
|
||||
position.jumpTo(target);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -4,28 +4,39 @@ import 'package:flutter/services.dart';
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../ui/adaptive/app_popups.dart';
|
||||
import '../domain/chat_quick_switch.dart';
|
||||
import '../domain/chat_quick_switch_order.dart';
|
||||
import '../ui/sessions/chat_sessions_controller.dart';
|
||||
import 'chat_quick_switch_keys.dart';
|
||||
import 'chat_quick_switch_row.dart';
|
||||
|
||||
/// Shows the chat quick switcher over the Chat destination: a search field
|
||||
/// with the keyboard in it above the open chats ([chatQuickSwitchCandidates]),
|
||||
/// narrowed and ranked as the operator types ([chatQuickSwitchMatches]). The
|
||||
/// first match is selected; Ctrl+N / Ctrl+P and Down / Up move the selection,
|
||||
/// wrapping, and Enter or a click chooses it. Esc closes it.
|
||||
/// most recently used first ([recent]), narrowed and ranked as the operator
|
||||
/// types ([chatQuickSwitchMatches]). With no query the chat used before
|
||||
/// [currentId] is selected, so the shortcut and then Enter go back to it;
|
||||
/// with one, the best match. A query also lists the closed chats it matches
|
||||
/// under "Closed", after the open ones. Ctrl+N / Ctrl+P and Down / Up move
|
||||
/// the selection, wrapping, and Enter or a click chooses it. Esc closes it.
|
||||
///
|
||||
/// A centred dialog on a wide app, a full-width bottom sheet on a phone, on
|
||||
/// the root navigator either way. Returns the route so a second press of the
|
||||
/// shortcut can close it; [onSelected] gets the chosen row once it closed.
|
||||
/// shortcut can close it; [onSelected] gets the chosen row once it closed (a
|
||||
/// closed row is still closed: the caller reopens it).
|
||||
ModalRoute<JsonMap> showChatQuickSwitch(
|
||||
BuildContext context, {
|
||||
required ChatSessionsController sessions,
|
||||
required ValueChanged<JsonMap> onSelected,
|
||||
String? Function(JsonMap session)? serverName,
|
||||
List<String> Function()? recent,
|
||||
String? currentId,
|
||||
}) {
|
||||
final navigator = Navigator.of(context, rootNavigator: true);
|
||||
Widget content(BuildContext context) =>
|
||||
ChatQuickSwitch(sessions: sessions, serverName: serverName);
|
||||
Widget content(BuildContext context) => ChatQuickSwitch(
|
||||
sessions: sessions,
|
||||
serverName: serverName,
|
||||
recent: recent?.call() ?? const [],
|
||||
currentId: currentId,
|
||||
);
|
||||
final ModalRoute<JsonMap> route = usesDesktopPopups(context)
|
||||
? DialogRoute<JsonMap>(
|
||||
context: context,
|
||||
@@ -76,11 +87,23 @@ void closeChatQuickSwitch(ModalRoute<JsonMap> route) {
|
||||
|
||||
/// The switcher's content: the field and the matching chats.
|
||||
class ChatQuickSwitch extends StatefulWidget {
|
||||
const ChatQuickSwitch({super.key, required this.sessions, this.serverName});
|
||||
const ChatQuickSwitch({
|
||||
super.key,
|
||||
required this.sessions,
|
||||
this.serverName,
|
||||
this.recent = const [],
|
||||
this.currentId,
|
||||
});
|
||||
|
||||
final ChatSessionsController sessions;
|
||||
final String? Function(JsonMap session)? serverName;
|
||||
|
||||
/// The chats used on this device, most recent first.
|
||||
final List<String> recent;
|
||||
|
||||
/// The chat shown when the switcher opened, if any.
|
||||
final String? currentId;
|
||||
|
||||
@override
|
||||
State<ChatQuickSwitch> createState() => _ChatQuickSwitchState();
|
||||
}
|
||||
@@ -88,16 +111,52 @@ class ChatQuickSwitch extends StatefulWidget {
|
||||
class _ChatQuickSwitchState extends State<ChatQuickSwitch> {
|
||||
final _query = TextEditingController();
|
||||
final _rowKeys = <String, GlobalKey>{};
|
||||
int _selected = 0;
|
||||
|
||||
/// The row the operator moved to; null keeps the initial selection
|
||||
/// ([chatQuickSwitchInitialSelection]).
|
||||
int? _moved;
|
||||
List<JsonMap> _shown = const [];
|
||||
|
||||
/// How many of [_shown] are open chats; the closed ones follow.
|
||||
int _openCount = 0;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_query.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _queryChanged(String _) => setState(() => _selected = 0);
|
||||
void _queryChanged(String _) => setState(() => _moved = null);
|
||||
|
||||
int get _selected =>
|
||||
_moved ??
|
||||
chatQuickSwitchInitialSelection(
|
||||
_shown,
|
||||
currentId: widget.currentId,
|
||||
emptyQuery: _query.text.trim().isEmpty,
|
||||
);
|
||||
|
||||
/// The open matches, then (with a query) the closed ones.
|
||||
void _match() {
|
||||
final query = _query.text;
|
||||
final open = chatQuickSwitchMatches(
|
||||
chatQuickSwitchByRecency(
|
||||
chatQuickSwitchCandidates(widget.sessions.sessions),
|
||||
widget.recent,
|
||||
),
|
||||
query,
|
||||
serverName: widget.serverName,
|
||||
);
|
||||
final closed = query.trim().isEmpty
|
||||
? const <JsonMap>[]
|
||||
: chatQuickSwitchMatches(
|
||||
chatQuickSwitchClosed(widget.sessions.sessions),
|
||||
query,
|
||||
serverName: widget.serverName,
|
||||
);
|
||||
_openCount = open.length;
|
||||
_shown = [...open, ...closed];
|
||||
}
|
||||
|
||||
/// Moves the selection [step] rows, wrapping, and scrolls it into view at
|
||||
/// the edge it moved towards.
|
||||
@@ -105,7 +164,7 @@ class _ChatQuickSwitchState extends State<ChatQuickSwitch> {
|
||||
if (_shown.isEmpty) return;
|
||||
final from = _selected.clamp(0, _shown.length - 1);
|
||||
final index = (from + step) % _shown.length;
|
||||
setState(() => _selected = index);
|
||||
setState(() => _moved = index);
|
||||
final id = '${_shown[index]['id'] ?? ''}';
|
||||
final policy = step < 0
|
||||
? ScrollPositionAlignmentPolicy.keepVisibleAtStart
|
||||
@@ -154,11 +213,7 @@ class _ChatQuickSwitchState extends State<ChatQuickSwitch> {
|
||||
final list = ListenableBuilder(
|
||||
listenable: widget.sessions,
|
||||
builder: (context, _) {
|
||||
_shown = chatQuickSwitchMatches(
|
||||
chatQuickSwitchCandidates(widget.sessions.sessions),
|
||||
_query.text,
|
||||
serverName: widget.serverName,
|
||||
);
|
||||
_match();
|
||||
if (_shown.isEmpty) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
@@ -181,7 +236,9 @@ class _ChatQuickSwitchState extends State<ChatQuickSwitch> {
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final (index, row) in _shown.indexed)
|
||||
for (final (index, row) in _shown.indexed) ...[
|
||||
if (index == _openCount)
|
||||
const ChatQuickSwitchSectionHeader(title: 'Closed'),
|
||||
ChatQuickSwitchRow(
|
||||
key: _rowKeys.putIfAbsent(
|
||||
'${row['id'] ?? ''}',
|
||||
@@ -190,8 +247,16 @@ class _ChatQuickSwitchState extends State<ChatQuickSwitch> {
|
||||
session: row,
|
||||
serverName: widget.serverName?.call(row),
|
||||
selected: index == selected,
|
||||
closed: index >= _openCount,
|
||||
markers: index >= _openCount
|
||||
? const []
|
||||
: chatQuickSwitchMarkers(
|
||||
row,
|
||||
unread: widget.sessions.isUnseen(row),
|
||||
),
|
||||
onTap: () => _choose(row),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
/// Where Ctrl+K / Alt+K pressed on the Chat destination goes: the mounted
|
||||
/// chat screen attaches its quick switcher here, and the app toggles it.
|
||||
/// Where an app-wide chat shortcut goes: Ctrl+K / Alt+K pressed on the Chat
|
||||
/// destination (the quick switcher), Alt+N (New chat) and Alt+J (the next
|
||||
/// chat needing the operator). The mounted chat screen attaches its action
|
||||
/// here, and the app runs it.
|
||||
class ChatQuickSwitchRequests {
|
||||
VoidCallback? _toggle;
|
||||
|
||||
|
||||
@@ -2,14 +2,17 @@ import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/chat_list_activity.dart';
|
||||
import '../domain/chat_quick_switch_order.dart';
|
||||
import '../domain/chat_sessions.dart';
|
||||
import '../ui/sessions/session_row_content.dart';
|
||||
import '../ui/sessions/session_row_style.dart';
|
||||
|
||||
/// One chat in the quick switcher: the list's avatar (harness mark in the
|
||||
/// chat's colour, with its running or awaiting badge), the title, and the
|
||||
/// folder with the machine it is on. The selected row takes the selection
|
||||
/// fill; hover and click work as on any list tile.
|
||||
/// folder with the machine it is on, then small [markers] (needs you,
|
||||
/// working, unread) and the star. A [closed] chat (listed under "Closed",
|
||||
/// reopened when chosen) shows no live state. The selected row takes the selection fill; hover
|
||||
/// and click work as on any list tile.
|
||||
class ChatQuickSwitchRow extends StatelessWidget {
|
||||
const ChatQuickSwitchRow({
|
||||
super.key,
|
||||
@@ -17,22 +20,31 @@ class ChatQuickSwitchRow extends StatelessWidget {
|
||||
required this.selected,
|
||||
required this.onTap,
|
||||
this.serverName,
|
||||
this.markers = const [],
|
||||
this.closed = false,
|
||||
});
|
||||
|
||||
final JsonMap session;
|
||||
final bool selected;
|
||||
final VoidCallback onTap;
|
||||
final String? serverName;
|
||||
final List<ChatQuickSwitchMarker> markers;
|
||||
final bool closed;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final id = '${session['id'] ?? ''}';
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final running = session['running'] == true;
|
||||
final running = !closed && session['running'] == true;
|
||||
final subtitle = [
|
||||
homeRelativePath('${session['directory'] ?? ''}'.trim()),
|
||||
?serverName,
|
||||
].where((part) => part.isNotEmpty).join(' · ');
|
||||
final trailing = [
|
||||
for (final marker in markers) ChatQuickSwitchMarkerIcon(marker: marker),
|
||||
if (session['starred'] == true)
|
||||
Icon(Icons.star, color: scheme.primary, semanticLabel: 'Starred'),
|
||||
];
|
||||
return ListTile(
|
||||
key: Key('chat-quick-switch-row-$id'),
|
||||
selected: selected,
|
||||
@@ -43,7 +55,7 @@ class ChatQuickSwitchRow extends StatelessWidget {
|
||||
session: session,
|
||||
running: running,
|
||||
backgroundTasks: running ? 0 : chatSessionBackgroundTasks(session),
|
||||
awaitingOperator: chatSessionAwaitingOperator(session),
|
||||
awaitingOperator: closed ? 0 : chatSessionAwaitingOperator(session),
|
||||
),
|
||||
title: Text(
|
||||
chatSessionTitle(session),
|
||||
@@ -53,10 +65,70 @@ class ChatQuickSwitchRow extends StatelessWidget {
|
||||
subtitle: subtitle.isEmpty
|
||||
? null
|
||||
: Text(subtitle, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
trailing: session['starred'] == true
|
||||
? Icon(Icons.star, color: scheme.primary, semanticLabel: 'Starred')
|
||||
: null,
|
||||
trailing: trailing.isEmpty
|
||||
? null
|
||||
: Row(mainAxisSize: MainAxisSize.min, spacing: 6, children: trailing),
|
||||
onTap: onTap,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// One row marker: a small icon in the state's colour, named by its tooltip
|
||||
/// and to assistive technology.
|
||||
class ChatQuickSwitchMarkerIcon extends StatelessWidget {
|
||||
const ChatQuickSwitchMarkerIcon({super.key, required this.marker});
|
||||
|
||||
final ChatQuickSwitchMarker marker;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final (icon, color) = switch (marker) {
|
||||
ChatQuickSwitchMarker.needsYou => (
|
||||
Icons.notifications_active,
|
||||
scheme.error,
|
||||
),
|
||||
ChatQuickSwitchMarker.working => (
|
||||
Icons.play_circle_outline,
|
||||
scheme.onSurfaceVariant,
|
||||
),
|
||||
ChatQuickSwitchMarker.unread => (Icons.circle, scheme.primary),
|
||||
};
|
||||
return Tooltip(
|
||||
message: marker.label,
|
||||
child: Icon(
|
||||
icon,
|
||||
key: Key('chat-quick-switch-marker-${marker.name}'),
|
||||
size: marker == ChatQuickSwitchMarker.unread ? 10 : 18,
|
||||
color: color,
|
||||
semanticLabel: marker.label,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The heading over the switcher's closed chats.
|
||||
class ChatQuickSwitchSectionHeader extends StatelessWidget {
|
||||
const ChatQuickSwitchSectionHeader({super.key, required this.title});
|
||||
|
||||
final String title;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Container(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
|
||||
child: Semantics(
|
||||
header: true,
|
||||
child: Text(
|
||||
title,
|
||||
key: const Key('chat-quick-switch-closed-header'),
|
||||
style: theme.textTheme.labelLarge?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -439,9 +439,10 @@ class ChatThreadController extends ChangeNotifier {
|
||||
return;
|
||||
}
|
||||
// A delta a history page already included is not added again.
|
||||
if (!_live.admit(body)) return;
|
||||
final admitted = _live.admit(body);
|
||||
if (admitted == null) return;
|
||||
final current = _thread;
|
||||
final next = applyChatEvent(current, body);
|
||||
final next = applyChatEvent(current, admitted);
|
||||
if (identical(next, current)) return;
|
||||
// A frame for a cached message is fresh state the next read must not drop.
|
||||
final changed = body['message_id'];
|
||||
|
||||
@@ -27,6 +27,7 @@ import '../ui/sessions/chat_color_picker.dart';
|
||||
import '../ui/sessions/session_actions.dart';
|
||||
import '../ui/sessions/session_row_content.dart';
|
||||
import '../ui/sessions/chat_adaptive.dart';
|
||||
import '../ui/transcript/chat_find_highlight.dart';
|
||||
import '../ui/transcript/chat_markdown_view.dart';
|
||||
import '../ui/transcript/chat_message_bubble.dart';
|
||||
import '../ui/transcript/chat_message_view.dart';
|
||||
@@ -50,6 +51,7 @@ import 'chat_session_section.dart';
|
||||
import 'chat_background_tasks.dart';
|
||||
import 'chat_command_actions.dart';
|
||||
import 'chat_composer_bar.dart';
|
||||
import 'chat_find_host.dart';
|
||||
import 'chat_composer_controller.dart';
|
||||
import 'chat_escape_stop.dart';
|
||||
import 'chat_delivery_indicator.dart';
|
||||
@@ -241,7 +243,26 @@ class ChatThreadView extends StatefulWidget {
|
||||
State<ChatThreadView> createState() => _ChatThreadViewState();
|
||||
}
|
||||
|
||||
class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
class _ChatThreadViewState extends State<ChatThreadView> with ChatFindHost {
|
||||
@override
|
||||
ScrollController get findScroll => _scroll;
|
||||
@override
|
||||
ChatThreadController get findThread => _controller;
|
||||
|
||||
@override
|
||||
void findReleaseFollow() {
|
||||
if (!_following) return;
|
||||
setState(() {
|
||||
_following = false;
|
||||
_newestAtRelease = _newestMessageId();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void findSettleFollow() {
|
||||
if (_scroll.hasClients) _updateFollow(_scroll.position);
|
||||
}
|
||||
|
||||
late ChatThreadController _controller = _attach();
|
||||
late ChatComposerController _composer = _attachComposer();
|
||||
|
||||
@@ -831,6 +852,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
_saveTranscript(widget.transcripts, widget.sessionId);
|
||||
widget.paneCommands?.removeListener(_takeCommands);
|
||||
widget.paneCommands?.setFinished(widget.sessionId, false);
|
||||
disposeFind();
|
||||
_scroll.dispose();
|
||||
widget.onComposerDisposed?.call(_composer);
|
||||
_composer.dispose();
|
||||
@@ -1247,6 +1269,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
// across paging and streaming.
|
||||
final keys = _rowKeys.forRows(rows);
|
||||
final split = _splitFor(rows);
|
||||
findTranscript(rows, keys);
|
||||
final initialLoad = !_controller.loaded && _controller.loading;
|
||||
final historyNotice = _noticeOf(
|
||||
notices,
|
||||
@@ -1344,32 +1367,35 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
// Slivers mount only visible rows. Defer constructing
|
||||
// their chips and checking cached widgets until then,
|
||||
// rather than visiting the entire history per delta.
|
||||
child: ChatDayDivided(
|
||||
day: days[index],
|
||||
// An answer row starts at the gutter; the divider
|
||||
// keeps to the reading column.
|
||||
inset: rows[index]['kind'] == 'assistant'
|
||||
? gutter
|
||||
: 0,
|
||||
child: ChatTranscriptRowSelection(
|
||||
child: ChatCopyGutter(
|
||||
width: rows[index]['kind'] == 'assistant'
|
||||
? gutter
|
||||
: 0,
|
||||
child: Builder(
|
||||
builder: (_) => _entering(
|
||||
rows[index],
|
||||
_transcriptRow(
|
||||
child: ChatFindRow(
|
||||
rowKey: keys[index],
|
||||
child: ChatDayDivided(
|
||||
day: days[index],
|
||||
// An answer row starts at the gutter; the divider
|
||||
// keeps to the reading column.
|
||||
inset: rows[index]['kind'] == 'assistant'
|
||||
? gutter
|
||||
: 0,
|
||||
child: ChatTranscriptRowSelection(
|
||||
child: ChatCopyGutter(
|
||||
width: rows[index]['kind'] == 'assistant'
|
||||
? gutter
|
||||
: 0,
|
||||
child: Builder(
|
||||
builder: (_) => _entering(
|
||||
rows[index],
|
||||
keys[index],
|
||||
onDismissCompaction:
|
||||
compactionNotice != null &&
|
||||
chatNoticeActivityCondition(
|
||||
rows[index],
|
||||
) ==
|
||||
compactionNotice.condition
|
||||
? () => _dismiss(compactionNotice)
|
||||
: null,
|
||||
_transcriptRow(
|
||||
rows[index],
|
||||
keys[index],
|
||||
onDismissCompaction:
|
||||
compactionNotice != null &&
|
||||
chatNoticeActivityCondition(
|
||||
rows[index],
|
||||
) ==
|
||||
compactionNotice.condition
|
||||
? () => _dismiss(compactionNotice)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -1385,108 +1411,114 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
// the viewport itself ends above the composer.
|
||||
// Bottom-anchored at the split row, the newest rows are
|
||||
// laid out first and older ones only when scrolled to.
|
||||
ChatTranscriptSelectionArea(
|
||||
child: ChatTranscriptScrollView(
|
||||
key: ValueKey<String>(
|
||||
'chat-thread-${widget.sessionId}',
|
||||
),
|
||||
controller: _scroll,
|
||||
splitAfter: split < 0
|
||||
? null
|
||||
: ValueKey<String>(keys[split]),
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
side - gutter,
|
||||
media.top + 8,
|
||||
side,
|
||||
8,
|
||||
),
|
||||
children: chatCopyGutterInset(gutter, transcript, [
|
||||
if (initialLoad)
|
||||
Padding(
|
||||
key: const Key('chat-thread-loading'),
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: const Center(child: AppSpinner()),
|
||||
),
|
||||
if (_controller.hasMore)
|
||||
Padding(
|
||||
key: const Key('chat-load-older'),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
findScope(
|
||||
ChatTranscriptSelectionArea(
|
||||
child: ChatTranscriptScrollView(
|
||||
key: ValueKey<String>(
|
||||
'chat-thread-${widget.sessionId}',
|
||||
),
|
||||
controller: _scroll,
|
||||
splitAfter: split < 0
|
||||
? null
|
||||
: ValueKey<String>(keys[split]),
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
side - gutter,
|
||||
media.top + 8,
|
||||
side,
|
||||
8,
|
||||
),
|
||||
children: chatCopyGutterInset(gutter, transcript, [
|
||||
if (initialLoad)
|
||||
Padding(
|
||||
key: const Key('chat-thread-loading'),
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: const Center(child: AppSpinner()),
|
||||
),
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: TextButton(
|
||||
onPressed: _controller.loading
|
||||
? null
|
||||
: _controller.loadOlder,
|
||||
child: const Text('Load older'),
|
||||
if (_controller.hasMore)
|
||||
Padding(
|
||||
key: const Key('chat-load-older'),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
),
|
||||
child: Align(
|
||||
alignment:
|
||||
AlignmentDirectional.centerStart,
|
||||
child: TextButton(
|
||||
onPressed: _controller.loading
|
||||
? null
|
||||
: _controller.loadOlder,
|
||||
child: const Text('Load older'),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (historyNotice != null)
|
||||
_ChatNoticeLine(
|
||||
key: const Key('chat-history-error'),
|
||||
notice: historyNotice,
|
||||
onDismiss: _dismiss,
|
||||
onRetry: _controller.load,
|
||||
),
|
||||
if (liveNotice != null)
|
||||
_ChatNoticeLine(
|
||||
key: const Key('chat-live-error'),
|
||||
notice: liveNotice,
|
||||
onDismiss: _dismiss,
|
||||
onRetry: _controller.resync,
|
||||
),
|
||||
if (_controller.loaded &&
|
||||
allRows.isEmpty &&
|
||||
allNotices.isEmpty &&
|
||||
_commandNotices.isEmpty &&
|
||||
_controller.error == null)
|
||||
const Padding(
|
||||
key: Key('chat-thread-empty'),
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Text('No messages in this chat yet.'),
|
||||
),
|
||||
...transcript,
|
||||
// Messages the server holds queued (one sent before
|
||||
// a reload, or from another device) follow the
|
||||
// transcript: none has reached the harness yet.
|
||||
for (final prompt
|
||||
in _controller.queuedOutsideTranscript)
|
||||
Padding(
|
||||
key: ValueKey<String>(
|
||||
'chat-queued-${prompt['operation_id']}',
|
||||
if (historyNotice != null)
|
||||
_ChatNoticeLine(
|
||||
key: const Key('chat-history-error'),
|
||||
notice: historyNotice,
|
||||
onDismiss: _dismiss,
|
||||
onRetry: _controller.load,
|
||||
),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
if (liveNotice != null)
|
||||
_ChatNoticeLine(
|
||||
key: const Key('chat-live-error'),
|
||||
notice: liveNotice,
|
||||
onDismiss: _dismiss,
|
||||
onRetry: _controller.resync,
|
||||
),
|
||||
child: _queuedRow(prompt),
|
||||
),
|
||||
// Messages the server has not accepted follow the
|
||||
// transcript until they are retried or edited.
|
||||
for (final send in _composer.deliveries.unsent)
|
||||
Padding(
|
||||
key: ValueKey<String>(
|
||||
'chat-unsent-${send.operationId}',
|
||||
if (_controller.loaded &&
|
||||
allRows.isEmpty &&
|
||||
allNotices.isEmpty &&
|
||||
_commandNotices.isEmpty &&
|
||||
_controller.error == null)
|
||||
const Padding(
|
||||
key: Key('chat-thread-empty'),
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Text(
|
||||
'No messages in this chat yet.',
|
||||
),
|
||||
),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
...transcript,
|
||||
// Messages the server holds queued (one sent before
|
||||
// a reload, or from another device) follow the
|
||||
// transcript: none has reached the harness yet.
|
||||
for (final prompt
|
||||
in _controller.queuedOutsideTranscript)
|
||||
Padding(
|
||||
key: ValueKey<String>(
|
||||
'chat-queued-${prompt['operation_id']}',
|
||||
),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
),
|
||||
child: _queuedRow(prompt),
|
||||
),
|
||||
child: _unsentRow(send),
|
||||
),
|
||||
// The conversation's own command lines sit after the
|
||||
// turns, as on the web; they are never bubbles.
|
||||
for (final notice in _commandNotices)
|
||||
_ChatNoticeLine(
|
||||
key: ValueKey<String>(
|
||||
'chat-command-notice-${notice.condition}',
|
||||
// Messages the server has not accepted follow the
|
||||
// transcript until they are retried or edited.
|
||||
for (final send in _composer.deliveries.unsent)
|
||||
Padding(
|
||||
key: ValueKey<String>(
|
||||
'chat-unsent-${send.operationId}',
|
||||
),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
),
|
||||
child: _unsentRow(send),
|
||||
),
|
||||
notice: notice,
|
||||
onDismiss: _dismiss,
|
||||
),
|
||||
]),
|
||||
// The conversation's own command lines sit after the
|
||||
// turns, as on the web; they are never bubbles.
|
||||
for (final notice in _commandNotices)
|
||||
_ChatNoticeLine(
|
||||
key: ValueKey<String>(
|
||||
'chat-command-notice-${notice.condition}',
|
||||
),
|
||||
notice: notice,
|
||||
onDismiss: _dismiss,
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
),
|
||||
?findBar(top: media.top + 8, end: side + 8),
|
||||
if (showJump)
|
||||
PositionedDirectional(
|
||||
end: side + 16,
|
||||
@@ -1511,10 +1543,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
// scrolls under fixed bars.
|
||||
// Two Escape presses stop a running turn while the conversation has
|
||||
// the keyboard; the wheel over the page still scrolls it.
|
||||
final column = ChatEscapeStop(
|
||||
running: _controller.running,
|
||||
onStop: _stopTurn,
|
||||
child: VerticalWheelForwarder(controller: _scroll, child: page),
|
||||
final column = Focus(
|
||||
canRequestFocus: false,
|
||||
skipTraversal: true,
|
||||
onKeyEvent: findKey,
|
||||
child: ChatEscapeStop(
|
||||
running: _controller.running,
|
||||
onStop: _stopTurn,
|
||||
child: VerticalWheelForwarder(controller: _scroll, child: page),
|
||||
),
|
||||
);
|
||||
final wideFiles =
|
||||
_filesVisible && MediaQuery.sizeOf(context).width >= 700;
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../../core/servers/server_scope.dart';
|
||||
|
||||
/// Where the chats' most-recently-used order is kept on this device.
|
||||
abstract interface class ChatRecencyStore {
|
||||
Future<List<String>> read();
|
||||
|
||||
Future<void> write(List<String> ids);
|
||||
}
|
||||
|
||||
/// The chats this device used, most recent first, for the quick switcher's
|
||||
/// order with no query. A chat counts as used when it is opened or its pane
|
||||
/// takes focus ([touch]). The list is read once, lazily, and written back on
|
||||
/// every change; a chat touched before the read finished stays in front.
|
||||
class ChatRecency {
|
||||
ChatRecency({ChatRecencyStore? store, this.limit = 200})
|
||||
: _store = store ?? MemoryChatRecencyStore();
|
||||
|
||||
final ChatRecencyStore _store;
|
||||
|
||||
/// How many chats are remembered.
|
||||
final int limit;
|
||||
|
||||
List<String> _ids = const [];
|
||||
Future<void>? _loading;
|
||||
|
||||
/// The remembered chats, most recent first.
|
||||
List<String> get ids => _ids;
|
||||
|
||||
/// Reads the stored order once; later calls return the same read.
|
||||
Future<void> load() => _loading ??= _read();
|
||||
|
||||
Future<void> _read() async {
|
||||
List<String> stored;
|
||||
try {
|
||||
stored = await _store.read();
|
||||
} catch (_) {
|
||||
stored = const [];
|
||||
}
|
||||
_ids = _merged(_ids, stored);
|
||||
}
|
||||
|
||||
/// [id] was opened or focused: it moves to the front.
|
||||
void touch(String id) {
|
||||
if (id.isEmpty || (_ids.isNotEmpty && _ids.first == id)) return;
|
||||
_ids = _merged([id], _ids);
|
||||
unawaited(load().then((_) => _write()));
|
||||
}
|
||||
|
||||
Future<void> _write() async {
|
||||
try {
|
||||
await _store.write(_ids);
|
||||
} catch (_) {
|
||||
// The order is a convenience; the switcher still lists every chat.
|
||||
}
|
||||
}
|
||||
|
||||
List<String> _merged(List<String> front, List<String> rest) {
|
||||
final seen = <String>{};
|
||||
return [
|
||||
for (final id in [...front, ...rest])
|
||||
if (id.isNotEmpty && seen.add(id)) id,
|
||||
].take(limit).toList(growable: false);
|
||||
}
|
||||
}
|
||||
|
||||
class SharedPreferencesChatRecencyStore implements ChatRecencyStore {
|
||||
const SharedPreferencesChatRecencyStore({this.serverScope = ''});
|
||||
|
||||
final String serverScope;
|
||||
|
||||
String get _key => scopedServerKey('pipelines.chat.recency.v1', serverScope);
|
||||
|
||||
@override
|
||||
Future<List<String>> read() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getStringList(_key) ?? const [];
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> write(List<String> ids) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setStringList(_key, ids);
|
||||
}
|
||||
}
|
||||
|
||||
/// An in-memory store for tests and hosts without preferences.
|
||||
class MemoryChatRecencyStore implements ChatRecencyStore {
|
||||
MemoryChatRecencyStore([List<String>? ids]) : ids = ids ?? [];
|
||||
|
||||
List<String> ids;
|
||||
|
||||
@override
|
||||
Future<List<String>> read() async => List.of(ids);
|
||||
|
||||
@override
|
||||
Future<void> write(List<String> ids) async => this.ids = List.of(ids);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'chat_list_activity.dart';
|
||||
import 'chat_sessions.dart';
|
||||
|
||||
/// Whether an open chat needs the operator: it waits on an approval or a
|
||||
/// question, has replies not read yet ([unread]), or an action on it failed
|
||||
/// ([failed]).
|
||||
bool chatNeedsAttention(
|
||||
JsonMap session, {
|
||||
required bool unread,
|
||||
required bool failed,
|
||||
}) => chatSessionAwaitingOperator(session) > 0 || unread || failed;
|
||||
|
||||
/// The chat Alt+J opens: the next open chat after [currentId], in the order
|
||||
/// the list draws them (starred, then by directory; folded sections count),
|
||||
/// that [needsAttention], wrapping around. With no current chat (or one not
|
||||
/// among the open chats) the first such chat. Null when no other chat needs
|
||||
/// the operator.
|
||||
JsonMap? chatNextNeedingAttention(
|
||||
List<JsonMap> sessions,
|
||||
String? currentId,
|
||||
bool Function(JsonMap session) needsAttention,
|
||||
) {
|
||||
final open = chatSessionsInListOrder(
|
||||
chatSessionSections(
|
||||
sessions
|
||||
.where((row) => row['closed_at'] == null && row['closed'] != true)
|
||||
.toList(),
|
||||
),
|
||||
isOpen: (_) => true,
|
||||
);
|
||||
if (open.isEmpty) return null;
|
||||
final at = open.indexWhere((row) => '${row['id'] ?? ''}' == currentId);
|
||||
for (var step = 1; step <= open.length; step++) {
|
||||
final row = open[(at + step) % open.length];
|
||||
if ('${row['id'] ?? ''}' == currentId) continue;
|
||||
if (needsAttention(row)) return row;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// One piece of transcript text find searches, as the transcript shows it:
|
||||
/// a user turn's text (its text parts joined by line breaks, as its bubble
|
||||
/// draws them) or one text part of an answer. [rowKey] is the transcript
|
||||
/// row's stable key; [text] is exactly the string the row renders.
|
||||
class ChatFindUnit {
|
||||
const ChatFindUnit(this.rowIndex, this.rowKey, this.text, this.messageIds);
|
||||
|
||||
final int rowIndex;
|
||||
final String rowKey;
|
||||
final String text;
|
||||
|
||||
/// The stored messages the row holds.
|
||||
final List<String> messageIds;
|
||||
}
|
||||
|
||||
/// A match's character range in its unit's text.
|
||||
typedef ChatFindRange = ({int start, int end});
|
||||
|
||||
/// One match in the loaded transcript.
|
||||
class ChatFindMatch {
|
||||
const ChatFindMatch(this.unit, this.start, this.end, this.ordinal);
|
||||
|
||||
final ChatFindUnit unit;
|
||||
final int start;
|
||||
final int end;
|
||||
|
||||
/// Which occurrence in [unit] this is, from its start.
|
||||
final int ordinal;
|
||||
|
||||
String get rowKey => unit.rowKey;
|
||||
|
||||
/// Whether [other] is the same occurrence in the same text.
|
||||
bool sameAs(ChatFindMatch other) =>
|
||||
other.rowKey == rowKey &&
|
||||
other.unit.text == unit.text &&
|
||||
other.ordinal == ordinal;
|
||||
}
|
||||
|
||||
/// A match the server found in a message the transcript has not loaded yet.
|
||||
class ChatFindRemoteHit {
|
||||
const ChatFindRemoteHit(this.messageId, this.part, this.offset);
|
||||
|
||||
final String messageId;
|
||||
final int part;
|
||||
final int offset;
|
||||
|
||||
/// The hits of a scoped chat search reply, newest message first.
|
||||
static List<ChatFindRemoteHit> fromReply(JsonMap reply) {
|
||||
final results = reply['search_results'];
|
||||
final list = results is Map ? results['results'] : null;
|
||||
if (list is! List) return const [];
|
||||
return [
|
||||
for (final result in list)
|
||||
if (result is Map && result['chat'] is Map)
|
||||
ChatFindRemoteHit(
|
||||
'${(result['chat'] as Map)['message_id'] ?? ''}',
|
||||
_int((result['chat'] as Map)['part']),
|
||||
_int((result['chat'] as Map)['offset']),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
static int _int(Object? value) => value is num ? value.toInt() : 0;
|
||||
}
|
||||
|
||||
/// The text units of transcript [rows] (keyed by [keys]), in display order.
|
||||
/// Only what reads as conversation is searched: user turns and the text of
|
||||
/// answers, not activity, cards or notices.
|
||||
List<ChatFindUnit> chatFindUnits(List<JsonMap> rows, List<String> keys) {
|
||||
final units = <ChatFindUnit>[];
|
||||
for (var index = 0; index < rows.length && index < keys.length; index++) {
|
||||
final row = rows[index];
|
||||
final kind = row['kind'];
|
||||
if (kind == 'user') {
|
||||
final message = row['message'] is Map ? row['message'] as Map : row;
|
||||
final text = _textParts(message).join('\n');
|
||||
if (text.trim().isEmpty) continue;
|
||||
final id = '${row['key'] ?? message['id'] ?? ''}';
|
||||
units.add(ChatFindUnit(index, keys[index], text, [id]));
|
||||
} else if (kind == 'assistant') {
|
||||
final ids = [
|
||||
for (final id in row['messageIds'] as List? ?? const []) '$id',
|
||||
];
|
||||
for (final text in _textParts(row)) {
|
||||
if (text.trim().isEmpty) continue;
|
||||
units.add(ChatFindUnit(index, keys[index], text, ids));
|
||||
}
|
||||
}
|
||||
}
|
||||
return units;
|
||||
}
|
||||
|
||||
List<String> _textParts(Map<dynamic, dynamic> source) {
|
||||
final parts = source['parts'];
|
||||
if (parts is! List) return const [];
|
||||
return [
|
||||
for (final part in parts)
|
||||
if (part is Map &&
|
||||
(part['type'] == null || part['type'] == 'text') &&
|
||||
part['text'] is String)
|
||||
part['text'] as String,
|
||||
];
|
||||
}
|
||||
|
||||
/// The non-overlapping occurrences of [query] in [text].
|
||||
List<ChatFindRange> chatFindRanges(
|
||||
String text,
|
||||
String query, {
|
||||
required bool caseSensitive,
|
||||
}) {
|
||||
if (query.isEmpty || text.length < query.length) return const [];
|
||||
final pattern = RegExp(RegExp.escape(query), caseSensitive: caseSensitive);
|
||||
return [
|
||||
for (final match in pattern.allMatches(text))
|
||||
(start: match.start, end: match.end),
|
||||
];
|
||||
}
|
||||
|
||||
/// Every match of [query] in [units], in display order (oldest first).
|
||||
List<ChatFindMatch> chatFindMatches(
|
||||
List<ChatFindUnit> units,
|
||||
String query, {
|
||||
required bool caseSensitive,
|
||||
int cap = chatFindLocalCap,
|
||||
}) {
|
||||
final matches = <ChatFindMatch>[];
|
||||
for (final unit in units) {
|
||||
var ordinal = 0;
|
||||
for (final range in chatFindRanges(
|
||||
unit.text,
|
||||
query,
|
||||
caseSensitive: caseSensitive,
|
||||
)) {
|
||||
matches.add(ChatFindMatch(unit, range.start, range.end, ordinal++));
|
||||
if (matches.length >= cap) return matches;
|
||||
}
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
|
||||
/// How many matches find counts in the loaded transcript, and in history
|
||||
/// it has not loaded, before it reports "N+".
|
||||
const chatFindLocalCap = 2000;
|
||||
const chatFindRemoteCap = 1000;
|
||||
@@ -28,17 +28,21 @@ class ChatLiveFrames {
|
||||
/// Stops recording for a read that will not be applied.
|
||||
void abandon(List<JsonMap> frames) => _reads.remove(frames);
|
||||
|
||||
/// Whether [frame] should be folded into the held transcript, recording it
|
||||
/// for every read in flight. A frame with no number is always folded.
|
||||
bool admit(JsonMap frame) {
|
||||
/// The part of [frame] to fold into the held transcript, recording it for
|
||||
/// every read in flight, or null when a page already included all of it. A
|
||||
/// frame with no number is always folded whole; a joined frame whose first
|
||||
/// deltas were already included is trimmed to the rest.
|
||||
JsonMap? admit(JsonMap frame) {
|
||||
final seq = frame['seq'];
|
||||
if (seq is! int) return true;
|
||||
if (seq <= _included) return false;
|
||||
if (seq is! int) return frame;
|
||||
if (seq <= _included) return null;
|
||||
final admitted = chatDeltasAfter(frame, _included);
|
||||
if (admitted == null) return null;
|
||||
_included = seq;
|
||||
for (final read in _reads) {
|
||||
read.add(frame);
|
||||
read.add(admitted);
|
||||
}
|
||||
return true;
|
||||
return admitted;
|
||||
}
|
||||
|
||||
/// [messages] after applying [page]: frames recorded during the read that
|
||||
@@ -65,9 +69,11 @@ class ChatLiveFrames {
|
||||
};
|
||||
}
|
||||
var thread = <String, dynamic>{'messages': messages};
|
||||
for (final frame in frames) {
|
||||
final seq = frame['seq'];
|
||||
for (final recorded in frames) {
|
||||
final seq = recorded['seq'];
|
||||
if (seq is! int || seq <= liveSeq) continue;
|
||||
final frame = chatDeltasAfter(recorded, liveSeq);
|
||||
if (frame == null) continue;
|
||||
final messageId = frame['message_id'];
|
||||
if (!replaced(messageId)) continue;
|
||||
final part = frame['part'];
|
||||
@@ -82,3 +88,35 @@ class ChatLiveFrames {
|
||||
return chatMessageList(thread['messages']);
|
||||
}
|
||||
}
|
||||
|
||||
/// [frame] without the numbered deltas up to [included].
|
||||
///
|
||||
/// A server joins consecutive deltas of one part while a slow client's queue
|
||||
/// is backed up: the joined frame's `seq_from`..`seq` names the deltas it holds
|
||||
/// and `delta_lens` each one's length in UTF-16 code units. When a history page
|
||||
/// already holds a prefix of them, only the rest is new. A plain frame (or one
|
||||
/// wholly past [included]) is returned unchanged; null means nothing in it is
|
||||
/// new.
|
||||
JsonMap? chatDeltasAfter(JsonMap frame, int included) {
|
||||
final seq = frame['seq'];
|
||||
if (seq is! int) return frame;
|
||||
if (seq <= included) return null;
|
||||
final from = frame['seq_from'];
|
||||
final lens = frame['delta_lens'];
|
||||
if (from is! int || from > included || lens is! List) return frame;
|
||||
final delta = frame['delta'];
|
||||
if (delta is! String || lens.length != seq - from + 1) return frame;
|
||||
var cut = 0;
|
||||
for (var i = 0; i <= included - from; i++) {
|
||||
final length = lens[i];
|
||||
if (length is! int || length < 0) return frame;
|
||||
cut += length;
|
||||
}
|
||||
if (cut >= delta.length) return null;
|
||||
return {
|
||||
...frame,
|
||||
'delta': delta.substring(cut),
|
||||
'seq_from': included + 1,
|
||||
'delta_lens': lens.sublist(included - from + 1),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'chat_list_activity.dart';
|
||||
|
||||
/// [candidates] most recently used first: each chat in [recent] (most recent
|
||||
/// first) by its place there, then the chats never used on this device in
|
||||
/// [candidates]' own order.
|
||||
List<JsonMap> chatQuickSwitchByRecency(
|
||||
List<JsonMap> candidates,
|
||||
List<String> recent,
|
||||
) {
|
||||
final rank = {for (final (index, id) in recent.indexed) id: index};
|
||||
final indexed = candidates.indexed.toList()
|
||||
..sort((a, b) {
|
||||
final ra = rank['${a.$2['id'] ?? ''}'];
|
||||
final rb = rank['${b.$2['id'] ?? ''}'];
|
||||
if (ra != null && rb != null) return ra - rb;
|
||||
if (ra != null) return -1;
|
||||
if (rb != null) return 1;
|
||||
return a.$1 - b.$1;
|
||||
});
|
||||
return [for (final (_, row) in indexed) row];
|
||||
}
|
||||
|
||||
/// Whether [row] is a closed chat.
|
||||
bool chatQuickSwitchIsClosed(JsonMap row) =>
|
||||
row['closed_at'] != null || row['closed'] == true;
|
||||
|
||||
/// The closed chats the switcher offers under "Closed" once a query matches
|
||||
/// them, most recently closed first.
|
||||
List<JsonMap> chatQuickSwitchClosed(List<JsonMap> sessions) {
|
||||
int closedAt(JsonMap row) {
|
||||
final at = row['closed_at'];
|
||||
return at is num ? at.toInt() : 0;
|
||||
}
|
||||
|
||||
return sessions.where(chatQuickSwitchIsClosed).toList()
|
||||
..sort((a, b) => closedAt(b) - closedAt(a));
|
||||
}
|
||||
|
||||
/// The row the switcher selects first: with no query, the first chat that is
|
||||
/// not [currentId] (the one used before it, so the shortcut and then Enter go
|
||||
/// back there, as Alt+Tab does); with a query, the best match.
|
||||
int chatQuickSwitchInitialSelection(
|
||||
List<JsonMap> shown, {
|
||||
required String? currentId,
|
||||
required bool emptyQuery,
|
||||
}) {
|
||||
if (!emptyQuery || currentId == null) return 0;
|
||||
final index = shown.indexWhere((row) => '${row['id'] ?? ''}' != currentId);
|
||||
return index < 0 ? 0 : index;
|
||||
}
|
||||
|
||||
/// What a switcher row marks about its chat, most urgent first.
|
||||
enum ChatQuickSwitchMarker {
|
||||
needsYou('Needs you'),
|
||||
working('Working'),
|
||||
unread('Unread');
|
||||
|
||||
const ChatQuickSwitchMarker(this.label);
|
||||
|
||||
final String label;
|
||||
}
|
||||
|
||||
/// [session]'s markers: approvals or questions waiting on the operator, a
|
||||
/// turn running, and replies not read yet ([unread], as the list reads it).
|
||||
List<ChatQuickSwitchMarker> chatQuickSwitchMarkers(
|
||||
JsonMap session, {
|
||||
required bool unread,
|
||||
}) => [
|
||||
if (chatSessionAwaitingOperator(session) > 0) ChatQuickSwitchMarker.needsYou,
|
||||
if (session['running'] == true) ChatQuickSwitchMarker.working,
|
||||
if (unread) ChatQuickSwitchMarker.unread,
|
||||
];
|
||||
@@ -50,7 +50,9 @@ import 'ui/sessions/chat_adaptive.dart';
|
||||
import 'conversation/composer_focus_request.dart';
|
||||
import 'conversation/composer_selection_focus.dart';
|
||||
import 'domain/chat_commands.dart';
|
||||
import 'domain/chat_attention_cycle.dart';
|
||||
import 'domain/chat_cycle.dart';
|
||||
import 'domain/chat_quick_switch_order.dart';
|
||||
import '../terminal/terminal_scope.dart';
|
||||
import 'domain/chat_colors.dart';
|
||||
import 'ui/sessions/chat_color_palette.dart';
|
||||
@@ -59,6 +61,7 @@ import 'ui/sessions/chat_sessions_controller.dart';
|
||||
import 'ui/sessions/chat_sessions_screen.dart';
|
||||
import '../../ui/input/keyboard_owner.dart';
|
||||
|
||||
part 'chat_screen_attention.dart';
|
||||
part 'chat_screen_float.dart';
|
||||
part 'chat_screen_pane_menu.dart';
|
||||
part 'chat_screen_keys.dart';
|
||||
@@ -121,7 +124,8 @@ class _ChatScreenState extends State<ChatScreen>
|
||||
_ChatScreenKeys,
|
||||
_ChatScreenFloat,
|
||||
_ChatScreenPaneMenu,
|
||||
_ChatScreenQuickSwitch {
|
||||
_ChatScreenQuickSwitch,
|
||||
_ChatScreenAttention {
|
||||
/// The chats' shared state: the list, opened rows, accepted models,
|
||||
/// transcript positions and caches (see [ChatRuntime]).
|
||||
@override
|
||||
@@ -161,11 +165,13 @@ class _ChatScreenState extends State<ChatScreen>
|
||||
_runtime.addSessionReplacedListener(_replacedElsewhere);
|
||||
_bindWindows();
|
||||
_bindQuickSwitch();
|
||||
_bindAttention();
|
||||
final initial = widget.initialSessionId;
|
||||
if (initial != null && initial.isNotEmpty) {
|
||||
_workspace.open(initial);
|
||||
_workspaceVisible = true;
|
||||
_publishedWorkspaceSession = initial;
|
||||
_runtime.recency.touch(initial);
|
||||
}
|
||||
_workspace.addListener(_workspaceChanged);
|
||||
_bindWorkspacePersistence();
|
||||
@@ -256,6 +262,7 @@ class _ChatScreenState extends State<ChatScreen>
|
||||
_openedSessions[id] = session;
|
||||
_workspaceVisible = true;
|
||||
_workspace.open(id);
|
||||
_runtime.recency.touch(id);
|
||||
// A docked chat chosen while chat windows float over the workspace would
|
||||
// open behind them: hide the windows so the chosen chat is seen.
|
||||
final windows = widget.windows;
|
||||
@@ -465,6 +472,7 @@ class _ChatScreenState extends State<ChatScreen>
|
||||
_openWorkspace?.dispose();
|
||||
_unbindWindows();
|
||||
_unbindQuickSwitch();
|
||||
_unbindAttention();
|
||||
_workspace.removeListener(_workspaceChanged);
|
||||
_workspace.dispose();
|
||||
_sessions.removeListener(_nextChanged);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import '../../../../ui/layout/app_list_row.dart';
|
||||
import '../../../../core/servers/chat/federated_chat_gateway.dart';
|
||||
import '../../../../core/servers/server_context.dart';
|
||||
import 'dart:async';
|
||||
@@ -127,7 +128,18 @@ class ChatCompactSidebar extends StatelessWidget {
|
||||
duration: MediaQuery.disableAnimationsOf(context)
|
||||
? Duration.zero
|
||||
: const Duration(milliseconds: 200),
|
||||
color: selected ? Colors.transparent : color.withValues(alpha: .07),
|
||||
// The lists' shared open-row style: the tonal fill and one leading
|
||||
// bar in the chat's colour.
|
||||
color: selected
|
||||
? AppListRow.selectedColor(context)
|
||||
: color.withValues(alpha: .07),
|
||||
foregroundDecoration: selected
|
||||
? BoxDecoration(
|
||||
border: BorderDirectional(
|
||||
start: BorderSide(color: color, width: kAppListRowBarWidth),
|
||||
),
|
||||
)
|
||||
: null,
|
||||
child: Draggable<JsonMap>(
|
||||
// A mouse drags at once (a click still opens the chat); the chip
|
||||
// follows the pointer.
|
||||
|
||||
@@ -143,6 +143,10 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
/// Another device changed a chat's shared colour, star or title: the row
|
||||
/// takes the server's values at once, with no re-list. Each field the
|
||||
/// registry row omits is cleared, since omitted means unset on the wire.
|
||||
/// The server sends these pushes concurrently, so they can arrive out of
|
||||
/// order: one whose `revision` is older than the row held here is stale and
|
||||
/// ignored (a row or push without a revision, from an older server, is
|
||||
/// always applied).
|
||||
///
|
||||
/// A row naming `previous_id` is a chat another device moved to a fresh
|
||||
/// session (`/new`): it replaces that row in place and [onSessionReplaced]
|
||||
@@ -165,8 +169,14 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
if ('${row['id'] ?? ''}' == id)
|
||||
() {
|
||||
found = true;
|
||||
if (chatSessionPushIsStale(row, changed)) return row;
|
||||
final next = <String, dynamic>{...row};
|
||||
for (final key in const ['color', 'starred', 'starred_at']) {
|
||||
for (final key in const [
|
||||
'color',
|
||||
'starred',
|
||||
'starred_at',
|
||||
'revision',
|
||||
]) {
|
||||
if (changed.containsKey(key)) {
|
||||
next[key] = changed[key];
|
||||
} else {
|
||||
@@ -404,8 +414,14 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
final runningRevision = _runningRevision;
|
||||
final sessions = await repository.sessions();
|
||||
if (generation != _generation) return;
|
||||
// A push applied while this list was read can be newer than its row.
|
||||
final held = {for (final row in _sessions) '${row['id'] ?? ''}': row};
|
||||
_sessions = [
|
||||
for (final row in sessions) _withActivity(row, runningRevision),
|
||||
for (final row in sessions)
|
||||
_withActivity(
|
||||
newerChatSessionMetadata(row, held['${row['id'] ?? ''}']),
|
||||
runningRevision,
|
||||
),
|
||||
];
|
||||
_seedLocal();
|
||||
_loading = false;
|
||||
@@ -644,3 +660,41 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// The registry revision a chat list row or push carries; 0 when absent.
|
||||
int chatSessionRevision(Map<dynamic, dynamic> row) {
|
||||
final value = row['revision'];
|
||||
return value is num ? value.toInt() : 0;
|
||||
}
|
||||
|
||||
/// Whether [pushed] is older than [held]: both carry a revision and the
|
||||
/// push's is lower. A push is never stale against a row with no revision.
|
||||
bool chatSessionPushIsStale(
|
||||
Map<dynamic, dynamic> held,
|
||||
Map<dynamic, dynamic> pushed,
|
||||
) {
|
||||
final incoming = chatSessionRevision(pushed);
|
||||
return incoming > 0 && incoming < chatSessionRevision(held);
|
||||
}
|
||||
|
||||
/// [fetched] with the shared metadata (colour, star, title, revision) of
|
||||
/// [held] when [held] is newer: a list read that started before a push was
|
||||
/// applied must not revert it.
|
||||
JsonMap newerChatSessionMetadata(JsonMap fetched, JsonMap? held) {
|
||||
if (held == null || !chatSessionPushIsStale(held, fetched)) return fetched;
|
||||
final next = <String, dynamic>{...fetched};
|
||||
for (final key in const [
|
||||
'color',
|
||||
'starred',
|
||||
'starred_at',
|
||||
'title',
|
||||
'revision',
|
||||
]) {
|
||||
if (held.containsKey(key)) {
|
||||
next[key] = held[key];
|
||||
} else {
|
||||
next.remove(key);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'chat_color_palette.dart';
|
||||
|
||||
/// A chat's colour identifies it; this animated edge identifies where it is
|
||||
/// visible. The active chat has a stronger edge in both list presentations.
|
||||
/// visible. A chat shown in another pane (visible, not the open one) keeps a
|
||||
/// thin leading bar. The open chat is marked by the lists' shared selection
|
||||
/// style on its row (`AppListRow.selected`: tonal fill and one leading bar),
|
||||
/// the same in every list, so this adds nothing more to it.
|
||||
class ChatVisibilityMarker extends StatelessWidget {
|
||||
const ChatVisibilityMarker({
|
||||
super.key,
|
||||
@@ -19,41 +21,24 @@ class ChatVisibilityMarker extends StatelessWidget {
|
||||
final bool active;
|
||||
final Widget child;
|
||||
|
||||
/// The thin bar of a chat visible in another pane.
|
||||
static const double visibleBarWidth = 3;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final dark = chatColorDarkSurface(context);
|
||||
// The open chat: selected and shown beside the list.
|
||||
final open = active && visible;
|
||||
final elsewhere = visible && !active;
|
||||
final row = AnimatedContainer(
|
||||
key: ValueKey('chat-visibility-$sessionId'),
|
||||
duration: MediaQuery.disableAnimationsOf(context)
|
||||
? Duration.zero
|
||||
: const Duration(milliseconds: 220),
|
||||
curve: Curves.easeInOut,
|
||||
// The open chat is unmistakable: a strong fill in its colour, a full
|
||||
// outline, a thick leading bar and (below) a pointer toward the
|
||||
// conversation shown beside the list. A chat visible elsewhere keeps a
|
||||
// thin leading bar.
|
||||
decoration: BoxDecoration(
|
||||
color: open
|
||||
? color.withValues(alpha: dark ? .40 : .28)
|
||||
: active
|
||||
? color.withValues(alpha: dark ? .30 : .22)
|
||||
: null,
|
||||
),
|
||||
foregroundDecoration: BoxDecoration(
|
||||
border: open
|
||||
? BorderDirectional(
|
||||
start: BorderSide(color: color, width: 8),
|
||||
top: BorderSide(color: color, width: 2),
|
||||
end: BorderSide(color: color, width: 2),
|
||||
bottom: BorderSide(color: color, width: 2),
|
||||
)
|
||||
: BorderDirectional(
|
||||
start: visible
|
||||
? BorderSide(color: color, width: 3)
|
||||
: BorderSide.none,
|
||||
),
|
||||
border: BorderDirectional(
|
||||
start: elsewhere
|
||||
? BorderSide(color: color, width: visibleBarWidth)
|
||||
: BorderSide.none,
|
||||
),
|
||||
),
|
||||
child: child,
|
||||
);
|
||||
@@ -64,56 +49,7 @@ class ChatVisibilityMarker extends StatelessWidget {
|
||||
? 'Visible chat'
|
||||
: null,
|
||||
selected: active,
|
||||
// Always a Stack, so selecting a chat never rebuilds its row.
|
||||
child: Stack(
|
||||
children: [
|
||||
row,
|
||||
if (open)
|
||||
PositionedDirectional(
|
||||
end: 0,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
child: IgnorePointer(
|
||||
child: Center(
|
||||
child: CustomPaint(
|
||||
key: Key('chat-active-pointer-$sessionId'),
|
||||
size: const Size(9, 18),
|
||||
painter: _Pointer(
|
||||
color: color,
|
||||
rtl: Directionality.of(context) == TextDirection.rtl,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: row,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A small triangle on the row's trailing edge, pointing toward the open
|
||||
/// conversation beside the list.
|
||||
class _Pointer extends CustomPainter {
|
||||
const _Pointer({required this.color, required this.rtl});
|
||||
|
||||
final Color color;
|
||||
final bool rtl;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final path = rtl
|
||||
? (Path()
|
||||
..moveTo(size.width, 0)
|
||||
..lineTo(0, size.height / 2)
|
||||
..lineTo(size.width, size.height))
|
||||
: (Path()
|
||||
..moveTo(0, 0)
|
||||
..lineTo(size.width, size.height / 2)
|
||||
..lineTo(0, size.height));
|
||||
canvas.drawPath(path..close(), Paint()..color = color);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(_Pointer old) => old.color != color || old.rtl != rtl;
|
||||
}
|
||||
|
||||
@@ -25,8 +25,9 @@ import 'chat_awaiting.dart';
|
||||
/// An unread chat is emphasised (heavier title, accent time) with an accent
|
||||
/// dot ending its line; a starred chat shows a small star after its title; a
|
||||
/// running chat carries an activity badge on its avatar. A chat with a colour
|
||||
/// wears a faint row tint and a coloured avatar. An animated leading edge
|
||||
/// marks visible chats, growing wider for the active chat. The menu remains
|
||||
/// wears a faint row tint and a coloured avatar. The open chat wears the
|
||||
/// lists' shared selection (tonal fill and one leading bar); a thin animated
|
||||
/// leading edge marks a chat visible elsewhere. The menu remains
|
||||
/// the row's way to its actions.
|
||||
class ChatSessionRow extends StatelessWidget {
|
||||
const ChatSessionRow({
|
||||
@@ -80,7 +81,7 @@ class ChatSessionRow extends StatelessWidget {
|
||||
id: id,
|
||||
color: tint == null ? background : Color.alphaBlend(tint, background),
|
||||
marker: marker,
|
||||
markerWidth: visible ? (selected ? 10 : 3) : 0,
|
||||
markerWidth: selected ? kAppListRowBarWidth : (visible ? 3 : 0),
|
||||
child: draggable
|
||||
? Draggable<JsonMap>(
|
||||
// A mouse drags at once (a click still opens the chat); the chip
|
||||
@@ -130,7 +131,9 @@ class ChatSessionRow extends StatelessWidget {
|
||||
child: AppListRow(
|
||||
key: Key('chat-row-$id'),
|
||||
selected: selected,
|
||||
selectedFill: Colors.transparent,
|
||||
// The shared open-row style (tonal fill and one leading bar), the
|
||||
// bar in the chat's own colour when it has one.
|
||||
selectionAccent: marker,
|
||||
emphasized: unread,
|
||||
divider: divider,
|
||||
onTap: () => onOpen(session),
|
||||
|
||||
@@ -116,9 +116,14 @@ class _CopyPosition extends SingleChildLayoutDelegate {
|
||||
anchor != oldDelegate.anchor;
|
||||
}
|
||||
|
||||
/// The copy slot always occupies the same space, so hover never shifts code.
|
||||
/// Keyboard focus also reveals it; a touch on the code still selects normally.
|
||||
class ChatCodeCopyRegion extends StatefulWidget {
|
||||
/// A fenced code block as one framed piece: a header strip with the
|
||||
/// language label and Copy, then the code on its own fill.
|
||||
///
|
||||
/// Copy is always in the header (a touch screen has no hover to reveal it),
|
||||
/// outside the selectable document, so selecting the code never takes the
|
||||
/// button's label with it. Light mode keeps the code fill light, framed by a
|
||||
/// hairline, so code text keeps its full contrast; dark mode lifts it a step.
|
||||
class ChatCodeCopyRegion extends StatelessWidget {
|
||||
const ChatCodeCopyRegion({
|
||||
super.key,
|
||||
required this.code,
|
||||
@@ -127,49 +132,57 @@ class ChatCodeCopyRegion extends StatefulWidget {
|
||||
});
|
||||
final String code;
|
||||
final Widget label, child;
|
||||
@override
|
||||
State<ChatCodeCopyRegion> createState() => _ChatCodeCopyRegionState();
|
||||
}
|
||||
|
||||
class _ChatCodeCopyRegionState extends State<ChatCodeCopyRegion> {
|
||||
bool _hover = false, _focus = false;
|
||||
/// The block's corner radius.
|
||||
static const double radius = 8;
|
||||
|
||||
/// The code body's fill.
|
||||
static Color fill(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
return scheme.brightness == Brightness.light
|
||||
? scheme.surfaceContainerLow
|
||||
: scheme.surfaceContainerHighest;
|
||||
}
|
||||
|
||||
/// The header strip's fill, one step from the body's.
|
||||
static Color headerFill(BuildContext context) =>
|
||||
Theme.of(context).colorScheme.surfaceContainerHigh;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final visible = _hover || _focus;
|
||||
return MouseRegion(
|
||||
onEnter: (_) => setState(() => _hover = true),
|
||||
onExit: (_) => setState(() => _hover = false),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: widget.label),
|
||||
Focus(
|
||||
skipTraversal: true,
|
||||
onFocusChange: (value) => setState(() => _focus = value),
|
||||
child: ExcludeSemantics(
|
||||
excluding: !visible,
|
||||
child: IgnorePointer(
|
||||
ignoring: !visible,
|
||||
child: Opacity(
|
||||
opacity: visible ? 1 : 0,
|
||||
child: SelectionContainer.disabled(
|
||||
child: ChatCopyButton(
|
||||
text: widget.code,
|
||||
showLabel: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final header = ColoredBox(
|
||||
key: const Key('chat-code-header'),
|
||||
color: headerFill(context),
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.only(start: 12, end: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(child: label),
|
||||
SelectionContainer.disabled(
|
||||
child: ChatCopyButton(text: code, showLabel: true),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
return DecoratedBox(
|
||||
position: DecorationPosition.foreground,
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: scheme.outlineVariant),
|
||||
borderRadius: BorderRadius.circular(radius),
|
||||
),
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(radius),
|
||||
child: ColoredBox(
|
||||
key: const Key('chat-code-body'),
|
||||
color: fill(context),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [header, child],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
widget.child,
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
|
||||
import '../../conversation/chat_find_controller.dart';
|
||||
import '../../shell/chat_shell_terminal_theme.dart';
|
||||
|
||||
/// The boxes, in [ancestor]'s coordinates, of a character range of a
|
||||
/// rendered text; empty when it is not laid out.
|
||||
typedef ChatFindRects =
|
||||
List<Rect> Function(int start, int end, RenderBox ancestor);
|
||||
|
||||
/// Where find's matches are drawn: the open find (null while it is closed)
|
||||
/// and the rendered texts and rows the transcript has built, so the current
|
||||
/// match can be scrolled into view.
|
||||
class ChatFindTargets {
|
||||
final rows = <String, BuildContext>{};
|
||||
final texts = <String, Map<String, ChatFindRects>>{};
|
||||
|
||||
ChatFindRects? textFor(String rowKey, String text) => texts[rowKey]?[text];
|
||||
}
|
||||
|
||||
class ChatFindScope extends InheritedWidget {
|
||||
const ChatFindScope({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.targets,
|
||||
required super.child,
|
||||
});
|
||||
|
||||
final ChatFindController? controller;
|
||||
final ChatFindTargets targets;
|
||||
|
||||
static ChatFindScope? maybeOf(BuildContext context) =>
|
||||
context.dependOnInheritedWidgetOfExactType<ChatFindScope>();
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(ChatFindScope oldWidget) =>
|
||||
controller != oldWidget.controller || targets != oldWidget.targets;
|
||||
}
|
||||
|
||||
/// Marks one transcript row for find: the texts in it highlight their
|
||||
/// matches under [rowKey], and the row registers itself while built.
|
||||
class ChatFindRow extends StatefulWidget {
|
||||
const ChatFindRow({super.key, required this.rowKey, required this.child});
|
||||
|
||||
final String rowKey;
|
||||
final Widget child;
|
||||
|
||||
static String? keyOf(BuildContext context) =>
|
||||
context.dependOnInheritedWidgetOfExactType<_ChatFindRowKey>()?.rowKey;
|
||||
|
||||
@override
|
||||
State<ChatFindRow> createState() => _ChatFindRowState();
|
||||
}
|
||||
|
||||
class _ChatFindRowState extends State<ChatFindRow> {
|
||||
ChatFindTargets? _targets;
|
||||
String? _registered;
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
_register();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(ChatFindRow oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
_register();
|
||||
}
|
||||
|
||||
void _register() {
|
||||
_unregister();
|
||||
final targets = ChatFindScope.maybeOf(context)?.targets;
|
||||
if (targets == null) return;
|
||||
targets.rows[widget.rowKey] = context;
|
||||
_targets = targets;
|
||||
_registered = widget.rowKey;
|
||||
}
|
||||
|
||||
void _unregister() {
|
||||
final targets = _targets;
|
||||
final key = _registered;
|
||||
if (targets != null && key != null && targets.rows[key] == context) {
|
||||
targets.rows.remove(key);
|
||||
}
|
||||
_targets = null;
|
||||
_registered = null;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_unregister();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) =>
|
||||
_ChatFindRowKey(rowKey: widget.rowKey, child: widget.child);
|
||||
}
|
||||
|
||||
class _ChatFindRowKey extends InheritedWidget {
|
||||
const _ChatFindRowKey({required this.rowKey, required super.child});
|
||||
|
||||
final String rowKey;
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(_ChatFindRowKey oldWidget) =>
|
||||
rowKey != oldWidget.rowKey;
|
||||
}
|
||||
|
||||
/// Paints find's matches in one rendered [text], the current one stronger,
|
||||
/// like the terminal's find. The text itself is never restyled, so nothing
|
||||
/// shifts or rewraps as the current match moves. The translucent marks go
|
||||
/// over the text, since a code block's own fill would hide them behind it.
|
||||
class ChatFindHighlight extends StatefulWidget {
|
||||
const ChatFindHighlight({
|
||||
super.key,
|
||||
required this.text,
|
||||
required this.rects,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
final String text;
|
||||
final ChatFindRects rects;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
State<ChatFindHighlight> createState() => _ChatFindHighlightState();
|
||||
}
|
||||
|
||||
class _ChatFindHighlightState extends State<ChatFindHighlight> {
|
||||
final _anchor = GlobalKey();
|
||||
ChatFindTargets? _targets;
|
||||
(String, String)? _registered;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_unregister();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _register(ChatFindTargets? targets, String? rowKey) {
|
||||
final next = rowKey == null ? null : (rowKey, widget.text);
|
||||
if (identical(targets, _targets) && next == _registered) {
|
||||
// Another text with the same row and string may have unregistered
|
||||
// the shared entry; put it back.
|
||||
if (next != null) {
|
||||
targets!.texts.putIfAbsent(next.$1, () => {})[next.$2] = widget.rects;
|
||||
}
|
||||
return;
|
||||
}
|
||||
_unregister();
|
||||
if (targets == null || next == null) return;
|
||||
targets.texts.putIfAbsent(next.$1, () => {})[next.$2] = widget.rects;
|
||||
_targets = targets;
|
||||
_registered = next;
|
||||
}
|
||||
|
||||
void _unregister() {
|
||||
final targets = _targets;
|
||||
final key = _registered;
|
||||
if (targets != null && key != null) {
|
||||
final texts = targets.texts[key.$1];
|
||||
texts?.remove(key.$2);
|
||||
if (texts != null && texts.isEmpty) targets.texts.remove(key.$1);
|
||||
}
|
||||
_targets = null;
|
||||
_registered = null;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scope = ChatFindScope.maybeOf(context);
|
||||
final rowKey = ChatFindRow.keyOf(context);
|
||||
_register(scope?.targets, rowKey);
|
||||
final controller = scope?.controller;
|
||||
if (controller == null || rowKey == null) {
|
||||
return KeyedSubtree(key: _anchor, child: widget.child);
|
||||
}
|
||||
final colours = chatShellTerminalMatchColours(context);
|
||||
return CustomPaint(
|
||||
key: _anchor,
|
||||
foregroundPainter: _ChatFindPainter(
|
||||
controller: controller,
|
||||
rowKey: rowKey,
|
||||
text: widget.text,
|
||||
rects: widget.rects,
|
||||
anchor: _anchor,
|
||||
hit: colours.hit,
|
||||
current: colours.current,
|
||||
),
|
||||
child: widget.child,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ChatFindPainter extends CustomPainter {
|
||||
_ChatFindPainter({
|
||||
required this.controller,
|
||||
required this.rowKey,
|
||||
required this.text,
|
||||
required this.rects,
|
||||
required this.anchor,
|
||||
required this.hit,
|
||||
required this.current,
|
||||
}) : super(repaint: controller);
|
||||
|
||||
final ChatFindController controller;
|
||||
final String rowKey;
|
||||
final String text;
|
||||
final ChatFindRects rects;
|
||||
final GlobalKey anchor;
|
||||
final Color hit;
|
||||
final Color current;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final highlights = controller.highlightsFor(rowKey, text);
|
||||
if (highlights.isEmpty) return;
|
||||
final box = anchor.currentContext?.findRenderObject();
|
||||
if (box is! RenderBox || !box.attached) return;
|
||||
for (final highlight in highlights) {
|
||||
final fill = Paint()..color = highlight.current ? current : hit;
|
||||
for (final rect in rects(highlight.start, highlight.end, box)) {
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(rect.inflate(1), const Radius.circular(3)),
|
||||
fill,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(_ChatFindPainter oldDelegate) =>
|
||||
oldDelegate.controller != controller ||
|
||||
oldDelegate.rowKey != rowKey ||
|
||||
oldDelegate.text != text ||
|
||||
oldDelegate.hit != hit ||
|
||||
oldDelegate.current != current;
|
||||
}
|
||||
|
||||
/// The boxes of characters [start]..[end] of the first paragraph (or
|
||||
/// editable) under [context], for a text rendered verbatim.
|
||||
List<Rect> chatFindPlainRects(
|
||||
BuildContext? context,
|
||||
int start,
|
||||
int end,
|
||||
RenderBox ancestor,
|
||||
) {
|
||||
final paragraph = chatFindTextRenderer(context);
|
||||
if (paragraph == null || !paragraph.attached || !paragraph.hasSize) {
|
||||
return const [];
|
||||
}
|
||||
final selection = TextSelection(baseOffset: start, extentOffset: end);
|
||||
final boxes = switch (paragraph) {
|
||||
RenderParagraph() => paragraph.getBoxesForSelection(selection),
|
||||
RenderEditable() => paragraph.getBoxesForSelection(selection),
|
||||
_ => const <TextBox>[],
|
||||
};
|
||||
final transform = paragraph.getTransformTo(ancestor);
|
||||
return [
|
||||
for (final box in boxes) MatrixUtils.transformRect(transform, box.toRect()),
|
||||
];
|
||||
}
|
||||
|
||||
/// The first [RenderParagraph] or [RenderEditable] under [context].
|
||||
RenderBox? chatFindTextRenderer(BuildContext? context) {
|
||||
RenderBox? found;
|
||||
void visit(RenderObject object) {
|
||||
if (found != null) return;
|
||||
if (object is RenderParagraph || object is RenderEditable) {
|
||||
found = object as RenderBox;
|
||||
} else {
|
||||
object.visitChildren(visit);
|
||||
}
|
||||
}
|
||||
|
||||
final root = context?.findRenderObject();
|
||||
if (root != null) visit(root);
|
||||
return found;
|
||||
}
|
||||
@@ -2,8 +2,10 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import '../../../../ui/layout/wheel_scroll_forwarding.dart';
|
||||
|
||||
/// Native, persistent overflow affordances for a code block or table. The
|
||||
/// footer is outside the selectable document and never overlays its content.
|
||||
/// Native, persistent overflow affordances for a code block or table: the
|
||||
/// side with more content fades out under a small chevron, and the scrollbar
|
||||
/// thumb stays visible. The chevrons are outside the selectable document and
|
||||
/// take no taps; the semantics hint names the gestures and keys.
|
||||
class ChatHorizontalViewport extends StatefulWidget {
|
||||
const ChatHorizontalViewport({
|
||||
super.key,
|
||||
@@ -89,20 +91,67 @@ class _ChatHorizontalViewportState extends State<ChatHorizontalViewport> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// The width over which content fades out at a side with more to scroll.
|
||||
static const double _fadeWidth = 32;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final color = Theme.of(context).colorScheme.onSurfaceVariant;
|
||||
final focusColor = Theme.of(context).colorScheme.primary;
|
||||
final view = Padding(
|
||||
padding: EdgeInsets.only(bottom: _overflow ? 12 : 0),
|
||||
Widget view = Padding(
|
||||
padding: EdgeInsets.only(bottom: _overflow ? 10 : 0),
|
||||
child: HorizontalScrollView(controller: _controller, child: widget.child),
|
||||
);
|
||||
if (_left || _right) {
|
||||
// The side with more content fades out, the usual sign that a row
|
||||
// continues past the edge; content at rest is never covered.
|
||||
view = ShaderMask(
|
||||
key: const Key('chat-horizontal-fade'),
|
||||
blendMode: BlendMode.dstIn,
|
||||
shaderCallback: (bounds) {
|
||||
final fade = bounds.width <= 0
|
||||
? 0.0
|
||||
: (_fadeWidth / bounds.width).clamp(0.0, 0.5);
|
||||
const shown = Colors.white;
|
||||
const hidden = Color(0x00FFFFFF);
|
||||
return LinearGradient(
|
||||
colors: [
|
||||
_left ? hidden : shown,
|
||||
shown,
|
||||
shown,
|
||||
_right ? hidden : shown,
|
||||
],
|
||||
stops: [0, fade, 1 - fade, 1],
|
||||
).createShader(bounds);
|
||||
},
|
||||
child: view,
|
||||
);
|
||||
}
|
||||
final scrollbar = Scrollbar(
|
||||
controller: _controller,
|
||||
thumbVisibility: _overflow,
|
||||
trackVisibility: _overflow,
|
||||
child: view,
|
||||
);
|
||||
Widget chevron(bool left) => Positioned(
|
||||
left: left ? 0 : null,
|
||||
right: left ? null : 0,
|
||||
top: 0,
|
||||
bottom: 10,
|
||||
child: IgnorePointer(
|
||||
child: Center(
|
||||
child: Icon(
|
||||
left ? Icons.chevron_left : Icons.chevron_right,
|
||||
key: Key(
|
||||
left ? 'chat-horizontal-more-left' : 'chat-horizontal-more-right',
|
||||
),
|
||||
size: 18,
|
||||
// Physical sides: the arrow points where the content continues.
|
||||
textDirection: TextDirection.ltr,
|
||||
color: color.withValues(alpha: .7),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
return NotificationListener<ScrollMetricsNotification>(
|
||||
onNotification: (notification) {
|
||||
if (notification.metrics.axis == Axis.horizontal) _scheduleMetrics();
|
||||
@@ -127,35 +176,17 @@ class _ChatHorizontalViewportState extends State<ChatHorizontalViewport> {
|
||||
color: _focused ? focusColor : Colors.transparent,
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
child: Stack(
|
||||
children: [
|
||||
scrollbar,
|
||||
if (_overflow)
|
||||
SelectionContainer.disabled(
|
||||
child: ExcludeSemantics(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Row(
|
||||
if (_left || _right)
|
||||
Positioned.fill(
|
||||
child: SelectionContainer.disabled(
|
||||
child: ExcludeSemantics(
|
||||
child: Stack(
|
||||
children: [
|
||||
Icon(
|
||||
_left && _right
|
||||
? Icons.swap_horiz
|
||||
: _left
|
||||
? Icons.arrow_back
|
||||
: Icons.arrow_forward,
|
||||
size: 16,
|
||||
textDirection: TextDirection.ltr,
|
||||
color: color,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Flexible(
|
||||
child: Text(
|
||||
'Scroll horizontally',
|
||||
style: TextStyle(color: color),
|
||||
),
|
||||
),
|
||||
if (_left) chevron(true),
|
||||
if (_right) chevron(false),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'chat_find_highlight.dart';
|
||||
import 'chat_link_launcher.dart';
|
||||
import 'chat_link_spans.dart';
|
||||
import 'chat_links.dart';
|
||||
@@ -38,8 +39,19 @@ class _ChatLinkTextState extends State<ChatLinkText> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
final _textKey = GlobalKey();
|
||||
|
||||
/// The text with find's matches painted behind it; it renders verbatim,
|
||||
/// so a match's offsets are the rendered characters'.
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
Widget build(BuildContext context) => ChatFindHighlight(
|
||||
text: widget.text,
|
||||
rects: (start, end, box) =>
|
||||
chatFindPlainRects(_textKey.currentContext, start, end, box),
|
||||
child: KeyedSubtree(key: _textKey, child: _text(context)),
|
||||
);
|
||||
|
||||
Widget _text(BuildContext context) {
|
||||
final text = widget.text;
|
||||
if (_found.isEmpty) {
|
||||
return ChatTranscriptSelectionScope.maybeOf(context) == null
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:flutter/rendering.dart';
|
||||
|
||||
import 'chat_transcript_selection.dart';
|
||||
import 'chat_code_hover.dart';
|
||||
import 'chat_find_highlight.dart';
|
||||
import '../../../../ui/text/monospace.dart';
|
||||
import 'chat_link_launcher.dart';
|
||||
import 'chat_link_spans.dart';
|
||||
@@ -110,7 +111,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
// The text is built once and never restyled while speaking; the
|
||||
// spoken word is painted behind it, so nothing shifts or rewraps.
|
||||
final rendered = _rendered ??= _buildRendered(context);
|
||||
return CustomPaint(
|
||||
final spoken = CustomPaint(
|
||||
key: _paintKey,
|
||||
painter: SpokenWordPainter(
|
||||
anchor: _paintKey,
|
||||
@@ -121,6 +122,13 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
),
|
||||
child: rendered,
|
||||
);
|
||||
// Find's matches are painted the same way, behind the text.
|
||||
return ChatFindHighlight(
|
||||
text: widget.text,
|
||||
rects: (start, end, box) =>
|
||||
spokenWordRects(_segments, (start: start, end: end), box),
|
||||
child: spoken,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -252,6 +260,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
],
|
||||
);
|
||||
case MarkdownCode(language: final language, code: final code):
|
||||
final codeKey = _codeSegment(code);
|
||||
_skipCodeBlock(code);
|
||||
final labelStyle = _roleStyle(
|
||||
context,
|
||||
@@ -260,22 +269,20 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
return ChatCodeCopyRegion(
|
||||
code: code,
|
||||
label: Text(markdownCodeLabel(language), style: labelStyle),
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(color: _codeFill(context)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: ChatTranscriptHorizontalScrollView(
|
||||
label: 'code block',
|
||||
child: Text.rich(
|
||||
TextSpan(
|
||||
children: _linked(
|
||||
context,
|
||||
code,
|
||||
(part) => TextSpan(text: part),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: ChatTranscriptHorizontalScrollView(
|
||||
label: 'code block',
|
||||
child: Text.rich(
|
||||
key: codeKey,
|
||||
TextSpan(
|
||||
children: _linked(
|
||||
context,
|
||||
code,
|
||||
(part) => TextSpan(text: part),
|
||||
),
|
||||
style: const TextStyle(fontFamily: appMonospaceFamily),
|
||||
),
|
||||
style: const TextStyle(fontFamily: appMonospaceFamily),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -283,6 +290,27 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Records where a code block's text renders, character for character
|
||||
/// from its place in the source, so find can highlight matches in it.
|
||||
GlobalKey _codeSegment(String code) {
|
||||
if (_textCount == _textKeys.length) _textKeys.add(GlobalKey());
|
||||
final key = _textKeys[_textCount++];
|
||||
final start = code.isEmpty ? -1 : widget.text.indexOf(code, _sourceCursor);
|
||||
if (start >= 0) {
|
||||
_segments.add(
|
||||
MarkdownSpokenSegment(
|
||||
key,
|
||||
start,
|
||||
start + code.length,
|
||||
0,
|
||||
code.length,
|
||||
List<int>.generate(code.length, (index) => start + index),
|
||||
),
|
||||
);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
void _skipCodeBlock(String code) {
|
||||
_sourceCursor = fencedCodeSpan(
|
||||
widget.text,
|
||||
|
||||
@@ -28,6 +28,16 @@ class RunBadge {
|
||||
final String? ranAgo;
|
||||
final String? duration;
|
||||
|
||||
/// When the last run started, said as such for a list row: `last run
|
||||
/// 19 Oct`, `last run 2h ago`, `last run just now`. Null without a time.
|
||||
String? get lastRun {
|
||||
final ago = ranAgo;
|
||||
if (ago == null || ago.isEmpty) return null;
|
||||
// `5m`, `2h`, `3d` are ages; a date or `just now` reads as it is.
|
||||
final age = RegExp(r'^\d+[mhd]$').hasMatch(ago) ? '$ago ago' : ago;
|
||||
return 'last run $age';
|
||||
}
|
||||
|
||||
/// `2h · 1m 5s · run 42`; missing fragments are omitted.
|
||||
String get metaLine => [
|
||||
ranAgo,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'dart:async';
|
||||
|
||||
import '../../ui/adaptive/segmented_bar.dart';
|
||||
import '../../shell/destination.dart';
|
||||
import '../../shell/detail_page.dart';
|
||||
@@ -15,6 +17,7 @@ import 'pending_run_store.dart';
|
||||
import 'widgets/pipeline_bar_buttons.dart';
|
||||
import 'widgets/pipeline_detail_panel.dart';
|
||||
import 'widgets/pipeline_list_panel.dart';
|
||||
import 'ui/run_pipeline_from_list.dart';
|
||||
|
||||
export 'pipeline_models.dart' show PipelineDetail, PipelineVersion;
|
||||
|
||||
@@ -223,6 +226,18 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
|
||||
return _isRoutePin(detail) ? key : null;
|
||||
}
|
||||
|
||||
/// A list row's Run: the same start flow as the detail's Run button.
|
||||
void _runFromList(BuildContext context, PipelineSummary pipeline) =>
|
||||
unawaited(
|
||||
startPipelineRunFromList(
|
||||
context: context,
|
||||
pipeline: pipeline,
|
||||
controller: _controller,
|
||||
gateway: widget.gateway,
|
||||
onRunStarted: widget.onRunStarted,
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AnimatedBuilder(
|
||||
@@ -262,6 +277,7 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
|
||||
child: PipelineListPanel(
|
||||
controller: _controller,
|
||||
onOpenInChat: widget.onOpenPipelineInChat,
|
||||
onRun: _runFromList,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -270,6 +286,7 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
|
||||
child: PipelineListPanel(
|
||||
controller: _controller,
|
||||
onOpenInChat: widget.onOpenPipelineInChat,
|
||||
onRun: _runFromList,
|
||||
),
|
||||
),
|
||||
detailIdentity: _controller.selectedId,
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../pipeline_models.dart';
|
||||
import '../pipeline_repository.dart';
|
||||
import '../pipelines_controller.dart';
|
||||
import 'run_pipeline_flow.dart';
|
||||
import 'run_pipeline_wording.dart';
|
||||
|
||||
/// A list row's Run: reads the row's pipeline at its listed version, then
|
||||
/// opens the same start flow as the detail's Run button. Nothing starts until
|
||||
/// the form's own confirm; a refused read is shown, never a guessed form.
|
||||
Future<void> startPipelineRunFromList({
|
||||
required BuildContext context,
|
||||
required PipelineSummary pipeline,
|
||||
required PipelinesController controller,
|
||||
required ApiGateway gateway,
|
||||
ValueChanged<int>? onRunStarted,
|
||||
}) async {
|
||||
if (pipeline.archived) return;
|
||||
final PipelineDetail detail;
|
||||
try {
|
||||
detail = await PipelinesRepository(
|
||||
gateway,
|
||||
).getPipeline(pipeline.id, pipeline.version);
|
||||
} 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,
|
||||
);
|
||||
}
|
||||
@@ -14,7 +14,8 @@ import '../pipelines_controller.dart';
|
||||
import 'pipeline_controls.dart';
|
||||
import 'pipeline_filter_page.dart';
|
||||
import 'pipeline_scope_control.dart';
|
||||
import '../../../ui/layout/app_overflow_menu.dart';
|
||||
import '../../../shell/list_detail_policy.dart';
|
||||
import 'pipeline_row_actions.dart';
|
||||
|
||||
/// The list's horizontal rhythm, matching the web's toolbar and row inset
|
||||
/// (`var(--space-s)`: 12px). The detail pane keeps its own content padding.
|
||||
@@ -26,12 +27,17 @@ class PipelineListPanel extends StatelessWidget {
|
||||
super.key,
|
||||
required this.controller,
|
||||
this.onOpenInChat,
|
||||
this.onRun,
|
||||
});
|
||||
|
||||
final PipelinesController controller;
|
||||
final Future<void> Function(BuildContext, PipelineSummary, PipelineRun?)?
|
||||
onOpenInChat;
|
||||
|
||||
/// Opens the New run form for a row's pipeline (its menu's Run…, and its
|
||||
/// trailing Run button on a wide list); null offers neither.
|
||||
final void Function(BuildContext, PipelineSummary)? onRun;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final filters = controller.filters;
|
||||
@@ -230,6 +236,23 @@ class PipelineListPanel extends StatelessWidget {
|
||||
final now = DateTime.now();
|
||||
// The default padding is the media padding: the controls start below the
|
||||
// top bar and the last row clears the floating tab bar.
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) =>
|
||||
_rows(context, header, items, now, constraints.maxWidth),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _rows(
|
||||
BuildContext context,
|
||||
List<Widget> header,
|
||||
List<PipelineSummary> items,
|
||||
DateTime now,
|
||||
double width,
|
||||
) {
|
||||
// A wide layout's list, beside its detail and wide enough, gives each row
|
||||
// its own Run button beside its menu; a phone keeps Run in the menu.
|
||||
final wide =
|
||||
showsListBesideDetail(context) && width >= kPipelineRowRunButtonWidth;
|
||||
return ListView.builder(
|
||||
key: const Key('pipeline-list'),
|
||||
itemCount: header.length + items.length,
|
||||
@@ -248,7 +271,9 @@ class PipelineListPanel extends StatelessWidget {
|
||||
controller.openPipeline(pipeline.id, version: pipeline.version),
|
||||
leading: _pipelineIdentityIcon(context, pipeline),
|
||||
title: Text(pipeline.displayName),
|
||||
time: badge?.ranAgo,
|
||||
// The latest run's state is spelled out, not colour alone, with
|
||||
// when it ran: `Failed · last run 19 Oct`. The pipeline's own
|
||||
// facts (stages, schedules) follow on the next line.
|
||||
subtitleLeading: badge == null
|
||||
? null
|
||||
: AppListStatusDot(
|
||||
@@ -260,39 +285,51 @@ class PipelineListPanel extends StatelessWidget {
|
||||
semanticLabel: runStateLabel(badge.state),
|
||||
),
|
||||
subtitle: Text(
|
||||
ServerContext.metadata(context, _rowMetadata(pipeline)),
|
||||
badge == null
|
||||
? ServerContext.metadata(context, _rowMetadata(pipeline))
|
||||
: ServerContext.metadata(
|
||||
context,
|
||||
_statusLine(badge, badge.lastRun),
|
||||
),
|
||||
key: Key('pipeline-status-text-${pipeline.id}'),
|
||||
),
|
||||
// A narrow pane keeps the latest state, the useful decision signal;
|
||||
// stage counts, schedules and version live in the detail instead.
|
||||
// Do not turn an in-flight or failed run-history read into a false
|
||||
// no-runs claim: the line stays blank until history is known.
|
||||
detail: badge == null ? null : Text(_rowMetadata(pipeline)),
|
||||
compactDetail: false,
|
||||
// A narrow pane keeps the latest state and its date, the useful
|
||||
// decision signal; stage counts, schedules and version live in the
|
||||
// detail instead. Do not turn an in-flight or failed run-history
|
||||
// read into a false no-runs claim: the line stays blank until
|
||||
// history is known.
|
||||
compactSubtitle: badge == null
|
||||
? Text(ServerContext.metadata(context, ''))
|
||||
: Text(
|
||||
ServerContext.metadata(context, runStateLabel(badge.state)),
|
||||
),
|
||||
menu: onOpenInChat == null
|
||||
? null
|
||||
: AppOverflowMenu<bool>(
|
||||
key: Key('pipeline-row-more-menu-${pipeline.id}'),
|
||||
label: 'Pipeline actions',
|
||||
sheetTitle: pipeline.displayName,
|
||||
actions: const [
|
||||
AppMenuAction<bool>(
|
||||
value: true,
|
||||
label: 'Send to chat…',
|
||||
icon: Icons.chat_bubble_outline,
|
||||
),
|
||||
],
|
||||
onSelected: (context, _) =>
|
||||
onOpenInChat!(context, pipeline, run),
|
||||
ServerContext.metadata(
|
||||
context,
|
||||
_statusLine(badge, badge.ranAgo),
|
||||
),
|
||||
),
|
||||
menu: pipelineRowActions(
|
||||
pipeline: pipeline,
|
||||
wide: wide,
|
||||
onRun: onRun == null
|
||||
? null
|
||||
: (context) => onRun!(context, pipeline),
|
||||
onOpenInChat: onOpenInChat == null
|
||||
? null
|
||||
: (context) => onOpenInChat!(context, pipeline, run),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// The row's one muted subtitle: stage count and schedules.
|
||||
/// `Failed · last run 19 Oct`: the latest run's state and when it ran.
|
||||
String _statusLine(RunBadge badge, String? when) => [
|
||||
runStateLabel(badge.state),
|
||||
if (when != null && when.isNotEmpty) when,
|
||||
].join(' · ');
|
||||
|
||||
/// The row's muted facts line: stage count and schedules.
|
||||
String _rowMetadata(PipelineSummary pipeline) {
|
||||
final schedules = switch (pipeline.scheduleState) {
|
||||
PipelineScheduleState.scheduled => pipeline.scheduleLabel,
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/layout/app_overflow_menu.dart';
|
||||
import '../pipeline_models.dart';
|
||||
import '../ui/run_pipeline_wording.dart';
|
||||
|
||||
/// The pipeline list's width from which each row shows its own Run button
|
||||
/// beside its menu; a narrower list keeps Run in the menu only.
|
||||
const double kPipelineRowRunButtonWidth = 360;
|
||||
|
||||
const pipelineRowRunLabel = 'Run…';
|
||||
|
||||
Key pipelineRowRunKey(int id) => ValueKey('pipeline-row-run-$id');
|
||||
Key pipelineRowRunMenuKey(int id) => ValueKey('pipeline-row-run-menu-$id');
|
||||
Key pipelineRowMenuKey(int id) => ValueKey('pipeline-row-more-menu-$id');
|
||||
|
||||
enum _PipelineRowAction { run, sendToChat }
|
||||
|
||||
/// A pipeline row's trailing actions: its menu (Run…, Send to chat…) and, on
|
||||
/// a [wide] list, a Run button before it. Run is not offered for an archived
|
||||
/// pipeline, as its detail offers none. Null when there is nothing to offer.
|
||||
Widget? pipelineRowActions({
|
||||
required PipelineSummary pipeline,
|
||||
required bool wide,
|
||||
void Function(BuildContext)? onRun,
|
||||
void Function(BuildContext)? onOpenInChat,
|
||||
}) {
|
||||
final run = pipeline.archived ? null : onRun;
|
||||
final actions = [
|
||||
if (run != null)
|
||||
AppMenuAction(
|
||||
key: pipelineRowRunMenuKey(pipeline.id),
|
||||
value: _PipelineRowAction.run,
|
||||
label: pipelineRowRunLabel,
|
||||
icon: Icons.play_arrow_rounded,
|
||||
),
|
||||
if (onOpenInChat != null)
|
||||
const AppMenuAction(
|
||||
value: _PipelineRowAction.sendToChat,
|
||||
label: 'Send to chat…',
|
||||
icon: Icons.chat_bubble_outline,
|
||||
),
|
||||
];
|
||||
if (actions.isEmpty) return null;
|
||||
final menu = AppOverflowMenu<_PipelineRowAction>(
|
||||
key: pipelineRowMenuKey(pipeline.id),
|
||||
label: 'Pipeline actions',
|
||||
sheetTitle: pipeline.displayName,
|
||||
actions: actions,
|
||||
onSelected: (context, action) => switch (action) {
|
||||
_PipelineRowAction.run => run!(context),
|
||||
_PipelineRowAction.sendToChat => onOpenInChat!(context),
|
||||
},
|
||||
);
|
||||
if (!wide || run == null) return menu;
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Builder(
|
||||
builder: (context) => TextButton.icon(
|
||||
key: pipelineRowRunKey(pipeline.id),
|
||||
onPressed: () => run(context),
|
||||
icon: const Icon(Icons.play_arrow_rounded),
|
||||
label: Text(
|
||||
runPipelineActionLabel,
|
||||
semanticsLabel: 'Run ${pipeline.displayName}',
|
||||
),
|
||||
),
|
||||
),
|
||||
menu,
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -11,12 +11,19 @@ bool canRetryRun(JsonMap? run) {
|
||||
|
||||
/// Whether [run] can be started again with its inputs: a finished run that
|
||||
/// succeeded, was canceled or was interrupted, and names its pipeline. A
|
||||
/// failed run has Retry instead.
|
||||
bool canRunAgain(JsonMap? run) {
|
||||
/// failed run has Retry instead in menus (see [canStartRunAgain]).
|
||||
bool canRunAgain(JsonMap? run) =>
|
||||
canStartRunAgain(run) && run!['status'] != 'failed';
|
||||
|
||||
/// Whether the New run form can be pre-filled from [run]: any finished run,
|
||||
/// failed included, that names its pipeline. A failed run's banner offers it
|
||||
/// beside Retry.
|
||||
bool canStartRunAgain(JsonMap? run) {
|
||||
if (run == null || run['executing'] == true) return false;
|
||||
final pipeline = run['pipeline_id'];
|
||||
return const {
|
||||
'succeeded',
|
||||
'failed',
|
||||
'canceled',
|
||||
'interrupted',
|
||||
}.contains(run['status']) &&
|
||||
|
||||
@@ -23,6 +23,13 @@ String localDayKey(DateTime date) {
|
||||
return '${local.year}-${two(local.month)}-${two(local.day)}';
|
||||
}
|
||||
|
||||
/// The local time of day, `HH:mm`, for a run listed under its day heading.
|
||||
String runTimeOfDay(DateTime instant) {
|
||||
final local = instant.toLocal();
|
||||
String two(int value) => value.toString().padLeft(2, '0');
|
||||
return '${two(local.hour)}:${two(local.minute)}';
|
||||
}
|
||||
|
||||
String runDayLabel(String createdAt, DateTime today) {
|
||||
final created = DateTime.tryParse(createdAt)?.toLocal();
|
||||
if (created == null) return 'Unknown date';
|
||||
|
||||
@@ -38,7 +38,7 @@ Future<void> startRunAgainFlow({
|
||||
required ApiGateway gateway,
|
||||
ValueChanged<int>? onRunStarted,
|
||||
}) async {
|
||||
if (!canRunAgain(run)) return;
|
||||
if (!canStartRunAgain(run)) return;
|
||||
final pipelineId = (run['pipeline_id'] as num).toInt();
|
||||
final JsonMap full;
|
||||
final PipelineDetail detail;
|
||||
|
||||
@@ -26,9 +26,11 @@ Widget buildMaterialRunDetail({
|
||||
String? initialStageKey,
|
||||
int? initialVisit,
|
||||
void Function(String draft)? onSendToChat,
|
||||
Widget? failureActions,
|
||||
}) {
|
||||
return RunDetailTabs(
|
||||
run: run,
|
||||
failureActions: failureActions,
|
||||
copying: copying,
|
||||
copyStatus: copyStatus,
|
||||
onCopy: onCopy,
|
||||
|
||||
@@ -30,6 +30,7 @@ Widget runDetailSummaryTab({
|
||||
ExpansibleController? inputController,
|
||||
ExpansibleController? outputController,
|
||||
Widget? graphPreview,
|
||||
Widget? failureActions,
|
||||
}) {
|
||||
final rows = detailSummaryRows(run);
|
||||
final identity = detailSummaryIdentity(run);
|
||||
@@ -61,7 +62,9 @@ Widget runDetailSummaryTab({
|
||||
),
|
||||
),
|
||||
),
|
||||
SliverToBoxAdapter(child: RunFailureBanner(run: run)),
|
||||
SliverToBoxAdapter(
|
||||
child: RunFailureBanner(run: run, actions: failureActions),
|
||||
),
|
||||
SliverToBoxAdapter(
|
||||
child: WarningsSection(messages: warningMessages(run['warnings'])),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../../../ui/input/keyboard_owner.dart';
|
||||
|
||||
const _digits = [
|
||||
LogicalKeyboardKey.digit1,
|
||||
LogicalKeyboardKey.digit2,
|
||||
LogicalKeyboardKey.digit3,
|
||||
LogicalKeyboardKey.digit4,
|
||||
LogicalKeyboardKey.numpad1,
|
||||
LogicalKeyboardKey.numpad2,
|
||||
LogicalKeyboardKey.numpad3,
|
||||
LogicalKeyboardKey.numpad4,
|
||||
];
|
||||
|
||||
/// The 0-based run-detail tab a bare 1…4 key press names, or null. Any
|
||||
/// modifier (Ctrl+1…9 opens a chat list item) or a repeat is not the key.
|
||||
int? runDetailTabDigit(KeyEvent event, HardwareKeyboard keyboard) {
|
||||
if (event is! KeyDownEvent ||
|
||||
keyboard.isControlPressed ||
|
||||
keyboard.isMetaPressed ||
|
||||
keyboard.isAltPressed ||
|
||||
keyboard.isShiftPressed) {
|
||||
return null;
|
||||
}
|
||||
final index = _digits.indexOf(event.logicalKey);
|
||||
return index < 0 ? null : index % 4;
|
||||
}
|
||||
|
||||
/// Whether a digit pressed now is meant for the run detail at [context]: it
|
||||
/// is on screen (not in a hidden destination or tab), no dialog, menu or
|
||||
/// visit page is over it, and nothing that takes typing (a text field, the
|
||||
/// terminal) has the keyboard.
|
||||
bool runDetailOwnsDigits(BuildContext context) {
|
||||
if (!TickerMode.valuesOf(context).enabled) return false;
|
||||
final route = ModalRoute.of(context);
|
||||
if (route != null && !route.isCurrent) return false;
|
||||
return !primaryFocusTakesTyping();
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/adaptive/floating_bar_layout.dart';
|
||||
import '../../../ui/adaptive/floating_destination_bar.dart';
|
||||
@@ -16,14 +16,41 @@ const List<RunDetailTab> renderedRunDetailTabs = [
|
||||
RunDetailTab.changes,
|
||||
];
|
||||
|
||||
/// The run detail's tabs: the app's floating glass tab bar, full width at the
|
||||
/// bottom of a phone page; beside a list, sized to its tabs at the bottom of
|
||||
/// the detail pane (the shell's own tab bar stays over the list pane).
|
||||
/// The run's Artifacts count as a small badge: `0` on a run with none, so
|
||||
/// the (disabled) tab still says why it cannot open.
|
||||
class RunArtifactsCount extends StatelessWidget {
|
||||
const RunArtifactsCount({super.key, required this.count, this.child});
|
||||
|
||||
final int count;
|
||||
|
||||
/// The icon the badge sits on; null draws the badge on its own.
|
||||
final Widget? child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
return Badge(
|
||||
key: const ValueKey('run-detail-artifacts-count'),
|
||||
label: Text('$count'),
|
||||
backgroundColor: count == 0
|
||||
? scheme.surfaceContainerHighest
|
||||
: scheme.secondary,
|
||||
textColor: count == 0 ? scheme.onSurfaceVariant : scheme.onSecondary,
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The run detail's tabs on a phone: the app's floating glass tab bar, full
|
||||
/// width at the bottom of the page (a wide layout puts `RunDetailTopTabs`
|
||||
/// under the run header instead).
|
||||
///
|
||||
/// Float it over the tab body with `FloatingBarOverlay` at the same [edge];
|
||||
/// every tab is always visible, so a tab selected by the Graph is shown
|
||||
/// selected without scrolling. The whole bar is keyed `run-detail-tabs`, each
|
||||
/// tab `run-detail-tab-<name>`.
|
||||
/// selected without scrolling. Artifacts is always a tab, disabled with a
|
||||
/// `0` count on a run with none, so the tabs after it never move between
|
||||
/// runs. The whole bar is keyed `run-detail-tabs`, each tab
|
||||
/// `run-detail-tab-<name>`.
|
||||
class RunDetailTabStrip extends StatelessWidget {
|
||||
const RunDetailTabStrip({
|
||||
super.key,
|
||||
@@ -31,8 +58,14 @@ class RunDetailTabStrip extends StatelessWidget {
|
||||
required this.onSelected,
|
||||
this.tabs = renderedRunDetailTabs,
|
||||
this.edge = FloatingBarEdge.bottom,
|
||||
this.artifactCount,
|
||||
this.disabled = const {},
|
||||
this.disabledReasons = const {},
|
||||
});
|
||||
|
||||
/// Why a disabled tab cannot open, as its tooltip.
|
||||
final Map<RunDetailTab, String> disabledReasons;
|
||||
|
||||
final RunDetailTab selected;
|
||||
final ValueChanged<RunDetailTab> onSelected;
|
||||
final FloatingBarEdge edge;
|
||||
@@ -40,9 +73,17 @@ class RunDetailTabStrip extends StatelessWidget {
|
||||
/// The tabs this run offers, in [renderedRunDetailTabs] order.
|
||||
final List<RunDetailTab> tabs;
|
||||
|
||||
/// The run's recorded artifacts, badged on the Artifacts tab; null draws
|
||||
/// no badge.
|
||||
final int? artifactCount;
|
||||
|
||||
/// Tabs shown greyed out that take no taps.
|
||||
final Set<RunDetailTab> disabled;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final index = tabs.indexOf(selected);
|
||||
final count = artifactCount;
|
||||
return KeyedSubtree(
|
||||
key: const Key('run-detail-tabs'),
|
||||
child: FloatingDestinationBar(
|
||||
@@ -56,8 +97,12 @@ class RunDetailTabStrip extends StatelessWidget {
|
||||
for (final tab in tabs)
|
||||
FloatingDestinationItem(
|
||||
key: ValueKey('run-detail-tab-${tab.name}'),
|
||||
icon: Icon(tab.icon),
|
||||
icon: tab == RunDetailTab.artifacts && count != null
|
||||
? RunArtifactsCount(count: count, child: Icon(tab.icon))
|
||||
: Icon(tab.icon),
|
||||
label: tab.label,
|
||||
enabled: !disabled.contains(tab),
|
||||
tooltip: disabled.contains(tab) ? disabledReasons[tab] : null,
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -7,19 +7,23 @@ import '../../../ui/motion/fade_through_stack.dart';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../graph/widgets/run_graph_view.dart';
|
||||
import '../../artifacts/ui/artifact_gallery_action.dart';
|
||||
import '../../artifacts/ui/artifact_gallery_page.dart';
|
||||
import '../../artifacts/domain/artifact_chat_context.dart';
|
||||
import '../../artifacts/domain/artifact_summary.dart';
|
||||
import '../../changes/changes.dart';
|
||||
import 'run_changes_action.dart';
|
||||
import 'run_detail_content.dart';
|
||||
import 'run_graph_preview.dart';
|
||||
import 'run_detail_tab.dart';
|
||||
import 'run_detail_tab_bodies.dart';
|
||||
import 'run_detail_tab_keys.dart';
|
||||
import 'run_detail_tab_strip.dart';
|
||||
import 'run_detail_top_tabs.dart';
|
||||
import 'run_detail_timeline.dart';
|
||||
import 'run_detail_visit.dart';
|
||||
import 'run_detail_wide_chrome.dart';
|
||||
@@ -56,10 +60,15 @@ class RunDetailTabs extends StatefulWidget {
|
||||
this.initialStageKey,
|
||||
this.initialVisit,
|
||||
this.onSendToChat,
|
||||
this.failureActions,
|
||||
});
|
||||
|
||||
final JsonMap run;
|
||||
|
||||
/// What a failed run's "Why it failed" banner offers (Retry, Run again…,
|
||||
/// Open in chat); null offers none.
|
||||
final Widget? failureActions;
|
||||
|
||||
/// The host's own header: status, the run actions and notices. It floats
|
||||
/// outside the tab body, so switching tabs never drops an action.
|
||||
final Widget header;
|
||||
@@ -120,6 +129,19 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
|
||||
void initState() {
|
||||
super.initState();
|
||||
_applyInitialVisit();
|
||||
HardwareKeyboard.instance.addHandler(_tabDigitKey);
|
||||
}
|
||||
|
||||
/// A bare 1…4 outside text fields selects that tab of the shown ones.
|
||||
bool _tabDigitKey(KeyEvent event) {
|
||||
final index = runDetailTabDigit(event, HardwareKeyboard.instance);
|
||||
if (index == null || !mounted || !runDetailOwnsDigits(context)) {
|
||||
return false;
|
||||
}
|
||||
final tabs = _tabsFor(widget.run);
|
||||
if (index >= tabs.length) return false;
|
||||
if (_tab != tabs[index]) setState(() => _tab = tabs[index]);
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -136,6 +158,7 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
HardwareKeyboard.instance.removeHandler(_tabDigitKey);
|
||||
_inputSection.dispose();
|
||||
_outputSection.dispose();
|
||||
_liveRun.dispose();
|
||||
@@ -253,8 +276,8 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
|
||||
case RunArtifactTarget(:final url):
|
||||
_selectedStage = null;
|
||||
_selectedVisit = null;
|
||||
if (!_tabsFor(widget.run).contains(RunDetailTab.artifacts)) {
|
||||
// A run with no recorded steps has no gallery to open it in.
|
||||
if (_disabledTabs(widget.run).contains(RunDetailTab.artifacts)) {
|
||||
// A run with no recorded artifacts has no gallery to open it in.
|
||||
_tab = RunDetailTab.summary;
|
||||
WidgetsBinding.instance.addPostFrameCallback(
|
||||
(_) => mounted ? _showSearchArtifactMissingNotice() : null,
|
||||
@@ -369,18 +392,19 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Artifacts once the run has recorded steps; Changes once it has stopped
|
||||
/// executing, since a snapshot would not follow live captures.
|
||||
/// Every tab but Changes always, so a tab never moves between runs;
|
||||
/// Changes (the last) once the run has stopped executing, since a snapshot
|
||||
/// would not follow live captures.
|
||||
List<RunDetailTab> _tabsFor(JsonMap run) => [
|
||||
for (final tab in renderedRunDetailTabs)
|
||||
if (switch (tab) {
|
||||
RunDetailTab.artifacts => showRunArtifactsAction(run),
|
||||
RunDetailTab.changes => showRunChangesAction(run),
|
||||
_ => true,
|
||||
})
|
||||
tab,
|
||||
if (tab != RunDetailTab.changes || showRunChangesAction(run)) tab,
|
||||
];
|
||||
|
||||
/// Artifacts stays in place but disabled while the run recorded none.
|
||||
Set<RunDetailTab> _disabledTabs(JsonMap run) => {
|
||||
if (runArtifactCount(run) == 0) RunDetailTab.artifacts,
|
||||
};
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// A selected visit opens on its own page; the tab keeps the list.
|
||||
@@ -388,8 +412,12 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
|
||||
_syncVisitPage();
|
||||
}
|
||||
final tabs = _tabsFor(widget.run);
|
||||
// A tab the run no longer offers falls back to Summary.
|
||||
final shown = tabs.contains(_tab) || !renderedRunDetailTabs.contains(_tab)
|
||||
final disabled = _disabledTabs(widget.run);
|
||||
final artifactCount = runArtifactCount(widget.run);
|
||||
// A tab the run no longer offers (or cannot open) falls back to Summary.
|
||||
final shown =
|
||||
(tabs.contains(_tab) && !disabled.contains(_tab)) ||
|
||||
!renderedRunDetailTabs.contains(_tab)
|
||||
? _tab
|
||||
: RunDetailTab.summary;
|
||||
final edge = PageTabsEdge.of(context);
|
||||
@@ -403,29 +431,49 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
|
||||
child: widget.header,
|
||||
),
|
||||
);
|
||||
final tabStrip = RunDetailTabStrip(
|
||||
tabs: tabs,
|
||||
edge: edge,
|
||||
selected: shown,
|
||||
onSelected: (tab) => setState(() => _tab = tab),
|
||||
);
|
||||
void select(RunDetailTab tab) => setState(() => _tab = tab);
|
||||
final body = FadeThroughStack(
|
||||
key: ValueKey('run-detail-body-${widget.run['id']}'),
|
||||
index: tabs.indexOf(shown),
|
||||
lazy: true,
|
||||
children: [for (final tab in tabs) _body(tab)],
|
||||
);
|
||||
if (edge == FloatingBarEdge.top &&
|
||||
constraints.maxWidth >= kRunDetailWideChromeMinWidth) {
|
||||
// Beside a list the tabs and the header share one row under the
|
||||
// pane's bar, so only that row (not a header strip over a tabs
|
||||
// strip) sits above the tab's content.
|
||||
// Why a disabled Artifacts tab cannot open: none recorded, capture
|
||||
// pending or unavailable.
|
||||
final reasons = {
|
||||
RunDetailTab.artifacts: artifactsHeader(
|
||||
runDetailArtifactSteps(widget.run),
|
||||
executing: runDetailExecuting(widget.run),
|
||||
),
|
||||
};
|
||||
if (runDetailTabsOnTop(context, constraints.maxWidth)) {
|
||||
// A wide layout puts the tabs right under the run header, at the
|
||||
// top of the detail, in one strip with it.
|
||||
return FloatingBarOverlay(
|
||||
edge: FloatingBarEdge.top,
|
||||
bar: RunDetailWideChrome(tabs: tabStrip, header: header),
|
||||
bar: RunDetailWideChrome(
|
||||
header: header,
|
||||
tabs: RunDetailTopTabs(
|
||||
tabs: tabs,
|
||||
selected: shown,
|
||||
onSelected: select,
|
||||
artifactCount: artifactCount,
|
||||
disabled: disabled,
|
||||
disabledReasons: reasons,
|
||||
),
|
||||
),
|
||||
child: body,
|
||||
);
|
||||
}
|
||||
final tabStrip = RunDetailTabStrip(
|
||||
tabs: tabs,
|
||||
edge: edge,
|
||||
selected: shown,
|
||||
onSelected: select,
|
||||
artifactCount: artifactCount,
|
||||
disabled: disabled,
|
||||
disabledReasons: reasons,
|
||||
);
|
||||
// The header (status, actions, notices) is a glass strip floating
|
||||
// just under the top bar, so every tab scrolls behind both and pads
|
||||
// its first item clear of them at rest. Below it, the tabs float over
|
||||
@@ -458,6 +506,7 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
|
||||
onCopy: widget.onCopy,
|
||||
inputController: _inputSection,
|
||||
outputController: _outputSection,
|
||||
failureActions: widget.failureActions,
|
||||
graphPreview: RunGraphPreview(
|
||||
graph: detailGraph(widget.run),
|
||||
run: widget.run,
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'run_detail_tab.dart';
|
||||
import 'run_detail_tab_strip.dart';
|
||||
|
||||
/// The run detail's tabs on a wide layout: a Material [SegmentedButton] of
|
||||
/// icon-and-label segments under the run header, at the top of the detail
|
||||
/// where the eye already is, with labels at the button text size.
|
||||
///
|
||||
/// The segments keep their order and positions across runs: Artifacts is
|
||||
/// always one, disabled with a `0` count when the run recorded none. Keys
|
||||
/// match the phone bar's: the whole row `run-detail-tabs`, each label
|
||||
/// `run-detail-tab-<name>`.
|
||||
class RunDetailTopTabs extends StatelessWidget {
|
||||
const RunDetailTopTabs({
|
||||
super.key,
|
||||
required this.tabs,
|
||||
required this.selected,
|
||||
required this.onSelected,
|
||||
this.artifactCount,
|
||||
this.disabled = const {},
|
||||
this.disabledReasons = const {},
|
||||
});
|
||||
|
||||
final List<RunDetailTab> tabs;
|
||||
final RunDetailTab selected;
|
||||
final ValueChanged<RunDetailTab> onSelected;
|
||||
final int? artifactCount;
|
||||
final Set<RunDetailTab> disabled;
|
||||
|
||||
/// Why a disabled tab cannot open, as its tooltip.
|
||||
final Map<RunDetailTab, String> disabledReasons;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final count = artifactCount;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
return Align(
|
||||
key: const Key('run-detail-tabs'),
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: SegmentedButton<RunDetailTab>(
|
||||
showSelectedIcon: false,
|
||||
// On the frosted strip the unselected segments take the surface,
|
||||
// so the selected one's tonal fill stands out from the glass.
|
||||
style: ButtonStyle(
|
||||
backgroundColor: WidgetStateProperty.resolveWith(
|
||||
(states) => states.contains(WidgetState.selected)
|
||||
? scheme.secondaryContainer
|
||||
: scheme.surface,
|
||||
),
|
||||
),
|
||||
segments: [
|
||||
for (final tab in tabs)
|
||||
ButtonSegment<RunDetailTab>(
|
||||
value: tab,
|
||||
enabled: !disabled.contains(tab),
|
||||
tooltip: disabled.contains(tab) ? disabledReasons[tab] : null,
|
||||
icon: Icon(tab.icon),
|
||||
label: Row(
|
||||
key: ValueKey('run-detail-tab-${tab.name}'),
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(tab.label),
|
||||
if (tab == RunDetailTab.artifacts && count != null) ...[
|
||||
const SizedBox(width: 6),
|
||||
RunArtifactsCount(count: count),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
selected: {selected},
|
||||
onSelectionChanged: (value) {
|
||||
if (value.isNotEmpty) onSelected(value.first);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import 'run_more_menu.dart';
|
||||
import 'run_pipeline_link.dart';
|
||||
import 'run_detail_content.dart';
|
||||
import 'run_detail_material.dart';
|
||||
import 'run_failure_actions.dart';
|
||||
import 'runs_controller.dart';
|
||||
import '../../../core/error_advice.dart';
|
||||
import '../../../ui/status/error_notice.dart';
|
||||
@@ -96,6 +97,14 @@ class _RunDetailViewState extends State<RunDetailView> {
|
||||
onSendToChat: widget.onSendToChat == null
|
||||
? null
|
||||
: (draft) => widget.onSendToChat!(context, run, draft),
|
||||
failureActions: RunFailureActions(
|
||||
run: run,
|
||||
gateway: widget.gateway,
|
||||
onRunChanged: widget.controller.acceptRunDetail,
|
||||
onRunOpened: widget.onRunOpened,
|
||||
onRunAgain: widget.onRunAgain,
|
||||
onOpenInChat: widget.onOpenInChat,
|
||||
),
|
||||
);
|
||||
// The top bar becomes the run's: Back to the list, its title over its
|
||||
// number, pipeline and version (a link to that pipeline when the host
|
||||
@@ -181,14 +190,41 @@ class _RunDetailViewState extends State<RunDetailView> {
|
||||
: widget.controller.error ?? 'Run details unavailable.';
|
||||
// Back stays available while the detail is pending as well as after a
|
||||
// failure, so a slow or refused request can never trap the destination.
|
||||
// The more menu is there from the first frame: while the detail loads its
|
||||
// items are listed from the run's list row, disabled until the detail
|
||||
// they act on arrives.
|
||||
final pending = _pendingRun();
|
||||
return ShellBar(
|
||||
title: 'Run',
|
||||
onBack: widget.onBack,
|
||||
hideNavigation: true,
|
||||
actions: [
|
||||
if (loading && pending != null)
|
||||
RunMoreMenu(
|
||||
run: pending,
|
||||
gateway: widget.gateway,
|
||||
onRunChanged: widget.controller.acceptRunDetail,
|
||||
onDeleted: widget.controller.applyDeletion,
|
||||
onOpenInChat: widget.onOpenInChat,
|
||||
onRunAgain: widget.onRunAgain,
|
||||
pending: true,
|
||||
),
|
||||
],
|
||||
child: _placeholderBody(loading, message),
|
||||
);
|
||||
}
|
||||
|
||||
/// The selected run as its list row knows it, else only its id; null when
|
||||
/// no run is selected.
|
||||
JsonMap? _pendingRun() {
|
||||
final id = widget.controller.selectedRunId;
|
||||
if (id == null) return null;
|
||||
for (final run in widget.controller.runs) {
|
||||
if (run['id'] == id) return run;
|
||||
}
|
||||
return {'id': id};
|
||||
}
|
||||
|
||||
Widget _placeholderBody(bool loading, String message) {
|
||||
return Center(
|
||||
child: Column(
|
||||
|
||||
@@ -1,26 +1,31 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../../../ui/adaptive/floating_bar_layout.dart';
|
||||
import '../../../ui/adaptive/floating_destination_bar.dart';
|
||||
import '../../../ui/adaptive/glass_pill.dart';
|
||||
import '../../../ui/adaptive/top_glass_strip.dart';
|
||||
|
||||
/// The narrowest detail pane that puts its tabs and header in one row;
|
||||
/// narrower panes stack the header strip over the tabs.
|
||||
/// The narrowest detail pane that puts its tabs under the run header.
|
||||
const double kRunDetailWideChromeMinWidth = kFloatingBarWideWidth;
|
||||
|
||||
/// The most of the row the tabs take, leaving the rest to the header.
|
||||
const double kRunDetailWideTabsShare = 0.6;
|
||||
/// The narrowest window whose run detail puts its tabs at the top: a wide
|
||||
/// (desktop or tablet) window. Phones keep the floating bottom tab bar.
|
||||
const double kRunDetailTopTabsMinWindowWidth = 840;
|
||||
|
||||
/// The run detail's controls beside a list (a wide split): its tabs and its
|
||||
/// header (status, run actions, notices) share one row under the pane's top
|
||||
/// bar, instead of stacking the header strip above a second tabs strip.
|
||||
/// Whether the run detail at [context], [width] wide, shows its tabs under
|
||||
/// the run header rather than as the floating bottom bar: on a wide window
|
||||
/// with a wide enough detail pane, or where the host asks for top tabs.
|
||||
bool runDetailTabsOnTop(BuildContext context, double width) {
|
||||
if (width < kRunDetailWideChromeMinWidth) return false;
|
||||
return PageTabsEdge.of(context) == FloatingBarEdge.top ||
|
||||
MediaQuery.sizeOf(context).width >= kRunDetailTopTabsMinWindowWidth;
|
||||
}
|
||||
|
||||
/// The run detail's controls on a wide layout: one frosted strip under the
|
||||
/// pane's top bar holding the header (status, run actions, notices) and,
|
||||
/// under it, the tabs, so the tabs sit right below the run's title instead
|
||||
/// of floating at the far corner of a wide pane.
|
||||
///
|
||||
/// The tabs lead, in line with the bar's title; the header follows as a glass
|
||||
/// piece as wide as its content, and wraps (or scrolls inside its height
|
||||
/// limit) when the pane is narrow. Float the row with `FloatingBarOverlay`
|
||||
/// at the top edge so the tab body pads past it at rest. The header keeps the
|
||||
/// key `run-detail-header`.
|
||||
/// Float it with `FloatingBarOverlay` at the top edge so the tab body pads
|
||||
/// past it at rest. The strip keeps the key `run-detail-header`.
|
||||
class RunDetailWideChrome extends StatelessWidget {
|
||||
const RunDetailWideChrome({
|
||||
super.key,
|
||||
@@ -28,7 +33,7 @@ class RunDetailWideChrome extends StatelessWidget {
|
||||
required this.header,
|
||||
});
|
||||
|
||||
/// The tab strip at [FloatingBarEdge.top]; it brings its own 12px margins.
|
||||
/// The tabs (`RunDetailTopTabs`).
|
||||
final Widget tabs;
|
||||
|
||||
/// The header's content, already bounded in height.
|
||||
@@ -36,46 +41,19 @@ class RunDetailWideChrome extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final insets = MediaQuery.paddingOf(context);
|
||||
return Padding(
|
||||
padding: EdgeInsets.only(left: insets.left),
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) => Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
// The tabs keep at most 60% of the row, so the header always has
|
||||
// room for its status and actions (scaled text included).
|
||||
ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: constraints.maxWidth * kRunDetailWideTabsShare,
|
||||
),
|
||||
child: tabs,
|
||||
),
|
||||
Flexible(
|
||||
child: Padding(
|
||||
// The tabs' own trailing margin is the gap before the header.
|
||||
padding: EdgeInsets.only(
|
||||
right: FloatingDestinationBar.topMargin + insets.right,
|
||||
bottom: 8,
|
||||
),
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
heightFactor: 1,
|
||||
child: GlassPill(
|
||||
key: const Key('run-detail-header'),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(kTopGlassStripRadius),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: header,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
return TopGlassStrip(
|
||||
key: const Key('run-detail-header'),
|
||||
padding: const EdgeInsets.fromLTRB(0, 4, 0, 12),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
header,
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
child: tabs,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../actions/retry_action.dart';
|
||||
import '../actions/retry_eligibility.dart';
|
||||
import '../actions/retry_wording.dart';
|
||||
import 'run_again_flow.dart';
|
||||
|
||||
const runFailureRetryKey = ValueKey<String>('run-failure-retry');
|
||||
const runFailureRunAgainKey = ValueKey<String>('run-failure-run-again');
|
||||
const runFailureOpenInChatKey = ValueKey<String>('run-failure-open-in-chat');
|
||||
const runFailureOpenInChatLabel = 'Open in chat';
|
||||
|
||||
/// What a failed run's "Why it failed" banner offers: Retry (the server's
|
||||
/// retry, as the more menu's), Run again… (the New run form pre-filled from
|
||||
/// the run) and Open in chat (the run's send-to-chat flow, with its context).
|
||||
///
|
||||
/// Each is the existing action; one the host cannot apply is omitted. It stays
|
||||
/// mounted while a picked flow runs, so a retry's result reaches the run.
|
||||
class RunFailureActions extends StatefulWidget {
|
||||
const RunFailureActions({
|
||||
super.key,
|
||||
required this.run,
|
||||
required this.gateway,
|
||||
required this.onRunChanged,
|
||||
this.onRunOpened,
|
||||
this.onRunAgain,
|
||||
this.onOpenInChat,
|
||||
});
|
||||
|
||||
final JsonMap run;
|
||||
final ApiGateway gateway;
|
||||
final ValueChanged<JsonMap> onRunChanged;
|
||||
final ValueChanged<num>? onRunOpened;
|
||||
final ValueChanged<JsonMap>? onRunAgain;
|
||||
final Future<void> Function(BuildContext, JsonMap)? onOpenInChat;
|
||||
|
||||
@override
|
||||
State<RunFailureActions> createState() => _RunFailureActionsState();
|
||||
}
|
||||
|
||||
class _RunFailureActionsState extends State<RunFailureActions> {
|
||||
void _retry() => openRetryRunPrompt(
|
||||
context,
|
||||
run: widget.run,
|
||||
gateway: widget.gateway,
|
||||
onRunChanged: widget.onRunChanged,
|
||||
onRunOpened: widget.onRunOpened,
|
||||
owns: (owned) => mounted && retryRunId(widget.run) == owned,
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final run = widget.run;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final onBanner = TextButton.styleFrom(
|
||||
foregroundColor: scheme.onErrorContainer,
|
||||
);
|
||||
final runAgain = widget.onRunAgain;
|
||||
final openInChat = widget.onOpenInChat;
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
if (retryRunId(run) != null && canRetryRun(run))
|
||||
FilledButton.icon(
|
||||
key: runFailureRetryKey,
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: scheme.error,
|
||||
foregroundColor: scheme.onError,
|
||||
),
|
||||
onPressed: _retry,
|
||||
icon: const Icon(Icons.replay),
|
||||
label: const Text(retryActionLabel),
|
||||
),
|
||||
if (runAgain != null && canStartRunAgain(run))
|
||||
TextButton.icon(
|
||||
key: runFailureRunAgainKey,
|
||||
style: onBanner,
|
||||
onPressed: () => runAgain(run),
|
||||
icon: const Icon(Icons.edit_note),
|
||||
label: const Text(runAgainActionLabel),
|
||||
),
|
||||
if (openInChat != null)
|
||||
TextButton.icon(
|
||||
key: runFailureOpenInChatKey,
|
||||
style: onBanner,
|
||||
onPressed: () => openInChat(context, run),
|
||||
icon: const Icon(Icons.chat_bubble_outline),
|
||||
label: const Text(runFailureOpenInChatLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,15 @@ import '../domain/run_outcome_line.dart';
|
||||
/// The run Summary's prominent "Why it failed" note: a failed run's recorded
|
||||
/// failure reason (else its diagnostic), selectable, at the top of the
|
||||
/// Summary so the reason is read before the facts. Nothing for other runs.
|
||||
///
|
||||
/// [actions] (the run's Retry, Run again… and Open in chat; see
|
||||
/// `RunFailureActions`) sit under the reason, so what to do next is beside
|
||||
/// why it failed.
|
||||
class RunFailureBanner extends StatelessWidget {
|
||||
const RunFailureBanner({super.key, required this.run});
|
||||
const RunFailureBanner({super.key, required this.run, this.actions});
|
||||
|
||||
final JsonMap run;
|
||||
final Widget? actions;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -53,6 +58,10 @@ class RunFailureBanner extends StatelessWidget {
|
||||
color: scheme.onErrorContainer,
|
||||
),
|
||||
),
|
||||
if (actions case final actions?) ...[
|
||||
const SizedBox(height: 8),
|
||||
actions,
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -38,8 +38,13 @@ class RunListRow extends StatelessWidget {
|
||||
this.onLongPress,
|
||||
this.onOpenInChat,
|
||||
this.onRunAgain,
|
||||
this.timeOfDay = false,
|
||||
});
|
||||
|
||||
/// The row sits under a day heading, so its time is the time of day
|
||||
/// (`09:12`) rather than a date the heading already names.
|
||||
final bool timeOfDay;
|
||||
|
||||
final ValueChanged<JsonMap>? onRunAgain;
|
||||
|
||||
final JsonMap run;
|
||||
@@ -137,6 +142,8 @@ class RunListRow extends StatelessWidget {
|
||||
title: Text(title),
|
||||
timeWidget: createdAt == null
|
||||
? null
|
||||
: timeOfDay
|
||||
? Text(runTimeOfDay(createdAt), key: ValueKey('run-row-time-$id'))
|
||||
: RelativeTimeLabel(instant: createdAt, now: now),
|
||||
subtitle: line(subtitle),
|
||||
compactSubtitle: line(compactSubtitle),
|
||||
|
||||
@@ -72,8 +72,13 @@ class RunMoreMenu extends StatefulWidget {
|
||||
this.onOpenInChat,
|
||||
this.onRunAgain,
|
||||
this.menuKey = runMoreMenuKey,
|
||||
this.pending = false,
|
||||
});
|
||||
|
||||
/// The run's detail is still loading: [run] is its list row (or only its
|
||||
/// id), so the items are listed but disabled until the detail arrives.
|
||||
final bool pending;
|
||||
|
||||
/// Opens the New run form pre-filled from this run (finished runs that
|
||||
/// did not fail); without it the menu offers no Run again.
|
||||
final ValueChanged<JsonMap>? onRunAgain;
|
||||
@@ -168,6 +173,7 @@ class _RunMoreMenuState extends State<RunMoreMenu> {
|
||||
_RunMoreItem.openInChat => Icons.chat_bubble_outline,
|
||||
},
|
||||
destructive: item == _RunMoreItem.delete,
|
||||
enabled: !widget.pending,
|
||||
),
|
||||
],
|
||||
onSelected: _pick,
|
||||
|
||||
@@ -247,7 +247,12 @@ class RunsList extends StatelessWidget {
|
||||
final last = next >= entries.length || entries[next].run == null;
|
||||
return Arrival(
|
||||
id: '${entry.run!['id']}',
|
||||
child: _runTile(context, entry.run!, divider: !last),
|
||||
child: _runTile(
|
||||
context,
|
||||
entry.run!,
|
||||
divider: !last,
|
||||
timeOfDay: !flatRunSorts.contains(controller.sort),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -310,7 +315,12 @@ class RunsList extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
|
||||
Widget _runTile(BuildContext context, JsonMap run, {bool divider = true}) {
|
||||
Widget _runTile(
|
||||
BuildContext context,
|
||||
JsonMap run, {
|
||||
bool divider = true,
|
||||
bool timeOfDay = false,
|
||||
}) {
|
||||
final id = run['id'];
|
||||
final selection = controller.selection;
|
||||
final now = DateTime.now();
|
||||
@@ -320,6 +330,7 @@ class RunsList extends StatelessWidget {
|
||||
memo: (
|
||||
MemoMap(run),
|
||||
divider,
|
||||
timeOfDay,
|
||||
selection.active,
|
||||
selection.contains(id),
|
||||
id == controller.selectedRunId,
|
||||
@@ -327,11 +338,18 @@ class RunsList extends StatelessWidget {
|
||||
onSelected,
|
||||
// An executing run's duration ticks inside the row, not from here.
|
||||
),
|
||||
builder: (context) => _runRow(run, id, now, divider: divider),
|
||||
builder: (context) =>
|
||||
_runRow(run, id, now, divider: divider, timeOfDay: timeOfDay),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _runRow(JsonMap run, Object? id, DateTime now, {bool divider = true}) {
|
||||
Widget _runRow(
|
||||
JsonMap run,
|
||||
Object? id,
|
||||
DateTime now, {
|
||||
bool divider = true,
|
||||
bool timeOfDay = false,
|
||||
}) {
|
||||
final selection = controller.selection;
|
||||
return RunListRow(
|
||||
selecting: selection.active,
|
||||
@@ -342,6 +360,7 @@ class RunsList extends StatelessWidget {
|
||||
onDeleted: controller.applyDeletion,
|
||||
run: run,
|
||||
divider: divider,
|
||||
timeOfDay: timeOfDay,
|
||||
selected: id == controller.selectedRunId,
|
||||
now: now,
|
||||
onTap: id is num ? () => onSelected(id) : null,
|
||||
|
||||
@@ -4,6 +4,7 @@ import '../chat/workspace/chat_center_stage_controller.dart';
|
||||
import '../chat/workspace/chat_float_shortcut.dart';
|
||||
import '../terminal/terminal_shortcuts.dart';
|
||||
import '../../shell/windows/window_shortcuts.dart';
|
||||
import '../../shell/shell_chat_actions_shortcut.dart';
|
||||
import '../../shell/shell_chat_shortcut.dart';
|
||||
import '../../shell/shell_cheatsheet_shortcut.dart';
|
||||
import '../../shell/shell_runs_pipelines_shortcut.dart';
|
||||
@@ -114,7 +115,21 @@ class KeyboardShortcutRegistry {
|
||||
action: 'Switch to another chat',
|
||||
keys: shellChatShortcutLabels(platform).join(', '),
|
||||
caveat:
|
||||
'On Chat: type to filter the open chats, Ctrl+N or Down and Ctrl+P or Up to move, Enter to open, Esc or the shortcut again to close.${web ? ' A browser tab keeps Ctrl+N (new window) for itself; use Down, or the installed app.' : ''}',
|
||||
'On Chat: the open chats, most recently used first, with the previous chat selected, so the shortcut then Enter goes back to it. Type to filter (matching closed chats are listed under Closed; Enter reopens one), Ctrl+N or Down and Ctrl+P or Up to move, Enter to open, Esc or the shortcut again to close.${web ? ' A browser tab keeps Ctrl+N (new window) for itself; use Down, or the installed app.' : ''}',
|
||||
),
|
||||
KeyboardShortcutEntry(
|
||||
group: KeyboardShortcutGroup.chat,
|
||||
action: 'New chat',
|
||||
keys: shellChatActionLabel(ShellChatAction.newChat, platform),
|
||||
caveat:
|
||||
'From any destination. In the terminal the key goes to the terminal.',
|
||||
),
|
||||
KeyboardShortcutEntry(
|
||||
group: KeyboardShortcutGroup.chat,
|
||||
action: 'Next chat needing you',
|
||||
keys: shellChatActionLabel(ShellChatAction.nextAttention, platform),
|
||||
caveat:
|
||||
'Opens the next chat waiting for you, with unread replies, or with a failed action, in list order; press again to cycle. In the terminal the key goes to the terminal.',
|
||||
),
|
||||
KeyboardShortcutEntry(
|
||||
group: KeyboardShortcutGroup.chat,
|
||||
@@ -134,6 +149,13 @@ class KeyboardShortcutRegistry {
|
||||
caveat:
|
||||
'While the slash command list is open above the composer. Esc dismisses it.',
|
||||
),
|
||||
KeyboardShortcutEntry(
|
||||
group: KeyboardShortcutGroup.chat,
|
||||
action: 'Find in chat',
|
||||
keys: _apple ? 'Cmd+F' : 'Ctrl+F',
|
||||
caveat:
|
||||
'Enter moves to an older match, Shift+Enter to a newer one; Esc closes and returns to the composer. Older history is searched on the server and loaded as needed. In the terminal the key goes to the terminal.',
|
||||
),
|
||||
KeyboardShortcutEntry(
|
||||
group: KeyboardShortcutGroup.chat,
|
||||
action: 'Toggle Files',
|
||||
@@ -273,6 +295,20 @@ class KeyboardShortcutRegistry {
|
||||
caveat:
|
||||
'Available when the Chat list is mounted; numbers select its visible item.',
|
||||
),
|
||||
const KeyboardShortcutEntry(
|
||||
group: KeyboardShortcutGroup.lists,
|
||||
action: 'Switch run detail tabs',
|
||||
keys: '1, 2, 3, 4',
|
||||
caveat:
|
||||
'In a run: Summary, Timeline, Artifacts, Changes, as the run offers them. Not while typing.',
|
||||
),
|
||||
const KeyboardShortcutEntry(
|
||||
group: KeyboardShortcutGroup.lists,
|
||||
action: 'Next or previous changed file',
|
||||
keys: 'J, K, Down, Up',
|
||||
caveat:
|
||||
'In Changes on a wide window, once the file list has focus; Enter opens the file on its own page. Not while typing.',
|
||||
),
|
||||
const KeyboardShortcutEntry(
|
||||
group: KeyboardShortcutGroup.lists,
|
||||
action: 'Resize a list pane',
|
||||
|
||||
@@ -93,8 +93,14 @@ class SettingsTextField extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
/// The filled primary and outlined secondary settings actions. Buttons wrap on
|
||||
/// a narrow window (or with large text) instead of overflowing.
|
||||
/// The settings actions: the emphasised one filled, the other outlined.
|
||||
/// Buttons wrap on a narrow window (or with large text) instead of
|
||||
/// overflowing.
|
||||
///
|
||||
/// [primaryOutlined] turns the order of emphasis around for a primary action
|
||||
/// that ends something (Disconnect): the secondary action leads as a tonal
|
||||
/// button and the primary follows outlined, so the filled emphasis never sits
|
||||
/// on the action that drops the connection.
|
||||
class SettingsActions extends StatelessWidget {
|
||||
const SettingsActions({
|
||||
super.key,
|
||||
@@ -104,6 +110,7 @@ class SettingsActions extends StatelessWidget {
|
||||
required this.onSecondary,
|
||||
this.primaryKey,
|
||||
this.secondaryKey,
|
||||
this.primaryOutlined = false,
|
||||
});
|
||||
|
||||
final String primaryLabel;
|
||||
@@ -112,24 +119,38 @@ class SettingsActions extends StatelessWidget {
|
||||
final VoidCallback onSecondary;
|
||||
final Key? primaryKey;
|
||||
final Key? secondaryKey;
|
||||
final bool primaryOutlined;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final primary = primaryOutlined
|
||||
? OutlinedButton(
|
||||
key: primaryKey,
|
||||
onPressed: onPrimary,
|
||||
child: Text(primaryLabel),
|
||||
)
|
||||
: FilledButton(
|
||||
key: primaryKey,
|
||||
onPressed: onPrimary,
|
||||
child: Text(primaryLabel),
|
||||
);
|
||||
final secondary = primaryOutlined
|
||||
? FilledButton.tonal(
|
||||
key: secondaryKey,
|
||||
onPressed: onSecondary,
|
||||
child: Text(secondaryLabel),
|
||||
)
|
||||
: OutlinedButton(
|
||||
key: secondaryKey,
|
||||
onPressed: onSecondary,
|
||||
child: Text(secondaryLabel),
|
||||
);
|
||||
return Wrap(
|
||||
spacing: settingsControlGap,
|
||||
runSpacing: settingsControlGap,
|
||||
children: <Widget>[
|
||||
FilledButton(
|
||||
key: primaryKey,
|
||||
onPressed: onPrimary,
|
||||
child: Text(primaryLabel),
|
||||
),
|
||||
OutlinedButton(
|
||||
key: secondaryKey,
|
||||
onPressed: onSecondary,
|
||||
child: Text(secondaryLabel),
|
||||
),
|
||||
],
|
||||
children: primaryOutlined
|
||||
? <Widget>[secondary, primary]
|
||||
: <Widget>[primary, secondary],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +55,8 @@ class SettingsConnectionSection extends StatelessWidget {
|
||||
SettingsActions(
|
||||
primaryLabel: controller.primaryActionLabel,
|
||||
secondaryLabel: controller.secondaryActionLabel,
|
||||
// Disconnect is outlined beside a tonal Reconnect.
|
||||
primaryOutlined: controller.connectionActive,
|
||||
primaryKey: controller.connectionActive
|
||||
? SettingsKeys.disconnect
|
||||
: SettingsKeys.connect,
|
||||
|
||||
@@ -12,6 +12,7 @@ import 'shell_navigation_bar.dart';
|
||||
import 'shell_rail_scope.dart';
|
||||
import 'list_pane_widths.dart';
|
||||
import 'shell_bar.dart';
|
||||
import 'shell_chat_actions_shortcut.dart';
|
||||
import 'shell_chat_shortcut.dart';
|
||||
import 'shell_cheatsheet.dart';
|
||||
import 'shell_cheatsheet_shortcut.dart';
|
||||
@@ -33,6 +34,7 @@ class AdaptiveShell extends StatefulWidget {
|
||||
this.onSearch,
|
||||
this.onOpenChat,
|
||||
this.onChatQuickSwitch,
|
||||
this.onChatAction,
|
||||
this.attentionCount = 0,
|
||||
this.runningRunCount,
|
||||
this.listPaneWidthStore = const SharedPreferencesListPaneWidthStore(),
|
||||
@@ -77,6 +79,11 @@ class AdaptiveShell extends StatefulWidget {
|
||||
/// the composer focus of [onOpenChat] there too.
|
||||
final VoidCallback? onChatQuickSwitch;
|
||||
|
||||
/// Runs after Alt+N or Alt+J (see [shellChatActionShortcut]) has shown the
|
||||
/// Chat destination: the host starts a new chat or opens the next chat
|
||||
/// needing the operator. Null leaves both chords unhandled.
|
||||
final ValueChanged<ShellChatAction>? onChatAction;
|
||||
|
||||
/// Runs needing the operator today, retained in the tab's accessible label.
|
||||
final int attentionCount;
|
||||
|
||||
@@ -410,8 +417,20 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// A terminal keeps its keys (Escape, Ctrl+/, Ctrl+digits).
|
||||
// A terminal keeps its keys (Escape, Ctrl+/, Ctrl+digits, Alt+N, Alt+J).
|
||||
if (primaryFocusIsTypingSurface()) return false;
|
||||
final chatAction = widget.onChatAction == null
|
||||
? null
|
||||
: shellChatActionShortcut(event, keyboard);
|
||||
if (chatAction != null) {
|
||||
// A dialog or popup over the shell keeps its keys.
|
||||
if (!_shellRouteHasKeyboard()) return false;
|
||||
if (event is KeyDownEvent) {
|
||||
if (_selected != AppDestination.chat) _select(AppDestination.chat);
|
||||
widget.onChatAction!(chatAction);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (_selected == AppDestination.search &&
|
||||
event is KeyDownEvent &&
|
||||
event.logicalKey == LogicalKeyboardKey.escape &&
|
||||
@@ -450,6 +469,16 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
|
||||
widget.onOpenChat?.call();
|
||||
}
|
||||
|
||||
/// Whether the keyboard is outside any dialog, sheet or menu (a page, such
|
||||
/// as a phone's open chat, is fine).
|
||||
bool _shellRouteHasKeyboard() {
|
||||
final focusedContext = FocusManager.instance.primaryFocus?.context;
|
||||
final focusedRoute = focusedContext == null
|
||||
? null
|
||||
: ModalRoute.of(focusedContext);
|
||||
return focusedRoute is! PopupRoute;
|
||||
}
|
||||
|
||||
/// A popup or nested viewer owns Escape before the underlying Search tab.
|
||||
bool _searchEscape() {
|
||||
final route = ModalRoute.of(context);
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// The app-wide chat actions bound to a bare Alt chord (Option on a Mac).
|
||||
enum ShellChatAction {
|
||||
/// Alt+N: a new chat, with the Chat list's create dialog.
|
||||
newChat,
|
||||
|
||||
/// Alt+J: the next chat waiting for the operator, unread or failed.
|
||||
nextAttention,
|
||||
}
|
||||
|
||||
/// The chat action [event] asks for, or null: Alt+N or Alt+J with no other
|
||||
/// modifier. Option+N and Option+J yield a dead key or a symbol on a Mac, so
|
||||
/// the key is matched by position as well. Repeats of a held chord match too,
|
||||
/// so the caller can swallow them; only the first press acts.
|
||||
///
|
||||
/// Neither chord is taken by Chromium, Firefox or Safari on Linux, Windows or
|
||||
/// macOS, nor by the app's other shortcuts (Alt+K, Alt+T, Alt+Y, Alt+E,
|
||||
/// Alt+`, Alt+/). The terminal keeps both for readline (Alt+N searches
|
||||
/// history), so the caller leaves them to it while it has the keyboard.
|
||||
ShellChatAction? shellChatActionShortcut(
|
||||
KeyEvent event,
|
||||
HardwareKeyboard keyboard,
|
||||
) {
|
||||
if (event is KeyUpEvent ||
|
||||
!keyboard.isAltPressed ||
|
||||
keyboard.isControlPressed ||
|
||||
keyboard.isMetaPressed ||
|
||||
keyboard.isShiftPressed) {
|
||||
return null;
|
||||
}
|
||||
bool key(LogicalKeyboardKey logical, PhysicalKeyboardKey physical) =>
|
||||
event.logicalKey == logical || event.physicalKey == physical;
|
||||
if (key(LogicalKeyboardKey.keyN, PhysicalKeyboardKey.keyN)) {
|
||||
return ShellChatAction.newChat;
|
||||
}
|
||||
if (key(LogicalKeyboardKey.keyJ, PhysicalKeyboardKey.keyJ)) {
|
||||
return ShellChatAction.nextAttention;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// [action]'s chord as it reads on [platform], for the help page.
|
||||
String shellChatActionLabel(
|
||||
ShellChatAction action, [
|
||||
TargetPlatform? platform,
|
||||
]) {
|
||||
final target = platform ?? defaultTargetPlatform;
|
||||
final apple = target == TargetPlatform.macOS || target == TargetPlatform.iOS;
|
||||
final letter = switch (action) {
|
||||
ShellChatAction.newChat => 'N',
|
||||
ShellChatAction.nextAttention => 'J',
|
||||
};
|
||||
return '${apple ? 'Option' : 'Alt'}+$letter';
|
||||
}
|
||||
@@ -197,6 +197,7 @@ class _FloatingDestinationBarState extends State<FloatingDestinationBar>
|
||||
final labels = FloatingDestinationLabels(
|
||||
key: FloatingDestinationBar.rowKey,
|
||||
labels: [for (final item in items) item.label],
|
||||
enabled: [for (final item in items) item.enabled],
|
||||
selected: currentIndex,
|
||||
buttonBuilder: (index) => _button(context, index),
|
||||
onTap: widget.onTap,
|
||||
@@ -267,6 +268,8 @@ class _FloatingDestinationBarState extends State<FloatingDestinationBar>
|
||||
iconSize: iconSize * size / _size,
|
||||
label: item.label,
|
||||
icon: selected ? item.selectedIcon ?? item.icon : item.icon,
|
||||
enabled: item.enabled,
|
||||
tooltip: item.tooltip,
|
||||
onTap: () => widget.onTap(index),
|
||||
),
|
||||
),
|
||||
@@ -281,8 +284,18 @@ class FloatingDestinationItem {
|
||||
required this.label,
|
||||
this.selectedIcon,
|
||||
this.key,
|
||||
this.enabled = true,
|
||||
this.tooltip,
|
||||
});
|
||||
|
||||
/// The tab's tooltip (and accessibility hint) instead of its label, such
|
||||
/// as why a disabled tab cannot open.
|
||||
final String? tooltip;
|
||||
|
||||
/// False shows the tab greyed out and takes no taps, so a tab that has
|
||||
/// nothing to show keeps its place in the bar.
|
||||
final bool enabled;
|
||||
|
||||
final Widget icon;
|
||||
|
||||
/// The tab's accessible name (and Material tooltip); not drawn.
|
||||
|
||||
@@ -7,11 +7,16 @@ class FloatingDestinationLabels extends StatelessWidget {
|
||||
const FloatingDestinationLabels({
|
||||
super.key,
|
||||
required this.labels,
|
||||
this.enabled = const [],
|
||||
required this.selected,
|
||||
required this.buttonBuilder,
|
||||
required this.onTap,
|
||||
});
|
||||
final List<String> labels;
|
||||
|
||||
/// Per label; a missing entry is enabled.
|
||||
final List<bool> enabled;
|
||||
bool _enabled(int index) => index >= enabled.length || enabled[index];
|
||||
final int selected;
|
||||
final Widget Function(int) buttonBuilder;
|
||||
final ValueChanged<int> onTap;
|
||||
@@ -36,7 +41,7 @@ class FloatingDestinationLabels extends StatelessWidget {
|
||||
GestureDetector(
|
||||
key: ValueKey('destination-label-${labels[index]}'),
|
||||
excludeFromSemantics: true,
|
||||
onTap: () => onTap(index),
|
||||
onTap: _enabled(index) ? () => onTap(index) : null,
|
||||
child: TextFieldTapRegion(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
@@ -46,7 +51,9 @@ class FloatingDestinationLabels extends StatelessWidget {
|
||||
child: Text(
|
||||
labels[index],
|
||||
style: style.copyWith(
|
||||
color: color,
|
||||
color: _enabled(index)
|
||||
? color
|
||||
: color.withValues(alpha: .38),
|
||||
fontWeight: index == selected
|
||||
? FontWeight.w600
|
||||
: style.fontWeight,
|
||||
|
||||
@@ -33,8 +33,16 @@ class FloatingTabButton extends StatelessWidget {
|
||||
required this.label,
|
||||
required this.icon,
|
||||
required this.onTap,
|
||||
this.enabled = true,
|
||||
this.tooltip,
|
||||
});
|
||||
|
||||
/// Shown (and given as the accessibility hint) instead of [label].
|
||||
final String? tooltip;
|
||||
|
||||
/// False greys the tab out and ignores taps; it keeps its place.
|
||||
final bool enabled;
|
||||
|
||||
final FloatingTabMotion motion;
|
||||
final int index;
|
||||
final int count;
|
||||
@@ -64,12 +72,14 @@ class FloatingTabButton extends StatelessWidget {
|
||||
child: Semantics(
|
||||
role: SemanticsRole.tab,
|
||||
selected: selected,
|
||||
enabled: enabled,
|
||||
hint: tooltip,
|
||||
button: true,
|
||||
label: kIsWeb ? label : '$label\n${_tabLabel(context)}',
|
||||
// Switching tabs does not unfocus a text field (the composer).
|
||||
child: TextFieldTapRegion(
|
||||
child: Tooltip(
|
||||
message: label,
|
||||
message: tooltip ?? label,
|
||||
excludeFromSemantics: true,
|
||||
child: button,
|
||||
),
|
||||
@@ -87,7 +97,9 @@ class FloatingTabButton extends StatelessWidget {
|
||||
return (
|
||||
tint: scheme.secondaryContainer,
|
||||
selectedIcon: scheme.onSecondaryContainer,
|
||||
icon: scheme.onSurfaceVariant,
|
||||
icon: enabled
|
||||
? scheme.onSurfaceVariant
|
||||
: scheme.onSurface.withValues(alpha: .38),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -105,7 +117,7 @@ class FloatingTabButton extends StatelessWidget {
|
||||
key: fillKey,
|
||||
decoration: decoration,
|
||||
child: InkResponse(
|
||||
onTap: onTap,
|
||||
onTap: enabled ? onTap : null,
|
||||
customBorder: const CircleBorder(),
|
||||
containedInkWell: true,
|
||||
highlightShape: BoxShape.circle,
|
||||
|
||||
@@ -28,6 +28,11 @@ const double _lineGap = 4;
|
||||
const appListRowSurfaceKey = ValueKey<String>('app-list-row-surface');
|
||||
const appListRowDividerKey = ValueKey<String>('app-list-row-divider');
|
||||
const appListRowAccentKey = ValueKey<String>('app-list-row-accent');
|
||||
const appListRowSelectionKey = ValueKey<String>('app-list-row-selection');
|
||||
|
||||
/// The width of a row's leading bar: the open row's accent, or an identity
|
||||
/// colour's mark.
|
||||
const double kAppListRowBarWidth = 4;
|
||||
|
||||
/// The app's one list row (runs, pipelines, chats, search results,
|
||||
/// schedules).
|
||||
@@ -42,7 +47,9 @@ const appListRowAccentKey = ValueKey<String>('app-list-row-accent');
|
||||
/// under the text column separates rows. Nothing has a fixed height: the row
|
||||
/// grows with text scaling and every line ellipsises.
|
||||
///
|
||||
/// [selected] paints the open row (Material `secondaryContainer`); [emphasized]
|
||||
/// [selected] paints the open row: Material `secondaryContainer` with one
|
||||
/// [selectionAccent] bar on its leading edge, the one selection style every
|
||||
/// list shares; [emphasized]
|
||||
/// marks unread/attention (a heavier title and an accent time). Rows ripple.
|
||||
class AppListRow extends StatelessWidget {
|
||||
const AppListRow({
|
||||
@@ -54,6 +61,7 @@ class AppListRow extends StatelessWidget {
|
||||
this.subtitle,
|
||||
this.compactSubtitle,
|
||||
this.detail,
|
||||
this.compactDetail = true,
|
||||
this.subtitleLeading,
|
||||
this.subtitleTrailing,
|
||||
this.menu,
|
||||
@@ -68,8 +76,14 @@ class AppListRow extends StatelessWidget {
|
||||
this.compactWidth = kAppListRowCompactWidth,
|
||||
this.accent,
|
||||
this.showAccentBorder = true,
|
||||
this.selectionAccent,
|
||||
});
|
||||
|
||||
/// The leading bar's colour on the open row; Material `primary` when null.
|
||||
/// Every list marks its open row the same way: the tonal fill plus this
|
||||
/// one bar.
|
||||
final Color? selectionAccent;
|
||||
|
||||
/// The item's own colour (a chat's highlight): a bar on the row's leading
|
||||
/// edge and a faint tint under an unselected row. The selected fill still
|
||||
/// marks the open row, so the two never read as one another.
|
||||
@@ -93,6 +107,10 @@ class AppListRow extends StatelessWidget {
|
||||
/// An optional third line under the subtitle (a failed run's reason), one
|
||||
/// ellipsised line in the subtitle style unless the widget styles itself.
|
||||
final Widget? detail;
|
||||
|
||||
/// Whether a compact row keeps [detail]; false leaves a narrow row its
|
||||
/// title and [compactSubtitle] only.
|
||||
final bool compactDetail;
|
||||
final Widget? subtitleLeading;
|
||||
final Widget? subtitleTrailing;
|
||||
final Widget? menu;
|
||||
@@ -184,14 +202,22 @@ class AppListRow extends StatelessWidget {
|
||||
// The colour bar runs the row's whole height, divider included, and
|
||||
// the tint fills the divider's inset too, so coloured rows read as
|
||||
// one band each.
|
||||
Widget marked(Widget row) => accent == null || !showAccentBorder
|
||||
// The open row's bar, else an identity colour's own bar.
|
||||
final bar = selected
|
||||
? selectionAccent ??
|
||||
accent ??
|
||||
Theme.of(context).colorScheme.primary
|
||||
: showAccentBorder
|
||||
? accent
|
||||
: null;
|
||||
Widget marked(Widget row) => bar == null
|
||||
? row
|
||||
: DecoratedBox(
|
||||
key: appListRowAccentKey,
|
||||
key: selected ? appListRowSelectionKey : appListRowAccentKey,
|
||||
position: DecorationPosition.foreground,
|
||||
decoration: BoxDecoration(
|
||||
border: BorderDirectional(
|
||||
start: BorderSide(color: accent!, width: 4),
|
||||
start: BorderSide(color: bar, width: kAppListRowBarWidth),
|
||||
),
|
||||
),
|
||||
child: row,
|
||||
@@ -276,7 +302,7 @@ class AppListRow extends StatelessWidget {
|
||||
// A compact row has no room beside its title: the time takes a line of
|
||||
// its own under the subtitle.
|
||||
final timeLine = compact ? time : null;
|
||||
final detailLine = detail == null
|
||||
final detailLine = detail == null || (compact && !compactDetail)
|
||||
? null
|
||||
: Padding(
|
||||
padding: const EdgeInsets.only(top: _lineGap),
|
||||
|
||||
@@ -140,6 +140,37 @@ void main() {
|
||||
expect(session.subscriptionError, contains('too many run subscriptions'));
|
||||
});
|
||||
|
||||
test('runs_resync watches again and advances the runs epoch', () async {
|
||||
// The server detached this connection's run watch because it fell behind
|
||||
// and discarded the frames it held; without a new subscribe the Runs
|
||||
// list and detail froze until the next reconnect.
|
||||
final channel = FakeChannel()..readyCompleter.complete();
|
||||
final client = PipelinesClient(channelFactory: (_) => channel);
|
||||
final session = AppSession(
|
||||
endpoint: Uri.parse('ws://example.test/connect'),
|
||||
client: client,
|
||||
);
|
||||
addTearDown(session.dispose);
|
||||
|
||||
await session.start();
|
||||
await flush();
|
||||
final subscribe =
|
||||
jsonDecode(channel.outgoing.single as String) as Map<String, dynamic>;
|
||||
channel.incoming.add(
|
||||
jsonEncode({'id': subscribe['id'], 'type': 'subscribe'}),
|
||||
);
|
||||
await flush();
|
||||
final epoch = session.runsEpoch;
|
||||
final connection = session.connectionEpoch;
|
||||
|
||||
channel.incoming.add(jsonEncode({'type': 'runs_resync'}));
|
||||
await flush();
|
||||
expect(types(channel), ['subscribe', 'subscribe']);
|
||||
expect(session.runsEpoch, greaterThan(epoch));
|
||||
expect(session.connectionEpoch, connection);
|
||||
expect(session.subscription, RunSubscriptionState.pending);
|
||||
});
|
||||
|
||||
test('dispose drops the watch and releases the client', () async {
|
||||
final channel = FakeChannel()..readyCompleter.complete();
|
||||
final client = PipelinesClient(channelFactory: (_) => channel);
|
||||
|
||||
@@ -13,7 +13,11 @@ import 'chat_registration_test.dart'
|
||||
|
||||
final _field = find.byKey(const Key('chat-quick-switch-field'));
|
||||
|
||||
Future<void> _replySessions(WidgetTester tester, FakeChannel channel) async {
|
||||
Future<void> _replySessions(
|
||||
WidgetTester tester,
|
||||
FakeChannel channel, {
|
||||
bool awaiting = false,
|
||||
}) async {
|
||||
final request = await waitForRequest(tester, channel, 'chat_sessions');
|
||||
channel.incoming.add(
|
||||
jsonEncode({
|
||||
@@ -22,7 +26,12 @@ Future<void> _replySessions(WidgetTester tester, FakeChannel channel) async {
|
||||
'chat_sessions': [
|
||||
{'id': 's1', 'title': 'Wire chat', 'directory': '/workspace/demo'},
|
||||
{'id': 's2', 'title': 'Second chat', 'directory': '/workspace/other'},
|
||||
{'id': 's3', 'title': 'Third chat', 'directory': '/workspace/demo'},
|
||||
{
|
||||
'id': 's3',
|
||||
'title': 'Third chat',
|
||||
'directory': '/workspace/demo',
|
||||
if (awaiting) 'activity': {'awaiting_operator': 1, 'seq': 1},
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
@@ -31,8 +40,9 @@ Future<void> _replySessions(WidgetTester tester, FakeChannel channel) async {
|
||||
|
||||
Future<FakeChannel> _mountOnChat(
|
||||
WidgetTester tester,
|
||||
PlatformRouteInformationProvider provider,
|
||||
) async {
|
||||
PlatformRouteInformationProvider provider, {
|
||||
bool awaiting = false,
|
||||
}) async {
|
||||
tester.view.physicalSize = const Size(1200, 900);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
@@ -48,10 +58,15 @@ Future<FakeChannel> _mountOnChat(
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
await _replySessions(tester, channel);
|
||||
await _replySessions(tester, channel, awaiting: awaiting);
|
||||
await replySubscribe(tester, channel);
|
||||
await replyHistory(tester, channel);
|
||||
await tester.pumpAndSettle();
|
||||
// A chat waiting for the operator pulses its badge, so it never settles.
|
||||
if (awaiting) {
|
||||
await tester.pump(const Duration(seconds: 1));
|
||||
} else {
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
expect(find.byType(ChatThreadView), findsOneWidget);
|
||||
return channel;
|
||||
}
|
||||
@@ -149,6 +164,81 @@ void main() {
|
||||
await _teardown(tester);
|
||||
});
|
||||
|
||||
testWidgets('the shortcut then Enter returns to the previous chat', (
|
||||
tester,
|
||||
) async {
|
||||
final provider = _provider();
|
||||
final channel = await _mountOnChat(tester, provider);
|
||||
await _chord(tester, LogicalKeyboardKey.controlLeft);
|
||||
await tester.enterText(_field, 'second');
|
||||
await tester.pump();
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
await tester.pump();
|
||||
await replySubscribe(tester, channel, index: 1);
|
||||
await replyHistory(tester, channel, index: 1);
|
||||
await tester.pumpAndSettle();
|
||||
expect(provider.value.uri.path, '/chat/s2');
|
||||
|
||||
await _chord(tester, LogicalKeyboardKey.controlLeft);
|
||||
// Most recent first: the open chat, then the one before it, selected.
|
||||
final rows = tester
|
||||
.widgetList<ListTile>(
|
||||
find.byWidgetPredicate(
|
||||
(w) =>
|
||||
w is ListTile && '${w.key}'.contains('chat-quick-switch-row'),
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
expect(
|
||||
rows.map((tile) => '${tile.key}'.split('row-').last.split("'").first),
|
||||
['s2', 's1', 's3'],
|
||||
);
|
||||
expect(rows[1].selected, isTrue);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
await tester.pumpAndSettle();
|
||||
expect(provider.value.uri.path, '/chat/s1');
|
||||
await _teardown(tester);
|
||||
});
|
||||
|
||||
testWidgets('Alt+J opens the next chat waiting for you', (tester) async {
|
||||
final provider = _provider();
|
||||
final channel = await _mountOnChat(tester, provider, awaiting: true);
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.keyJ);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
await replySubscribe(tester, channel, index: 1);
|
||||
await replyHistory(tester, channel, index: 1);
|
||||
await tester.pump(const Duration(seconds: 1));
|
||||
expect(provider.value.uri.path, '/chat/s3');
|
||||
|
||||
// Only the open chat needs you now: nothing else to go to.
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.keyJ);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
expect(provider.value.uri.path, '/chat/s3');
|
||||
expect(find.text('No other chat needs you.'), findsOneWidget);
|
||||
await _teardown(tester);
|
||||
});
|
||||
|
||||
testWidgets('Alt+N from Runs opens New chat', (tester) async {
|
||||
await _mountOnChat(tester, _provider());
|
||||
await tester.tap(find.byKey(const ValueKey('shell.destination.runs')));
|
||||
await tester.pump(const Duration(milliseconds: 600));
|
||||
FocusManager.instance.primaryFocus?.unfocus();
|
||||
await tester.pump();
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.keyN);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 600));
|
||||
expect(find.byType(Dialog), findsOneWidget);
|
||||
await _teardown(tester);
|
||||
});
|
||||
|
||||
testWidgets('elsewhere the shortcut still jumps to Chat', (tester) async {
|
||||
final provider = _provider();
|
||||
await _mountOnChat(tester, provider);
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/changes/changes.dart';
|
||||
|
||||
import 'fixtures.dart';
|
||||
import 'widget_hosts.dart';
|
||||
|
||||
String _patch(String path, String line) =>
|
||||
'--- "a/$path"\n'
|
||||
'+++ "b/$path"\n'
|
||||
'@@ -1,1 +1,1 @@\n'
|
||||
'-old $line\n'
|
||||
'+new $line\n';
|
||||
|
||||
List<JsonMap> _steps() => [
|
||||
stepFixture(
|
||||
fileChanges: captureFixture(
|
||||
files: [
|
||||
fileChangeFixture(path: 'lib/a.dart', patch: _patch('lib/a.dart', 'A')),
|
||||
fileChangeFixture(path: 'lib/b.dart', patch: _patch('lib/b.dart', 'B')),
|
||||
fileChangeFixture(path: 'lib/c.dart', patch: _patch('lib/c.dart', 'C')),
|
||||
],
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
Future<void> _pumpAt(
|
||||
WidgetTester tester,
|
||||
Size size, {
|
||||
bool finalOnly = true,
|
||||
}) async {
|
||||
tester.view.physicalSize = size;
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
await tester.pumpWidget(
|
||||
materialHost(ChangesViewer(steps: _steps(), finalOnly: finalOnly)),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
bool _shows(String text) =>
|
||||
find.textContaining(text, findRichText: true).evaluate().isNotEmpty;
|
||||
|
||||
void main() {
|
||||
testWidgets('a wide pane lists the files beside the first file\'s diff', (
|
||||
tester,
|
||||
) async {
|
||||
await _pumpAt(tester, const Size(1400, 900));
|
||||
expect(find.byKey(const ValueKey('changes-final-split')), findsOneWidget);
|
||||
expect(find.byType(FileDiffViewer), findsOneWidget);
|
||||
expect(
|
||||
find.byKey(const ValueKey('changes-split-diff-lib/a.dart')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(_shows('new A'), isTrue);
|
||||
expect(_shows('new B'), isFalse);
|
||||
});
|
||||
|
||||
testWidgets('tapping a file shows its diff without leaving the pane', (
|
||||
tester,
|
||||
) async {
|
||||
await _pumpAt(tester, const Size(1400, 900));
|
||||
await tester.tap(find.bySemanticsLabel(RegExp('^Show diff for lib/c')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(FileDiffPage), findsNothing);
|
||||
expect(
|
||||
find.byKey(const ValueKey('changes-split-diff-lib/c.dart')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(_shows('new C'), isTrue);
|
||||
});
|
||||
|
||||
testWidgets('j/k and the arrows move between files once focused', (
|
||||
tester,
|
||||
) async {
|
||||
await _pumpAt(tester, const Size(1400, 900));
|
||||
await tester.tap(find.bySemanticsLabel(RegExp('^Show diff for lib/a')));
|
||||
await tester.pumpAndSettle();
|
||||
Future<void> press(LogicalKeyboardKey key) async {
|
||||
await tester.sendKeyEvent(key);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
await press(LogicalKeyboardKey.keyJ);
|
||||
expect(_shows('new B'), isTrue);
|
||||
await press(LogicalKeyboardKey.arrowDown);
|
||||
expect(_shows('new C'), isTrue);
|
||||
// The last file stays selected rather than wrapping.
|
||||
await press(LogicalKeyboardKey.keyJ);
|
||||
expect(_shows('new C'), isTrue);
|
||||
await press(LogicalKeyboardKey.keyK);
|
||||
expect(_shows('new B'), isTrue);
|
||||
await press(LogicalKeyboardKey.arrowUp);
|
||||
expect(_shows('new A'), isTrue);
|
||||
// Enter opens the selected file on its own page.
|
||||
await press(LogicalKeyboardKey.enter);
|
||||
expect(find.byType(FileDiffPage), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a visit page splits too, under the visit heading', (
|
||||
tester,
|
||||
) async {
|
||||
await _pumpAt(tester, const Size(1400, 900), finalOnly: false);
|
||||
expect(
|
||||
find.byKey(const ValueKey('changes-visit-split-implementer-1')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.textContaining('Visit 1'), findsOneWidget);
|
||||
expect(_shows('new A'), isTrue);
|
||||
});
|
||||
|
||||
testWidgets('a phone keeps one row per file opening its own page', (
|
||||
tester,
|
||||
) async {
|
||||
await _pumpAt(tester, const Size(560, 1000));
|
||||
expect(find.byKey(const ValueKey('changes-final-split')), findsNothing);
|
||||
expect(find.byType(FileDiffViewer), findsNothing);
|
||||
await tester.tap(find.bySemanticsLabel(RegExp('^Open diff for lib/b')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(FileDiffPage), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'a detail pane beside a list splits from 720 px in a wide window',
|
||||
(tester) async {
|
||||
tester.view.physicalSize = const Size(1440, 900);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
Widget pane(double width) => materialHost(
|
||||
Align(
|
||||
alignment: Alignment.topRight,
|
||||
child: SizedBox(
|
||||
width: width,
|
||||
child: ChangesViewer(steps: _steps(), finalOnly: true),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(pane(900));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const ValueKey('changes-final-split')), findsOneWidget);
|
||||
await tester.pumpWidget(pane(600));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const ValueKey('changes-final-split')), findsNothing);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/ui/layout/app_list_row.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/screen.dart';
|
||||
@@ -175,7 +176,8 @@ void main() {
|
||||
final background = appLightTheme().scaffoldBackgroundColor;
|
||||
expect(origin.color, isNot(background), reason: 'the chat colour tints it');
|
||||
expect(origin.color.a, 1);
|
||||
expect(origin.markerWidth, 10);
|
||||
// The open row's one bar, as every list marks its open row.
|
||||
expect(origin.markerWidth, kAppListRowBarWidth);
|
||||
expect(origin.marker, isNotNull);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/transcript/chat_find_highlight.dart';
|
||||
|
||||
import 'chat_thread_fixtures.dart';
|
||||
|
||||
JsonMap _text(String text) => {'type': 'text', 'text': text};
|
||||
|
||||
/// Answers scoped searches with [searchHits] for history older than the
|
||||
/// loaded page.
|
||||
class _FindGateway extends FakeChatGateway {
|
||||
final searches = <JsonMap>[];
|
||||
List<JsonMap> searchHits = const [];
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
if (type == 'search') {
|
||||
searches.add(Map<String, dynamic>.from(fields['search'] as Map));
|
||||
return {
|
||||
'type': 'search_results',
|
||||
'search_results': {'results': searchHits},
|
||||
};
|
||||
}
|
||||
return super.call(type, fields);
|
||||
}
|
||||
}
|
||||
|
||||
final _newest = [
|
||||
for (var i = 0; i < 30; i++)
|
||||
chatMessage(
|
||||
'n$i',
|
||||
i.isEven ? 'user' : 'assistant',
|
||||
parts: [
|
||||
_text(i == 2 || i == 27 ? 'Needle at $i, and needle' : 'filler $i'),
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
final _older = [
|
||||
chatMessage('o1', 'user', parts: [_text('an old needle')]),
|
||||
chatMessage('o2', 'assistant', parts: [_text('nothing')]),
|
||||
];
|
||||
|
||||
Future<_FindGateway> _host(WidgetTester tester, {bool older = false}) async {
|
||||
tester.view.physicalSize = const Size(1000, 900);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
final gateway = _FindGateway()
|
||||
..history = (fields) async {
|
||||
final query = fields['chat_query'] as Map;
|
||||
if (query['cursor'] == 'c1') return chatPage(_older);
|
||||
return chatPage(_newest, cursor: older ? 'c1' : '', hasMore: older);
|
||||
};
|
||||
addTearDown(gateway.close);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: ChatThreadView(
|
||||
gateway: gateway,
|
||||
sessionId: 's',
|
||||
onBack: () {},
|
||||
drafts: MemoryChatDraftStore(),
|
||||
newOperationId: () => 'op',
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
await tester.pump();
|
||||
return gateway;
|
||||
}
|
||||
|
||||
Future<void> _ctrlF(WidgetTester tester) async {
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.keyF);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
String _count(WidgetTester tester) =>
|
||||
tester.widget<Text>(find.byKey(const ValueKey('chat-find-count'))).data!;
|
||||
|
||||
void main() {
|
||||
testWidgets('Ctrl+F finds in the chat, steps older with Enter and Esc '
|
||||
'returns to the composer', (tester) async {
|
||||
await _host(tester);
|
||||
await tester.tap(find.byType(EditableText).last);
|
||||
await tester.pump();
|
||||
await _ctrlF(tester);
|
||||
expect(find.byKey(const ValueKey('chat-find-field')), findsOneWidget);
|
||||
|
||||
await tester.enterText(
|
||||
find.byKey(const ValueKey('chat-find-field')),
|
||||
'needle',
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(_count(tester), '1 of 4');
|
||||
// Each built text with a match registers where it draws.
|
||||
final scope = tester.widget<ChatFindScope>(find.byType(ChatFindScope));
|
||||
expect(scope.controller, isNotNull);
|
||||
expect(scope.targets.texts, isNotEmpty);
|
||||
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
await tester.pumpAndSettle();
|
||||
expect(_count(tester), '2 of 4');
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
await tester.pumpAndSettle();
|
||||
expect(_count(tester), '3 of 4');
|
||||
// The match in message n2 is near the top of history: it is built now.
|
||||
expect(
|
||||
find.textContaining('Needle at 2', findRichText: true),
|
||||
findsWidgets,
|
||||
);
|
||||
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
|
||||
await tester.pumpAndSettle();
|
||||
expect(_count(tester), '2 of 4');
|
||||
|
||||
await tester.tap(find.byKey(const ValueKey('chat-find-case')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(_count(tester), '1 of 2');
|
||||
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const ValueKey('chat-find-field')), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('matches in unloaded history are counted from the server and '
|
||||
'reached by loading older pages', (tester) async {
|
||||
final gateway = await _host(tester, older: true);
|
||||
gateway.searchHits = [
|
||||
{
|
||||
'chat': {'message_id': 'o1', 'part': 0, 'offset': 7},
|
||||
},
|
||||
];
|
||||
await tester.tap(find.byType(EditableText).last);
|
||||
await tester.pump();
|
||||
await _ctrlF(tester);
|
||||
await tester.enterText(
|
||||
find.byKey(const ValueKey('chat-find-field')),
|
||||
'needle',
|
||||
);
|
||||
await tester.pump(const Duration(milliseconds: 300));
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.searches.single['scope'], 'chat:s');
|
||||
expect(gateway.searches.single['cursor'], '0|c1');
|
||||
expect(_count(tester), '1 of 5');
|
||||
|
||||
// Step to the oldest: it is only on the server, so the older page loads.
|
||||
for (var i = 0; i < 4; i++) {
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
expect(_count(tester), '5 of 5');
|
||||
expect(
|
||||
gateway.calls.where(
|
||||
(call) =>
|
||||
call.type == 'chat_messages' &&
|
||||
(call.fields['chat_query'] as Map)['cursor'] == 'c1',
|
||||
),
|
||||
isNotEmpty,
|
||||
);
|
||||
expect(
|
||||
find.textContaining('an old needle', findRichText: true),
|
||||
findsWidgets,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('Ctrl+F with no focus in the chat opens nothing', (tester) async {
|
||||
await _host(tester);
|
||||
expect(find.byKey(const ValueKey('chat-find-field')), findsNothing);
|
||||
// No focus in the chat at all: the pane's handler never sees the key.
|
||||
await _ctrlF(tester);
|
||||
expect(find.byKey(const ValueKey('chat-find-field')), findsNothing);
|
||||
});
|
||||
}
|
||||
@@ -31,6 +31,8 @@ class _Switcher {
|
||||
Future<_Switcher> _open(
|
||||
WidgetTester tester, {
|
||||
Size size = const Size(900, 800),
|
||||
List<String> recent = const [],
|
||||
String? currentId,
|
||||
}) async {
|
||||
tester.view.physicalSize = size;
|
||||
tester.view.devicePixelRatio = 1;
|
||||
@@ -54,6 +56,8 @@ Future<_Switcher> _open(
|
||||
onPressed: () => switcher.route = showChatQuickSwitch(
|
||||
context,
|
||||
sessions: controller,
|
||||
recent: () => recent,
|
||||
currentId: currentId,
|
||||
onSelected: (row) => switcher.chosen.add('${row['id']}'),
|
||||
),
|
||||
child: const Text('Open'),
|
||||
@@ -162,8 +166,20 @@ void main() {
|
||||
'build',
|
||||
);
|
||||
await tester.pump();
|
||||
// The closed chat titled "Closed build" is not offered.
|
||||
expect(_shown(tester), ['one']);
|
||||
// The closed chat titled "Closed build" follows under Closed.
|
||||
expect(_shown(tester), ['one', 'gone']);
|
||||
expect(
|
||||
find.byKey(const Key('chat-quick-switch-closed-header')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
tester.getTopLeft(find.text('Closed')).dy,
|
||||
lessThan(
|
||||
tester
|
||||
.getTopLeft(find.byKey(const Key('chat-quick-switch-row-gone')))
|
||||
.dy,
|
||||
),
|
||||
);
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('chat-quick-switch-field')),
|
||||
'zzz',
|
||||
@@ -213,6 +229,38 @@ void main() {
|
||||
await tester.pump();
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'no query: most recent first, the previous chat selected; Enter goes back',
|
||||
(tester) async {
|
||||
final switcher = await _open(
|
||||
tester,
|
||||
recent: ['three', 'two'],
|
||||
currentId: 'three',
|
||||
);
|
||||
expect(_shown(tester), ['three', 'two', 'one']);
|
||||
expect(_selected(tester), 'two');
|
||||
await _key(tester, LogicalKeyboardKey.enter);
|
||||
await tester.pumpAndSettle();
|
||||
expect(switcher.chosen, ['two']);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('rows mark working, needs you and unread chats', (tester) async {
|
||||
await _open(tester);
|
||||
final two = find.byKey(const Key('chat-quick-switch-row-two'));
|
||||
expect(
|
||||
find.descendant(
|
||||
of: two,
|
||||
matching: find.byKey(const Key('chat-quick-switch-marker-working')),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.byKey(const Key('chat-quick-switch-marker-needsYou')),
|
||||
findsNothing,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('a phone shows it as a full-width bottom sheet', (tester) async {
|
||||
await _open(tester, size: const Size(400, 800));
|
||||
expect(find.byType(Dialog), findsNothing);
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/data/chat_recency.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
void main() {
|
||||
test('touch moves a chat to the front and persists the order', () async {
|
||||
final store = MemoryChatRecencyStore(['b', 'a']);
|
||||
final recency = ChatRecency(store: store);
|
||||
await recency.load();
|
||||
expect(recency.ids, ['b', 'a']);
|
||||
recency.touch('a');
|
||||
recency.touch('c');
|
||||
expect(recency.ids, ['c', 'a', 'b']);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(store.ids, ['c', 'a', 'b']);
|
||||
});
|
||||
|
||||
test('a chat touched before the read stays in front', () async {
|
||||
final recency = ChatRecency(store: MemoryChatRecencyStore(['b', 'a']));
|
||||
recency.touch('a');
|
||||
await recency.load();
|
||||
expect(recency.ids, ['a', 'b']);
|
||||
});
|
||||
|
||||
test('keeps at most the limit', () async {
|
||||
final recency = ChatRecency(limit: 2);
|
||||
for (final id in ['a', 'b', 'c']) {
|
||||
recency.touch(id);
|
||||
}
|
||||
expect(recency.ids, ['c', 'b']);
|
||||
});
|
||||
|
||||
test('shared preferences keep the order per server', () async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
const one = SharedPreferencesChatRecencyStore(serverScope: 'one');
|
||||
const two = SharedPreferencesChatRecencyStore(serverScope: 'two');
|
||||
await one.write(['x', 'y']);
|
||||
expect(await one.read(), ['x', 'y']);
|
||||
expect(await two.read(), isEmpty);
|
||||
final reloaded = ChatRecency(store: one);
|
||||
await reloaded.load();
|
||||
expect(reloaded.ids, ['x', 'y']);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_find.dart';
|
||||
|
||||
void main() {
|
||||
final rows = [
|
||||
{
|
||||
'kind': 'user',
|
||||
'key': 'u1',
|
||||
'message': {
|
||||
'id': 'u1',
|
||||
'parts': [
|
||||
{'type': 'text', 'text': 'Find the Needle'},
|
||||
{'type': 'text', 'text': 'and another needle'},
|
||||
],
|
||||
},
|
||||
},
|
||||
{'kind': 'activity', 'key': 'x', 'label': 'needle in activity'},
|
||||
{
|
||||
'kind': 'assistant',
|
||||
'key': 'a1',
|
||||
'messageIds': ['a1', 'a2'],
|
||||
'parts': [
|
||||
{'type': 'reasoning', 'text': 'needle thoughts'},
|
||||
{'type': 'text', 'text': 'A **needle** here, needle there'},
|
||||
{'type': 'text', 'text': ' '},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
test('units are user turns and answer text parts as rendered', () {
|
||||
final units = chatFindUnits(rows, ['k0', 'k1', 'k2']);
|
||||
expect(units.map((u) => u.text), [
|
||||
'Find the Needle\nand another needle',
|
||||
'A **needle** here, needle there',
|
||||
]);
|
||||
expect(units.map((u) => u.rowKey), ['k0', 'k2']);
|
||||
expect(units.first.messageIds, ['u1']);
|
||||
expect(units.last.messageIds, ['a1', 'a2']);
|
||||
});
|
||||
|
||||
test('matches fold case unless asked, in display order', () {
|
||||
final units = chatFindUnits(rows, ['k0', 'k1', 'k2']);
|
||||
final folded = chatFindMatches(units, 'needle', caseSensitive: false);
|
||||
expect(folded.length, 4);
|
||||
expect(folded.first.start, 'Find the '.length);
|
||||
expect(folded.map((m) => m.ordinal), [0, 1, 0, 1]);
|
||||
final exact = chatFindMatches(units, 'Needle', caseSensitive: true);
|
||||
expect(exact.length, 1);
|
||||
});
|
||||
|
||||
test('regex characters in the query are literal', () {
|
||||
expect(chatFindRanges('a.b axb (c)', '.', caseSensitive: false), [
|
||||
(start: 1, end: 2),
|
||||
]);
|
||||
expect(chatFindRanges('a.b axb (c)', '(c)', caseSensitive: false), [
|
||||
(start: 8, end: 11),
|
||||
]);
|
||||
});
|
||||
|
||||
test('server hits parse from a scoped reply', () {
|
||||
final hits = ChatFindRemoteHit.fromReply({
|
||||
'search_results': {
|
||||
'results': [
|
||||
{
|
||||
'chat': {'message_id': 'm9', 'part': 1, 'offset': 4},
|
||||
},
|
||||
{
|
||||
'chat': {'message_id': 'm8'},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(hits.map((h) => (h.messageId, h.part, h.offset)), [
|
||||
('m9', 1, 4),
|
||||
('m8', 0, 0),
|
||||
]);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_live_frames.dart';
|
||||
|
||||
/// A frame the server joined from deltas 10..12 ("héllo ", "wörld ", "😀!")
|
||||
/// while this client's queue was backed up.
|
||||
Map<String, dynamic> joined() => {
|
||||
'session_id': 's',
|
||||
'message_id': 'm',
|
||||
'kind': 'text',
|
||||
'part': {'type': 'text', 'id': 'm-text-0'},
|
||||
'delta': 'héllo wörld 😀!',
|
||||
'seq_from': 10,
|
||||
'seq': 12,
|
||||
'delta_lens': [6, 6, 3],
|
||||
};
|
||||
|
||||
void main() {
|
||||
test('a joined frame drops exactly the deltas a page already holds', () {
|
||||
expect(chatDeltasAfter(joined(), 9)?['delta'], 'héllo wörld 😀!');
|
||||
final rest = chatDeltasAfter(joined(), 10)!;
|
||||
expect(rest['delta'], 'wörld 😀!');
|
||||
expect(rest['seq_from'], 11);
|
||||
expect(rest['delta_lens'], [6, 3]);
|
||||
expect(chatDeltasAfter(joined(), 11)?['delta'], '😀!');
|
||||
expect(chatDeltasAfter(joined(), 12), isNull);
|
||||
});
|
||||
|
||||
test('a plain numbered delta is folded whole or not at all', () {
|
||||
final plain = {'kind': 'text', 'delta': 'x', 'seq': 5};
|
||||
expect(chatDeltasAfter(plain, 4), same(plain));
|
||||
expect(chatDeltasAfter(plain, 5), isNull);
|
||||
});
|
||||
|
||||
test('admit trims a joined frame overlapping what was included', () {
|
||||
final live = ChatLiveFrames();
|
||||
final first = {'kind': 'text', 'delta': 'héllo ', 'seq': 10};
|
||||
expect(live.admit(first), same(first));
|
||||
// The rest arrives joined with the delta already shown.
|
||||
expect(live.admit(joined())?['delta'], 'wörld 😀!');
|
||||
expect(live.admit(joined()), isNull);
|
||||
});
|
||||
|
||||
test('settle folds back only the part of a joined frame past the page', () {
|
||||
final live = ChatLiveFrames();
|
||||
final read = live.beginRead();
|
||||
live.admit(joined());
|
||||
final page = {
|
||||
'liveSeq': 11,
|
||||
'liveParts': ['m-text-0'],
|
||||
'messages': [
|
||||
{
|
||||
'id': 'm',
|
||||
'role': 'assistant',
|
||||
'parts': [
|
||||
{'type': 'text', 'id': 'm-text-0', 'text': 'héllo wörld '},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
final messages = live.settle(read, page, [
|
||||
for (final message in page['messages'] as List)
|
||||
Map<String, dynamic>.from(message as Map),
|
||||
], replaced: (_) => true);
|
||||
final parts = messages.single['parts'] as List;
|
||||
expect((parts.single as Map)['text'], 'héllo wörld 😀!');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_attention_cycle.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_quick_switch_order.dart';
|
||||
|
||||
List<String> ids(List<JsonMap> rows) => [
|
||||
for (final row in rows) '${row['id']}',
|
||||
];
|
||||
|
||||
void main() {
|
||||
final rows = <JsonMap>[
|
||||
{'id': 'a', 'title': 'A'},
|
||||
{'id': 'b', 'title': 'B'},
|
||||
{'id': 'c', 'title': 'C'},
|
||||
{'id': 'd', 'title': 'D'},
|
||||
];
|
||||
|
||||
test('recently used chats lead, the rest keep their order', () {
|
||||
expect(ids(chatQuickSwitchByRecency(rows, ['c', 'x', 'a'])), [
|
||||
'c',
|
||||
'a',
|
||||
'b',
|
||||
'd',
|
||||
]);
|
||||
expect(ids(chatQuickSwitchByRecency(rows, const [])), ['a', 'b', 'c', 'd']);
|
||||
});
|
||||
|
||||
test('no query selects the chat used before the current one', () {
|
||||
final shown = chatQuickSwitchByRecency(rows, ['c', 'a']);
|
||||
expect(
|
||||
chatQuickSwitchInitialSelection(shown, currentId: 'c', emptyQuery: true),
|
||||
1,
|
||||
);
|
||||
// Not showing a chat: the most recent one.
|
||||
expect(
|
||||
chatQuickSwitchInitialSelection(shown, currentId: null, emptyQuery: true),
|
||||
0,
|
||||
);
|
||||
// A query selects the best match, even the current chat.
|
||||
expect(
|
||||
chatQuickSwitchInitialSelection(shown, currentId: 'c', emptyQuery: false),
|
||||
0,
|
||||
);
|
||||
expect(
|
||||
chatQuickSwitchInitialSelection(
|
||||
[rows.first],
|
||||
currentId: 'a',
|
||||
emptyQuery: true,
|
||||
),
|
||||
0,
|
||||
);
|
||||
});
|
||||
|
||||
test('closed chats, most recently closed first', () {
|
||||
expect(
|
||||
ids(
|
||||
chatQuickSwitchClosed([
|
||||
...rows,
|
||||
{'id': 'old', 'closed_at': 1},
|
||||
{'id': 'new', 'closed_at': 9},
|
||||
{'id': 'flag', 'closed': true},
|
||||
]),
|
||||
),
|
||||
['new', 'old', 'flag'],
|
||||
);
|
||||
});
|
||||
|
||||
test('markers: needs you, working, unread', () {
|
||||
expect(
|
||||
chatQuickSwitchMarkers({
|
||||
'awaiting_operator': 2,
|
||||
'running': true,
|
||||
}, unread: true),
|
||||
[
|
||||
ChatQuickSwitchMarker.needsYou,
|
||||
ChatQuickSwitchMarker.working,
|
||||
ChatQuickSwitchMarker.unread,
|
||||
],
|
||||
);
|
||||
expect(chatQuickSwitchMarkers({'id': 'a'}, unread: false), isEmpty);
|
||||
});
|
||||
|
||||
group('next chat needing attention', () {
|
||||
final sessions = <JsonMap>[
|
||||
{'id': 'a', 'title': 'A', 'directory': '/x'},
|
||||
{'id': 'b', 'title': 'B', 'directory': '/x', 'awaiting_operator': 1},
|
||||
{'id': 'c', 'title': 'C', 'directory': '/x'},
|
||||
{'id': 'd', 'title': 'D', 'directory': '/x'},
|
||||
{'id': 'e', 'title': 'E', 'closed_at': 3, 'awaiting_operator': 1},
|
||||
];
|
||||
const unread = {'d'};
|
||||
const failed = {'a'};
|
||||
bool needs(JsonMap row) => chatNeedsAttention(
|
||||
row,
|
||||
unread: unread.contains(row['id']),
|
||||
failed: failed.contains(row['id']),
|
||||
);
|
||||
|
||||
test('cycles in list order, wrapping, skipping closed chats', () {
|
||||
expect(chatNextNeedingAttention(sessions, 'a', needs)?['id'], 'b');
|
||||
expect(chatNextNeedingAttention(sessions, 'b', needs)?['id'], 'd');
|
||||
expect(chatNextNeedingAttention(sessions, 'd', needs)?['id'], 'a');
|
||||
expect(chatNextNeedingAttention(sessions, 'c', needs)?['id'], 'd');
|
||||
expect(chatNextNeedingAttention(sessions, null, needs)?['id'], 'a');
|
||||
});
|
||||
|
||||
test('null when only the current chat needs the operator', () {
|
||||
bool onlyB(JsonMap row) => row['id'] == 'b';
|
||||
expect(chatNextNeedingAttention(sessions, 'b', onlyB), isNull);
|
||||
expect(chatNextNeedingAttention(sessions, 'a', onlyB)?['id'], 'b');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -58,13 +58,17 @@ void main() {
|
||||
of: row,
|
||||
matching: find.byKey(appListRowSurfaceKey),
|
||||
);
|
||||
// The lists' shared open-row style: the tonal fill and one bar.
|
||||
final color = tester.widget<Material>(surface).color;
|
||||
expect(color, const Color(0x00000000));
|
||||
final highlight = tester.widget<AnimatedContainer>(
|
||||
find.byKey(ValueKey('chat-visibility-$id')),
|
||||
final context = tester.element(row);
|
||||
expect(color == AppListRow.selectedColor(context), active);
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byKey(ValueKey('chat-visibility-$id')),
|
||||
matching: find.byKey(appListRowSelectionKey),
|
||||
),
|
||||
active ? findsOneWidget : findsNothing,
|
||||
);
|
||||
final fill = (highlight.decoration as BoxDecoration).color;
|
||||
expect(fill != null && fill.a > 0, active);
|
||||
}
|
||||
|
||||
expectRow('a', true);
|
||||
|
||||
@@ -210,16 +210,16 @@ void main() {
|
||||
),
|
||||
),
|
||||
);
|
||||
final surface = tester.widget<Material>(find.byKey(appListRowSurfaceKey));
|
||||
expect(surface.color, Colors.transparent);
|
||||
final highlight = tester.widget<AnimatedContainer>(
|
||||
find.byKey(const ValueKey('chat-visibility-s1')),
|
||||
);
|
||||
// The selected row is filled in its own colour.
|
||||
final fill = (highlight.decoration as BoxDecoration).color!;
|
||||
expect(fill.a, greaterThan(0));
|
||||
// The shared open-row style: the tonal fill, and its one bar in the
|
||||
// chat's own colour.
|
||||
final context = tester.element(find.byType(ChatSessionRow));
|
||||
expect(fill.withValues(alpha: 1), chatColorShade(context, 'amber'));
|
||||
final surface = tester.widget<Material>(find.byKey(appListRowSurfaceKey));
|
||||
expect(surface.color, AppListRow.selectedColor(context));
|
||||
final bar = tester.widget<DecoratedBox>(find.byKey(appListRowSelectionKey));
|
||||
final side =
|
||||
((bar.decoration as BoxDecoration).border as BorderDirectional).start;
|
||||
expect(side.color, chatColorShade(context, 'amber'));
|
||||
expect(side.width, kAppListRowBarWidth);
|
||||
expect(find.byKey(appListRowAccentKey), findsNothing);
|
||||
expect(find.byKey(const ValueKey('chat-visibility-s1')), findsOneWidget);
|
||||
});
|
||||
@@ -266,6 +266,45 @@ void main() {
|
||||
expect(gateway.count('chat_sessions'), lists);
|
||||
});
|
||||
|
||||
test('a push older than the row held is ignored', () async {
|
||||
JsonMap push(int revision, String color) => {
|
||||
'type': 'chat_session_changed',
|
||||
'chat_session': {
|
||||
'id': 's2',
|
||||
'title': 'Plain chat',
|
||||
'color': color,
|
||||
'revision': revision,
|
||||
},
|
||||
};
|
||||
// The server sends pushes concurrently: revision 7 lands before 6.
|
||||
gateway.pushed.add(push(7, 'pink'));
|
||||
gateway.pushed.add(push(6, 'blue'));
|
||||
await pumpEventQueue();
|
||||
expect(row('s2')['color'], 'pink');
|
||||
expect(row('s2')['revision'], 7);
|
||||
gateway.pushed.add(push(8, 'amber'));
|
||||
await pumpEventQueue();
|
||||
expect(row('s2')['color'], 'amber');
|
||||
// A list read older than the applied push does not revert it.
|
||||
var listed = <String, dynamic>{
|
||||
'id': 's2',
|
||||
'title': 'Plain chat',
|
||||
'directory': '/w',
|
||||
'revision': 5,
|
||||
};
|
||||
gateway.sessionsHandler = () async => {
|
||||
'chat_sessions': [listed],
|
||||
};
|
||||
await controller.refresh();
|
||||
expect(row('s2')['color'], 'amber');
|
||||
expect(row('s2')['revision'], 8);
|
||||
// A newer list row wins.
|
||||
listed = {...listed, 'color': 'teal', 'revision': 9};
|
||||
await controller.refresh();
|
||||
expect(row('s2')['color'], 'teal');
|
||||
expect(row('s2')['revision'], 9);
|
||||
});
|
||||
|
||||
test('a refused colour is undone and the reason shown', () async {
|
||||
gateway.failures['chat_color'] = 'unknown chat colour';
|
||||
await controller.setColor('s2', 'blue');
|
||||
|
||||
@@ -25,9 +25,20 @@ BorderSide edge(WidgetTester tester, String id) {
|
||||
return ((box.decoration as BoxDecoration).border as BorderDirectional).start;
|
||||
}
|
||||
|
||||
/// The shared open-row bar [AppListRow] draws on the selected row of [id].
|
||||
BorderSide? selectionBar(WidgetTester tester, String id) {
|
||||
final bar = find.descendant(
|
||||
of: find.byKey(ValueKey('chat-visibility-$id')),
|
||||
matching: find.byKey(appListRowSelectionKey),
|
||||
);
|
||||
if (bar.evaluate().isEmpty) return null;
|
||||
final box = tester.widget<DecoratedBox>(bar);
|
||||
return ((box.decoration as BoxDecoration).border as BorderDirectional).start;
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets(
|
||||
'only visible chats have an edge; active edge widens continuously',
|
||||
'visible chats have a thin edge; the open chat has the shared selection',
|
||||
(tester) async {
|
||||
tester.platformDispatcher.accessibilityFeaturesTestValue =
|
||||
const FakeAccessibilityFeatures(disableAnimations: false);
|
||||
@@ -72,19 +83,25 @@ void main() {
|
||||
),
|
||||
),
|
||||
);
|
||||
// A selected chat not shown in a pane wears only the shared selection.
|
||||
expect(edge(tester, 'off').style, BorderStyle.none);
|
||||
expect(selectionBar(tester, 'off')!.width, kAppListRowBarWidth);
|
||||
// A chat visible elsewhere keeps its thin edge.
|
||||
expect(edge(tester, 'on').width, 3);
|
||||
expect(selectionBar(tester, 'on'), isNull);
|
||||
expect(find.byKey(appListRowAccentKey), findsNothing);
|
||||
update(() => active = true);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
expect(edge(tester, 'on').width, greaterThan(3));
|
||||
expect(edge(tester, 'on').width, lessThan(8));
|
||||
await tester.pumpAndSettle();
|
||||
expect(edge(tester, 'on').width, 8);
|
||||
// Opened, it is marked exactly like any open row: one bar in the
|
||||
// chat's colour over the tonal fill, and no second edge.
|
||||
expect(edge(tester, 'on').style, BorderStyle.none);
|
||||
final bar = selectionBar(tester, 'on')!;
|
||||
expect(bar.width, kAppListRowBarWidth);
|
||||
expect(bar.color, isNot(Colors.transparent));
|
||||
update(() => active = false);
|
||||
await tester.pumpAndSettle();
|
||||
expect(edge(tester, 'on').width, 3);
|
||||
expect(selectionBar(tester, 'on'), isNull);
|
||||
},
|
||||
);
|
||||
testWidgets('compact chats keep identity colours and visible/active edges', (
|
||||
@@ -128,7 +145,18 @@ void main() {
|
||||
await tester.tap(find.byTooltip('New chat'));
|
||||
expect(newChatPressed, isTrue);
|
||||
expect(find.byTooltip('Expand chat list'), findsOneWidget);
|
||||
expect(edge(tester, 'a').width, 8);
|
||||
// The open chat: no second edge, the shared fill and bar instead.
|
||||
expect(edge(tester, 'a').style, BorderStyle.none);
|
||||
final open = tester
|
||||
.widgetList<AnimatedContainer>(
|
||||
find.descendant(
|
||||
of: find.byKey(const ValueKey('chat-visibility-a')),
|
||||
matching: find.byType(AnimatedContainer),
|
||||
),
|
||||
)
|
||||
.singleWhere((box) => box.foregroundDecoration != null);
|
||||
final bar = (open.foregroundDecoration as BoxDecoration).border;
|
||||
expect((bar as BorderDirectional).start.width, kAppListRowBarWidth);
|
||||
expect(edge(tester, 'b').width, 3);
|
||||
expect(edge(tester, 'c').style, BorderStyle.none);
|
||||
final avatars = tester
|
||||
|
||||
@@ -48,31 +48,36 @@ void main() {
|
||||
.setMockMethodCallHandler(SystemChannels.platform, null),
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'fenced code reveals Copy without shifting and copies exact whitespace',
|
||||
(tester) async {
|
||||
const code = ' final x = 1;\n\tkeep spaces ';
|
||||
await tester.pumpWidget(_host('```dart\n$code\n```'));
|
||||
await tester.pumpAndSettle();
|
||||
final before = tester.getTopLeft(find.text(code));
|
||||
expect(find.text('Copy').hitTestable(), findsNothing);
|
||||
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
|
||||
await mouse.addPointer(location: const Offset(1, 1));
|
||||
await mouse.moveTo(tester.getCenter(find.text(code)));
|
||||
await tester.pump();
|
||||
expect(find.text('Copy').hitTestable(), findsOneWidget);
|
||||
expect(tester.getTopLeft(find.text(code)), before);
|
||||
await tester.tap(find.text('Copy').hitTestable());
|
||||
await tester.pump();
|
||||
expect(copied, code);
|
||||
expect(find.text('Copied').hitTestable(), findsOneWidget);
|
||||
await mouse.moveTo(const Offset(1, 1));
|
||||
await tester.pump();
|
||||
expect(find.text('Copied').hitTestable(), findsNothing);
|
||||
await mouse.removePointer();
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
);
|
||||
testWidgets('fenced code has a header strip with its language and Copy', (
|
||||
tester,
|
||||
) async {
|
||||
const code = ' final x = 1;\n\tkeep spaces ';
|
||||
await tester.pumpWidget(_host('```dart\n$code\n```'));
|
||||
await tester.pumpAndSettle();
|
||||
// One framed block: the header strip (label and Copy) sits on top of
|
||||
// the code, inside the block, and Copy needs no hover (touch has none).
|
||||
final header = tester.getRect(find.byKey(const Key('chat-code-header')));
|
||||
final block = tester.getRect(find.byKey(const Key('chat-code-body')));
|
||||
final label = tester.getRect(find.text('dart'));
|
||||
final copy = tester.getRect(find.text('Copy').hitTestable());
|
||||
expect(header.top, block.top);
|
||||
expect(header.contains(label.center), isTrue);
|
||||
expect(header.contains(copy.center), isTrue);
|
||||
expect(tester.getTopLeft(find.text(code)).dy, greaterThan(header.bottom));
|
||||
expect(block.contains(tester.getCenter(find.text(code))), isTrue);
|
||||
final before = tester.getTopLeft(find.text(code));
|
||||
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
|
||||
await mouse.addPointer(location: const Offset(1, 1));
|
||||
await mouse.moveTo(tester.getCenter(find.text(code)));
|
||||
await tester.pump();
|
||||
expect(tester.getTopLeft(find.text(code)), before);
|
||||
await tester.tap(find.text('Copy').hitTestable());
|
||||
await tester.pump();
|
||||
expect(copied, code);
|
||||
expect(find.text('Copied').hitTestable(), findsOneWidget);
|
||||
await mouse.removePointer();
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'inline spans retain selection, hover transfer and copy the right raw snippet',
|
||||
@@ -168,11 +173,11 @@ void main() {
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets('keyboard focus exposes the reserved block action', (
|
||||
testWidgets('the block action is reachable from the keyboard', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(_host('```text\nraw\n```'));
|
||||
expect(find.text('Copy').hitTestable(), findsNothing);
|
||||
expect(find.text('Copy').hitTestable(), findsOneWidget);
|
||||
// The selectable transcript itself is the first focus stop.
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
|
||||
await tester.pump();
|
||||
|
||||
@@ -45,6 +45,9 @@ Widget _host({
|
||||
);
|
||||
}
|
||||
|
||||
/// The chevron over the faded side with more content.
|
||||
Finder _more(String side) => find.byKey(Key('chat-horizontal-more-$side'));
|
||||
|
||||
ScrollController _controller(WidgetTester tester) =>
|
||||
tester.widget<Scrollbar>(find.byType(Scrollbar)).controller!;
|
||||
|
||||
@@ -55,14 +58,16 @@ void main() {
|
||||
(tester) async {
|
||||
await tester.pumpWidget(_host(brightness: brightness));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Scroll horizontally'), findsOneWidget);
|
||||
expect(find.byKey(const Key('chat-horizontal-fade')), findsOneWidget);
|
||||
final controller = _controller(tester);
|
||||
expect(controller.position.maxScrollExtent, 640);
|
||||
expect(
|
||||
tester.widget<Scrollbar>(find.byType(Scrollbar)).thumbVisibility,
|
||||
isTrue,
|
||||
);
|
||||
expect(find.byIcon(Icons.arrow_forward), findsOneWidget);
|
||||
// More content to the right: that side fades under a chevron.
|
||||
expect(_more('right'), findsOneWidget);
|
||||
expect(_more('left'), findsNothing);
|
||||
final focus = tester
|
||||
.widgetList<Focus>(find.byType(Focus))
|
||||
.firstWhere(
|
||||
@@ -73,15 +78,17 @@ void main() {
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
|
||||
await tester.pumpAndSettle();
|
||||
expect(controller.offset, 80);
|
||||
expect(find.byIcon(Icons.swap_horiz), findsOneWidget);
|
||||
expect(_more('left'), findsOneWidget);
|
||||
expect(_more('right'), findsOneWidget);
|
||||
controller.jumpTo(controller.position.maxScrollExtent);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byIcon(Icons.arrow_back), findsOneWidget);
|
||||
expect(_more('left'), findsOneWidget);
|
||||
expect(_more('right'), findsNothing);
|
||||
await tester.pumpWidget(
|
||||
_host(brightness: brightness, contentWidth: 120),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Scroll horizontally'), findsNothing);
|
||||
expect(find.byKey(const Key('chat-horizontal-fade')), findsNothing);
|
||||
expect(tester.takeException(), isNull);
|
||||
},
|
||||
);
|
||||
@@ -92,9 +99,10 @@ void main() {
|
||||
(tester) async {
|
||||
await tester.pumpWidget(_host(direction: TextDirection.rtl));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byIcon(Icons.arrow_back), findsOneWidget);
|
||||
expect(_more('left'), findsOneWidget);
|
||||
expect(_more('right'), findsNothing);
|
||||
expect(
|
||||
tester.widget<Icon>(find.byIcon(Icons.arrow_back)).textDirection,
|
||||
tester.widget<Icon>(_more('left')).textDirection,
|
||||
TextDirection.ltr,
|
||||
);
|
||||
final controller = _controller(tester);
|
||||
@@ -169,7 +177,7 @@ void main() {
|
||||
find.bySemanticsLabel('Horizontally scrollable table'),
|
||||
findsNothing,
|
||||
);
|
||||
expect(find.text('Scroll horizontally'), findsOneWidget);
|
||||
expect(find.byKey(const Key('chat-horizontal-fade')), findsOneWidget);
|
||||
final viewport = tester.getRect(find.byType(ChatMarkdownView));
|
||||
expect(
|
||||
tester.getRect(find.byType(Table)).right,
|
||||
|
||||
@@ -27,7 +27,7 @@ void main() {
|
||||
'| No | Text | Ok |\n| --- | --- | --- |\n'
|
||||
'| one | ${List.filled(30, 'word').join(' ')} | done |',
|
||||
);
|
||||
expect(find.text('Scroll horizontally'), findsNothing);
|
||||
expect(find.byKey(const Key('chat-horizontal-fade')), findsNothing);
|
||||
expect(tableRect(tester).right, lessThanOrEqualTo(screenRight));
|
||||
final description = tester.getSize(find.textContaining('word word'));
|
||||
final status = tester.getSize(find.text('done'));
|
||||
@@ -55,7 +55,7 @@ void main() {
|
||||
'| --- | --- | --- | --- | --- | --- | --- |\n'
|
||||
'| a b | c d | e f | g h | i j | k l | m n |',
|
||||
);
|
||||
expect(find.text('Scroll horizontally'), findsOneWidget);
|
||||
expect(find.byKey(const Key('chat-horizontal-fade')), findsOneWidget);
|
||||
expect(
|
||||
find.bySemanticsLabel('Horizontally scrollable table'),
|
||||
findsOneWidget,
|
||||
@@ -76,7 +76,7 @@ void main() {
|
||||
'| Column | Notes |\n| --- | --- |\n'
|
||||
'| x | ${List.filled(40, 'note').join(' ')} |',
|
||||
);
|
||||
expect(find.text('Scroll horizontally'), findsNothing);
|
||||
expect(find.byKey(const Key('chat-horizontal-fade')), findsNothing);
|
||||
expect(tableRect(tester).right, lessThanOrEqualTo(screenRight));
|
||||
final header = tester.getSize(find.text('Column')).height;
|
||||
expect(header, tester.getSize(find.text('x')).height);
|
||||
|
||||
@@ -55,6 +55,11 @@ void main() {
|
||||
expect(find.textContaining('v2 · #'), findsNothing);
|
||||
expect(find.text('2 stages · 1 schedule'), findsOneWidget);
|
||||
expect(find.byKey(const Key('pipeline-status-1')), findsOneWidget);
|
||||
// The state is spelled out beside its dot, with when the run was.
|
||||
expect(
|
||||
tester.widget<Text>(find.byKey(const Key('pipeline-status-text-1'))).data,
|
||||
matches(RegExp(r'^Succeeded · last run .+')),
|
||||
);
|
||||
expect(find.byKey(const Key('pipeline-status-2')), findsOneWidget);
|
||||
expect(find.text('no runs recorded'), findsNothing);
|
||||
});
|
||||
@@ -142,7 +147,10 @@ void main() {
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.descendant(of: firstRow, matching: find.text('Succeeded')),
|
||||
find.descendant(
|
||||
of: firstRow,
|
||||
matching: find.textContaining(RegExp(r'^Succeeded( · .+)?$')),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
@@ -204,7 +212,10 @@ void main() {
|
||||
runs.complete(runListReply(fixture.runs));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.descendant(of: firstRow, matching: find.text('Succeeded')),
|
||||
find.descendant(
|
||||
of: firstRow,
|
||||
matching: find.textContaining(RegExp(r'^Succeeded( · .+)?$')),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:pipelines_app/features/pipelines/screen.dart';
|
||||
import 'package:pipelines_app/features/pipelines/ui/run_pipeline_wording.dart';
|
||||
import 'package:pipelines_app/features/pipelines/widgets/pipeline_row_actions.dart';
|
||||
|
||||
import 'package:pipelines_app/features/pipelines/pipeline_models.dart';
|
||||
import 'package:pipelines_app/ui/layout/app_overflow_menu.dart';
|
||||
|
||||
import '../fixtures.dart';
|
||||
import 'run_pipeline_launch_test.dart' show acceptedRun, launchGateway;
|
||||
|
||||
Future<void> _pump(WidgetTester tester, Size size, FakeGateway gateway) async {
|
||||
tester.view.physicalSize = size;
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
await tester.pumpWidget(MaterialApp(home: PipelinesScreen(gateway: gateway)));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
void main() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
|
||||
testWidgets('a wide list row has its own Run button opening the form', (
|
||||
tester,
|
||||
) async {
|
||||
final fixture = PipelineFixture();
|
||||
final gateway = launchGateway(fixture, onLaunch: (_) => acceptedRun(9));
|
||||
await _pump(tester, const Size(1440, 900), gateway);
|
||||
|
||||
expect(find.byKey(pipelineRowRunKey(1)), findsOneWidget);
|
||||
await tester.tap(find.byKey(pipelineRowRunKey(1)));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// The same New run form as the detail's Run, for the row's pipeline at
|
||||
// its listed version; opening it starts nothing.
|
||||
expect(find.byKey(runPipelinePromptKey), findsOneWidget);
|
||||
expect(gateway.callsOf('get_pipeline').last.fields, {
|
||||
'pipeline_id': 1,
|
||||
'version': 2,
|
||||
});
|
||||
expect(gateway.callsOf('run_pipeline'), isEmpty);
|
||||
// The row did not open the pipeline.
|
||||
expect(find.byKey(const Key('pipeline-detail')), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('a phone row offers Run… in its menu and no button', (
|
||||
tester,
|
||||
) async {
|
||||
final fixture = PipelineFixture();
|
||||
final gateway = launchGateway(fixture, onLaunch: (_) => acceptedRun(9));
|
||||
await _pump(tester, const Size(560, 900), gateway);
|
||||
|
||||
expect(find.byKey(pipelineRowRunKey(2)), findsNothing);
|
||||
await tester.tap(find.byKey(pipelineRowMenuKey(2)));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text(pipelineRowRunLabel));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byKey(runPipelinePromptKey), findsOneWidget);
|
||||
expect(gateway.callsOf('get_pipeline').last.fields['pipeline_id'], 2);
|
||||
});
|
||||
|
||||
test('an archived pipeline offers no Run, as its detail offers none', () {
|
||||
final archived = PipelineSummary.fromJson({
|
||||
...pipelineSummary(id: 4, name: 'Old'),
|
||||
'archived_at': '2026-10-01T00:00:00Z',
|
||||
});
|
||||
void run(BuildContext _) {}
|
||||
|
||||
expect(
|
||||
pipelineRowActions(pipeline: archived, wide: true, onRun: run),
|
||||
isNull,
|
||||
);
|
||||
// Send to chat stays; only Run is withheld.
|
||||
expect(
|
||||
pipelineRowActions(
|
||||
pipeline: archived,
|
||||
wide: true,
|
||||
onRun: run,
|
||||
onOpenInChat: run,
|
||||
),
|
||||
isA<AppOverflowMenu<Object?>>(),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/runs/data/runs_repository.dart';
|
||||
import 'package:pipelines_app/features/runs/ui/run_detail_view.dart';
|
||||
import 'package:pipelines_app/features/runs/ui/runs_controller.dart';
|
||||
import 'package:pipelines_app/ui/adaptive/floating_tab_button.dart';
|
||||
|
||||
import '../../artifacts/domain/artifact_fixtures.dart';
|
||||
|
||||
@@ -97,16 +98,44 @@ void main() {
|
||||
expect(find.text('reviewer · visit 1'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('the action is offered only when the detail has steps', (
|
||||
/// The Artifacts tab keeps its place on a run with none: disabled, badged
|
||||
/// `0`, and its tooltip (and accessibility hint) says why.
|
||||
Future<void> expectDisabledArtifacts(WidgetTester tester, String why) async {
|
||||
final tab = find.byKey(const ValueKey('run-detail-tab-artifacts'));
|
||||
expect(tab, findsOneWidget);
|
||||
final button = tester.widget<FloatingTabButton>(tab);
|
||||
expect(button.enabled, isFalse);
|
||||
expect(button.tooltip, why);
|
||||
expect(
|
||||
find.descendant(
|
||||
of: tab,
|
||||
matching: find.byKey(const ValueKey('run-detail-artifacts-count')),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.descendant(of: tab, matching: find.text('0')), findsOneWidget);
|
||||
// A tap does not open an empty gallery: Summary stays.
|
||||
await tester.tap(tab, warnIfMissed: false);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text(why), findsNothing);
|
||||
// Changes, after it, keeps its place.
|
||||
final order = [
|
||||
for (final name in ['summary', 'timeline', 'artifacts', 'changes'])
|
||||
tester.getCenter(find.byKey(ValueKey('run-detail-tab-$name'))).dx,
|
||||
];
|
||||
expect(order, orderedEquals([...order]..sort()));
|
||||
}
|
||||
|
||||
testWidgets('a run without steps keeps a disabled Artifacts tab', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _FakeGateway(_run(steps: const []));
|
||||
final controller = await _loaded(gateway);
|
||||
addTearDown(controller.dispose);
|
||||
await _pumpDetail(tester, controller, gateway);
|
||||
expect(
|
||||
find.byKey(const ValueKey('run-detail-tab-artifacts')),
|
||||
findsNothing,
|
||||
await expectDisabledArtifacts(
|
||||
tester,
|
||||
'No artifacts recorded for this run.',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -121,16 +150,10 @@ void main() {
|
||||
final controller = await _loaded(gateway);
|
||||
addTearDown(controller.dispose);
|
||||
await _pumpDetail(tester, controller, gateway);
|
||||
|
||||
await tester.ensureVisible(
|
||||
find.byKey(const ValueKey('run-detail-tab-artifacts')),
|
||||
await expectDisabledArtifacts(
|
||||
tester,
|
||||
'No artifacts recorded for this run.',
|
||||
);
|
||||
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.byKey(const ValueKey('run-detail-tab-artifacts')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('No artifacts recorded for this run.'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('an unavailable capture is never reported as empty', (
|
||||
@@ -142,16 +165,6 @@ void main() {
|
||||
final controller = await _loaded(gateway);
|
||||
addTearDown(controller.dispose);
|
||||
await _pumpDetail(tester, controller, gateway);
|
||||
|
||||
await tester.ensureVisible(
|
||||
find.byKey(const ValueKey('run-detail-tab-artifacts')),
|
||||
);
|
||||
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.byKey(const ValueKey('run-detail-tab-artifacts')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Artifacts · capture unavailable'), findsOneWidget);
|
||||
expect(find.text('No artifacts recorded for this run.'), findsNothing);
|
||||
await expectDisabledArtifacts(tester, 'Artifacts · capture unavailable');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,8 +10,8 @@ import 'package:pipelines_app/ui/adaptive/floating_bar_layout.dart';
|
||||
import 'run_detail_graph_support.dart';
|
||||
import 'run_detail_visit_support.dart';
|
||||
|
||||
/// The run and stage detail bodies are flat on the page, and beside a list one
|
||||
/// row of tabs and header.
|
||||
/// The run and stage detail bodies are flat on the page, and beside a list
|
||||
/// the tabs sit under the header in one strip.
|
||||
void main() {
|
||||
testWidgets('Summary and Timeline show their bodies', (tester) async {
|
||||
await pumpRunDetail(tester, RunDetailTestPlatform.material);
|
||||
@@ -28,7 +28,7 @@ void main() {
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('beside a list the tabs and the header share one row', (
|
||||
testWidgets('beside a list the tabs sit under the header at the top', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(720, 900);
|
||||
@@ -51,11 +51,13 @@ void main() {
|
||||
|
||||
final tabs = tester.getRect(find.byKey(const Key('run-detail-tabs')));
|
||||
final header = tester.getRect(find.byKey(const Key('run-detail-header')));
|
||||
// Side by side, not stacked: the header starts after the tabs and
|
||||
// overlaps them vertically.
|
||||
expect(header.left, greaterThanOrEqualTo(tabs.right - 12));
|
||||
expect(header.top, lessThan(tabs.bottom));
|
||||
expect(header.bottom, greaterThan(tabs.top));
|
||||
// One strip at the top: the tabs are inside it, at its foot, and the
|
||||
// whole strip sits near the top of the 900px detail.
|
||||
expect(tabs.top, greaterThan(header.top));
|
||||
expect(tabs.bottom, lessThanOrEqualTo(header.bottom));
|
||||
expect(tabs.left, greaterThanOrEqualTo(header.left));
|
||||
expect(header.top, lessThan(120));
|
||||
expect(tester.getRect(find.text('Summary')).top, greaterThan(header.top));
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/ui/adaptive/floating_destination_bar.dart';
|
||||
import 'package:pipelines_app/features/runs/ui/run_detail_top_tabs.dart';
|
||||
|
||||
import 'run_detail_graph_support.dart';
|
||||
|
||||
/// The selected tab's index, from the bottom bar (narrow) or the top
|
||||
/// segments (wide), whichever the layout shows.
|
||||
int _current(WidgetTester tester) {
|
||||
final bar = find.descendant(
|
||||
of: find.byKey(const Key('run-detail-tabs')),
|
||||
matching: find.byType(FloatingDestinationBar),
|
||||
);
|
||||
if (bar.evaluate().isNotEmpty) {
|
||||
return tester.widget<FloatingDestinationBar>(bar).currentIndex;
|
||||
}
|
||||
final segments = tester.widget<RunDetailTopTabs>(
|
||||
find.byType(RunDetailTopTabs),
|
||||
);
|
||||
return segments.tabs.indexOf(segments.selected);
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('bare 1-4 switch the run detail tabs', (tester) async {
|
||||
await pumpRunDetail(tester, RunDetailTestPlatform.material);
|
||||
expect(_current(tester), 0);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.digit2);
|
||||
await tester.pump();
|
||||
expect(_current(tester), 1);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.numpad1);
|
||||
await tester.pump();
|
||||
expect(_current(tester), 0);
|
||||
});
|
||||
|
||||
testWidgets('a modifier or a focused text field keeps the digit', (
|
||||
tester,
|
||||
) async {
|
||||
await pumpRunDetail(tester, RunDetailTestPlatform.material);
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.digit2);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
|
||||
await tester.pump();
|
||||
expect(_current(tester), 0);
|
||||
|
||||
// A text field over the detail (in an overlay of the same route) types.
|
||||
final field = TextEditingController();
|
||||
addTearDown(field.dispose);
|
||||
final overlay = OverlayEntry(
|
||||
builder: (_) => Material(
|
||||
child: TextField(key: const Key('probe-field'), controller: field),
|
||||
),
|
||||
);
|
||||
Overlay.of(
|
||||
tester.element(find.byKey(const Key('run-detail-tabs'))),
|
||||
).insert(overlay);
|
||||
await tester.pump();
|
||||
await tester.tap(find.byKey(const Key('probe-field')));
|
||||
await tester.pump();
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.digit2);
|
||||
await tester.pump();
|
||||
expect(_current(tester), 0);
|
||||
overlay.remove();
|
||||
});
|
||||
|
||||
testWidgets('a dialog over the run keeps the digits', (tester) async {
|
||||
await pumpRunDetail(tester, RunDetailTestPlatform.material);
|
||||
showDialog<void>(
|
||||
context: tester.element(find.byKey(const Key('run-detail-tabs'))),
|
||||
builder: (_) => const AlertDialog(content: Text('Over')),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.digit2);
|
||||
await tester.pump();
|
||||
Navigator.of(tester.element(find.text('Over'))).pop();
|
||||
await tester.pumpAndSettle();
|
||||
expect(_current(tester), 0);
|
||||
});
|
||||
}
|
||||
@@ -59,18 +59,21 @@ void main() {
|
||||
previous = center.dx;
|
||||
}
|
||||
expect(find.byKey(runMoreMenuKey), findsOneWidget);
|
||||
// The tabs are the floating glass bar: on this 900px detail it is sized
|
||||
// to its tabs at the right edge, above the bottom.
|
||||
final pill = tester.getRect(
|
||||
// On this wide 900px detail the tabs are Material segments under the
|
||||
// run header, at the top of the detail, not a floating bottom bar.
|
||||
final row = tester.getRect(strip);
|
||||
final header = tester.getRect(find.byKey(const Key('run-detail-header')));
|
||||
expect(find.byType(SegmentedButton<RunDetailTab>), findsOneWidget);
|
||||
expect(
|
||||
find.descendant(
|
||||
of: strip,
|
||||
matching: find.byKey(FloatingDestinationBar.rowKey),
|
||||
),
|
||||
findsNothing,
|
||||
);
|
||||
expect(pill.right, 900 - 16);
|
||||
expect(pill.bottom, 1000 - 16);
|
||||
// (The test font draws every glyph a full em wide.)
|
||||
expect(pill.width, lessThan(900 * 0.7));
|
||||
expect(row.top, greaterThan(header.top));
|
||||
expect(row.bottom, lessThanOrEqualTo(header.bottom));
|
||||
expect(row.top, lessThan(1000 / 3));
|
||||
|
||||
for (final tab in [
|
||||
RunDetailTab.timeline,
|
||||
@@ -122,19 +125,24 @@ void main() {
|
||||
greaterThanOrEqualTo(844 - pill.top),
|
||||
);
|
||||
|
||||
// Wide, the tabs move to the top under the header; the content still
|
||||
// fills the pane and starts below them at rest.
|
||||
await pumpRunDetail(tester, platform, size: const Size(1000, 844));
|
||||
final widePill = tester.getRect(
|
||||
final wideTabs = tester.getRect(strip);
|
||||
expect(wideTabs.top, lessThan(844 / 3));
|
||||
expect(
|
||||
find.descendant(
|
||||
of: strip,
|
||||
matching: find.byKey(FloatingDestinationBar.rowKey),
|
||||
),
|
||||
findsNothing,
|
||||
);
|
||||
expect(widePill.right, 1000 - 16);
|
||||
expect(widePill.bottom, 844 - 16);
|
||||
expect(widePill.width, lessThan(1000 * 0.6));
|
||||
// Beside the bar the content takes taps: the body fills the pane.
|
||||
expect(tester.getRect(body).left, 0);
|
||||
expect(tester.getRect(body).width, 1000);
|
||||
expect(
|
||||
MediaQuery.paddingOf(tester.element(body)).top,
|
||||
greaterThanOrEqualTo(wideTabs.bottom),
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('${platform.name} missing graph states the exact wording', (
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/runs/actions/retry_wording.dart';
|
||||
import 'package:pipelines_app/features/runs/actions/title_wording.dart';
|
||||
import 'package:pipelines_app/features/runs/screen.dart';
|
||||
import 'package:pipelines_app/features/runs/ui/run_failure_actions.dart';
|
||||
import 'package:pipelines_app/features/runs/ui/run_more_menu.dart';
|
||||
|
||||
import 'run_retry_wiring_support.dart';
|
||||
|
||||
Future<void> _mount(
|
||||
WidgetTester tester,
|
||||
ApiGateway gateway, {
|
||||
Future<void> Function(BuildContext, JsonMap)? onOpenInChat,
|
||||
bool settle = true,
|
||||
}) async {
|
||||
tester.view.physicalSize = const Size(1200, 900);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: RunsScreen(
|
||||
gateway: gateway,
|
||||
initialRunId: 7,
|
||||
onOpenInChat: onOpenInChat,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (settle) await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
/// A gateway that lists run 7 but never answers its detail.
|
||||
class _SlowDetailGateway implements ApiGateway {
|
||||
final pending = Completer<JsonMap>();
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => const Stream.empty();
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) =>
|
||||
switch (type) {
|
||||
'list_runs' => Future.value({
|
||||
'runs': [
|
||||
{'id': 7, 'title': 'Slow run', 'status': 'failed', 'name': 'p'},
|
||||
],
|
||||
}),
|
||||
'get_run' => pending.future,
|
||||
_ => Future.error(UnsupportedError(type)),
|
||||
};
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('the failure banner offers Retry, Run again… and Open in chat', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = RetryWiringGateway();
|
||||
addTearDown(gateway.framesController.close);
|
||||
gateway.details[7] = {
|
||||
...retryFailedDetail(),
|
||||
'pipeline_id': 3,
|
||||
'version': 2,
|
||||
'failure_reason': 'The build stage exited with status 2.',
|
||||
};
|
||||
final opened = <JsonMap>[];
|
||||
await _mount(
|
||||
tester,
|
||||
gateway,
|
||||
onOpenInChat: (context, run) async => opened.add(run),
|
||||
);
|
||||
|
||||
expect(find.text('The build stage exited with status 2.'), findsOneWidget);
|
||||
expect(find.byKey(runFailureRetryKey), findsOneWidget);
|
||||
expect(find.byKey(runFailureRunAgainKey), findsOneWidget);
|
||||
expect(find.byKey(runFailureOpenInChatKey), findsOneWidget);
|
||||
|
||||
// Retry is the menu's retry prompt; nothing is sent until its confirm.
|
||||
await tester.tap(find.byKey(runFailureRetryKey));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text(retryDialogTitle(7)), findsOneWidget);
|
||||
await tester.tap(find.byKey(retryKeepKey));
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.retryCalls, isEmpty);
|
||||
|
||||
// Open in chat hands the run to the host's send-to-chat flow.
|
||||
await tester.tap(find.byKey(runFailureOpenInChatKey));
|
||||
await tester.pumpAndSettle();
|
||||
expect(opened.single['id'], 7);
|
||||
|
||||
// Run again reads the run's pipeline for the pre-filled New run form.
|
||||
await tester.tap(find.byKey(runFailureRunAgainKey));
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.calls.map((call) => call.type), contains('get_pipeline'));
|
||||
});
|
||||
|
||||
testWidgets('a failed run without a pipeline offers no Run again', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = RetryWiringGateway();
|
||||
addTearDown(gateway.framesController.close);
|
||||
gateway.details[7] = {...retryFailedDetail(), 'failure_reason': 'Boom.'};
|
||||
await _mount(tester, gateway);
|
||||
|
||||
expect(find.byKey(runFailureRetryKey), findsOneWidget);
|
||||
expect(find.byKey(runFailureRunAgainKey), findsNothing);
|
||||
expect(find.byKey(runFailureOpenInChatKey), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('the more menu shows while the detail loads, items disabled', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _SlowDetailGateway();
|
||||
await _mount(tester, gateway, settle: false);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 50));
|
||||
|
||||
expect(find.text('Loading run details…'), findsOneWidget);
|
||||
expect(find.byKey(runMoreMenuKey), findsOneWidget);
|
||||
await tester.tap(find.byKey(runMoreMenuKey));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 400));
|
||||
final rename = tester.widget<PopupMenuItem<Object?>>(
|
||||
find.ancestor(
|
||||
of: find.text(runTitleActionLabel),
|
||||
matching: find.byWidgetPredicate((w) => w is PopupMenuItem),
|
||||
),
|
||||
);
|
||||
expect(rename.enabled, isFalse);
|
||||
|
||||
gateway.pending.complete({
|
||||
'run_detail': {
|
||||
'id': 7,
|
||||
'title': 'Slow run',
|
||||
'status': 'failed',
|
||||
'name': 'p',
|
||||
'steps': const <JsonMap>[],
|
||||
},
|
||||
});
|
||||
await tester.tapAt(const Offset(2, 2));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(runMoreMenuKey));
|
||||
await tester.pumpAndSettle();
|
||||
final loaded = tester.widget<PopupMenuItem<Object?>>(
|
||||
find.ancestor(
|
||||
of: find.text(runTitleActionLabel),
|
||||
matching: find.byWidgetPredicate((w) => w is PopupMenuItem),
|
||||
),
|
||||
);
|
||||
expect(loaded.enabled, isTrue);
|
||||
});
|
||||
}
|
||||
@@ -187,4 +187,30 @@ void main() {
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
}
|
||||
|
||||
testWidgets('under a day heading a row shows only its time of day', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: RunListRow(
|
||||
run: _finished,
|
||||
now: DateTime.utc(2026, 10, 22),
|
||||
timeOfDay: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
final created = DateTime.parse('${_finished['created_at']}');
|
||||
expect(find.byType(RelativeTimeLabel), findsNothing);
|
||||
final time = tester.widget<Text>(
|
||||
find.byKey(const ValueKey('run-row-time-42')),
|
||||
);
|
||||
expect(time.data, runTimeOfDay(created));
|
||||
expect(time.data, matches(RegExp(r'^\d\d:\d\d$')));
|
||||
// The day the heading already names is not repeated on the row.
|
||||
final local = created.toLocal();
|
||||
expect(find.textContaining('${local.day} Oct'), findsNothing);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/settings/settings_controls.dart';
|
||||
|
||||
Widget _actions({required bool connected}) => MaterialApp(
|
||||
home: Scaffold(
|
||||
body: SettingsActions(
|
||||
primaryLabel: connected ? 'Disconnect' : 'Connect',
|
||||
secondaryLabel: 'Reconnect',
|
||||
primaryKey: const Key('primary'),
|
||||
secondaryKey: const Key('secondary'),
|
||||
primaryOutlined: connected,
|
||||
onPrimary: () {},
|
||||
onSecondary: () {},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
void main() {
|
||||
testWidgets('connected: Reconnect is tonal and leads, Disconnect outlined', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(_actions(connected: true));
|
||||
final disconnect = find.byKey(const Key('primary'));
|
||||
final reconnect = find.byKey(const Key('secondary'));
|
||||
expect(tester.widget(disconnect), isA<OutlinedButton>());
|
||||
expect(tester.widget(reconnect), isA<FilledButton>());
|
||||
// Never the filled primary emphasis on the action that drops the link.
|
||||
expect(find.byType(OutlinedButton), findsOneWidget);
|
||||
expect(
|
||||
tester.getTopLeft(reconnect).dx,
|
||||
lessThan(tester.getTopLeft(disconnect).dx),
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('disconnected: Connect is filled, Reconnect outlined', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(_actions(connected: false));
|
||||
final connect = find.byKey(const Key('primary'));
|
||||
final reconnect = find.byKey(const Key('secondary'));
|
||||
expect(tester.widget(connect), isA<FilledButton>());
|
||||
expect(tester.widget(reconnect), isA<OutlinedButton>());
|
||||
expect(
|
||||
tester.getTopLeft(connect).dx,
|
||||
lessThan(tester.getTopLeft(reconnect).dx),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/shell/adaptive_shell.dart';
|
||||
import 'package:pipelines_app/shell/destination.dart';
|
||||
import 'package:pipelines_app/shell/shell_chat_actions_shortcut.dart';
|
||||
import 'package:pipelines_app/ui/input/keyboard_owner.dart';
|
||||
|
||||
KeyDownEvent _down(PhysicalKeyboardKey physical, LogicalKeyboardKey logical) =>
|
||||
KeyDownEvent(
|
||||
physicalKey: physical,
|
||||
logicalKey: logical,
|
||||
timeStamp: Duration.zero,
|
||||
);
|
||||
|
||||
final _n = _down(PhysicalKeyboardKey.keyN, LogicalKeyboardKey.keyN);
|
||||
final _j = _down(PhysicalKeyboardKey.keyJ, LogicalKeyboardKey.keyJ);
|
||||
|
||||
Future<void> _alt(WidgetTester tester, LogicalKeyboardKey key) async {
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
|
||||
await tester.sendKeyEvent(key);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('Alt+N is New chat and Alt+J the next chat needing you, alone', () {
|
||||
ShellChatAction? chord(Set<LogicalKeyboardKey> held, KeyEvent event) =>
|
||||
shellChatActionShortcut(event, _FakeKeyboard(held));
|
||||
const alt = LogicalKeyboardKey.altLeft;
|
||||
expect(chord({alt}, _n), ShellChatAction.newChat);
|
||||
expect(chord({alt}, _j), ShellChatAction.nextAttention);
|
||||
expect(chord({}, _n), isNull);
|
||||
expect(chord({alt, LogicalKeyboardKey.shiftLeft}, _n), isNull);
|
||||
expect(chord({alt, LogicalKeyboardKey.controlLeft}, _j), isNull);
|
||||
expect(chord({alt, LogicalKeyboardKey.metaLeft}, _j), isNull);
|
||||
expect(chord({LogicalKeyboardKey.controlLeft}, _n), isNull);
|
||||
// Option+N is a dead key (˜) on a Mac: matched by position.
|
||||
final dead = _down(
|
||||
PhysicalKeyboardKey.keyN,
|
||||
const LogicalKeyboardKey(0x02dc),
|
||||
);
|
||||
expect(chord({alt}, dead), ShellChatAction.newChat);
|
||||
expect(
|
||||
shellChatActionLabel(ShellChatAction.newChat, TargetPlatform.macOS),
|
||||
'Option+N',
|
||||
);
|
||||
expect(
|
||||
shellChatActionLabel(ShellChatAction.nextAttention, TargetPlatform.linux),
|
||||
'Alt+J',
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('the chords show Chat and report the action; the terminal '
|
||||
'keeps them', (tester) async {
|
||||
final terminal = FocusNode();
|
||||
addTearDown(terminal.dispose);
|
||||
final actions = <ShellChatAction>[];
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: AdaptiveShell(
|
||||
onChatAction: actions.add,
|
||||
destinationBodies: {
|
||||
AppDestination.pipelines: (_) => TypingSurface(
|
||||
child: Focus(focusNode: terminal, child: const Text('terminal')),
|
||||
),
|
||||
AppDestination.chat: (_) => const Text('chat body'),
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
terminal.requestFocus();
|
||||
await tester.pump();
|
||||
await _alt(tester, LogicalKeyboardKey.keyN);
|
||||
expect(actions, isEmpty);
|
||||
expect(find.text('chat body'), findsNothing);
|
||||
|
||||
terminal.unfocus();
|
||||
await tester.pump();
|
||||
await _alt(tester, LogicalKeyboardKey.keyJ);
|
||||
expect(actions, [ShellChatAction.nextAttention]);
|
||||
expect(find.text('chat body'), isOnstage);
|
||||
await _alt(tester, LogicalKeyboardKey.keyN);
|
||||
expect(actions, [ShellChatAction.nextAttention, ShellChatAction.newChat]);
|
||||
});
|
||||
|
||||
testWidgets('a dialog keeps the chords', (tester) async {
|
||||
final actions = <ShellChatAction>[];
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: AdaptiveShell(
|
||||
onChatAction: actions.add,
|
||||
destinationBodies: {
|
||||
AppDestination.pipelines: (context) => TextButton(
|
||||
onPressed: () => showDialog<void>(
|
||||
context: context,
|
||||
builder: (_) =>
|
||||
const AlertDialog(content: TextField(autofocus: true)),
|
||||
),
|
||||
child: const Text('dialog'),
|
||||
),
|
||||
AppDestination.chat: (_) => const Text('chat body'),
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.tap(find.text('dialog'));
|
||||
await tester.pumpAndSettle();
|
||||
await _alt(tester, LogicalKeyboardKey.keyN);
|
||||
expect(actions, isEmpty);
|
||||
});
|
||||
}
|
||||
|
||||
class _FakeKeyboard extends HardwareKeyboard {
|
||||
_FakeKeyboard(this.pressed);
|
||||
final Set<LogicalKeyboardKey> pressed;
|
||||
@override
|
||||
bool isLogicalKeyPressed(LogicalKeyboardKey key) => pressed.contains(key);
|
||||
}
|
||||
@@ -147,11 +147,21 @@ void main() {
|
||||
AppListRow.selectedColor(context),
|
||||
);
|
||||
final accent = Theme.of(context).colorScheme.primary;
|
||||
// The one selection style every list shares: the tonal fill plus one
|
||||
// leading bar in the accent.
|
||||
final bar = tester.widget<DecoratedBox>(
|
||||
find.descendant(of: row, matching: find.byKey(appListRowSelectionKey)),
|
||||
);
|
||||
final side =
|
||||
((bar.decoration as BoxDecoration).border as BorderDirectional).start;
|
||||
expect(side.color, accent);
|
||||
expect(side.width, kAppListRowBarWidth);
|
||||
expect(_paint(tester, 'Fixture run').fontWeight, FontWeight.w700);
|
||||
expect(_paint(tester, '9d ago').color, accent);
|
||||
|
||||
await tester.pumpWidget(_host(_row()));
|
||||
expect(tester.widget<Material>(surface).color, const Color(0x00000000));
|
||||
expect(find.byKey(appListRowSelectionKey), findsNothing);
|
||||
expect(_paint(tester, '9d ago').color, isNot(accent));
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"size": "1440x1000",
|
||||
"params": "chats=8&colors=1&activity=1&closed=2",
|
||||
"steps": [
|
||||
{ "open": "/chat/perf-chat-1" },
|
||||
{ "wait": 1500 },
|
||||
{ "press": "Alt+k", "wait": 800 },
|
||||
{ "type": "billing", "wait": 500 },
|
||||
{ "press": "Enter", "wait": 1200 },
|
||||
{ "press": "Alt+k", "wait": 800 },
|
||||
{ "shot": "recent-first-previous-selected" },
|
||||
{ "press": "Enter", "wait": 1200 },
|
||||
{ "shot": "back-to-previous" },
|
||||
{ "press": "Alt+k", "wait": 800 },
|
||||
{ "type": "s", "wait": 500 },
|
||||
{ "shot": "closed-section" },
|
||||
{ "type": "earch", "wait": 400 },
|
||||
{ "press": "Enter", "wait": 1500 },
|
||||
{ "shot": "closed-reopened" },
|
||||
{ "press": "Alt+j", "wait": 1500 },
|
||||
{ "shot": "alt-j-needs-you" },
|
||||
{ "press": "Alt+n", "wait": 1200 },
|
||||
{ "shot": "alt-n-new-chat" }
|
||||
]
|
||||
}
|
||||
@@ -310,3 +310,42 @@ void chatScrollStream(String sessionId, void Function(JsonMap frame) emit) {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// A scoped find-in-chat search (`scope: chat:<id>`) the way
|
||||
/// `internal/server/search_chat_scoped.go` answers it: every occurrence in
|
||||
/// the text parts of the history before [cursor] ("0|older" for the page
|
||||
/// `?older=1` holds back), newest message first.
|
||||
List<JsonMap> chatScrollScopedHits(
|
||||
String sessionId,
|
||||
String cursor,
|
||||
String query,
|
||||
bool caseSensitive,
|
||||
) {
|
||||
if (!_older || !cursor.endsWith('|older') || query.trim().isEmpty) {
|
||||
return const [];
|
||||
}
|
||||
final pattern = RegExp(RegExp.escape(query), caseSensitive: caseSensitive);
|
||||
final hits = <JsonMap>[];
|
||||
for (var i = -1; i >= -20; i--) {
|
||||
final message = _message(sessionId, i);
|
||||
final parts = message['parts'] as List;
|
||||
for (var part = 0; part < parts.length; part++) {
|
||||
final body = parts[part] as Map;
|
||||
if (body['type'] != 'text') continue;
|
||||
for (final match in pattern.allMatches('${body['text']}')) {
|
||||
hits.add({
|
||||
'kind': 'chat',
|
||||
'target': 'chat:$sessionId',
|
||||
'chat': {
|
||||
'session_id': sessionId,
|
||||
'message_id': message['id'],
|
||||
'part': part,
|
||||
'offset': match.start,
|
||||
'length': match.end - match.start,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
// them, and keeps colours picked with chat_color;
|
||||
// `?activity=1` (with `?chats=N`) lists a running chat, one with
|
||||
// background tasks and idle ones;
|
||||
// `?closed=N` (with `?chats=N`) closes the last N chats (chat_reopen
|
||||
// reopens one);
|
||||
// `?automations=N` reports N native automations for the selected chat;
|
||||
// `?msgs=`, `?rich=1`, `?older=1`, `?live=N` vary the chat transcripts for
|
||||
// scroll captures (tool/perf/chat_scroll_fixture.dart).
|
||||
@@ -91,8 +93,22 @@ const _colorNames = ['teal', 'purple', null, 'amber', 'red', null, 'blue'];
|
||||
final Map<String, String?> _pickedColors = {};
|
||||
final _chatCatalog = ChatCatalogFixture();
|
||||
|
||||
/// `?closed=N` (with `?chats=N`): the last N chats are closed until
|
||||
/// chat_reopen reopens one.
|
||||
int get _closedCount => int.tryParse(_params['closed'] ?? '') ?? 0;
|
||||
final Set<String> _reopened = {};
|
||||
|
||||
JsonMap _chatRow(int i) {
|
||||
final id = perfChatId(i);
|
||||
final closed = i >= _chats - _closedCount && !_reopened.contains(id);
|
||||
return {
|
||||
..._openChatRow(i, id),
|
||||
if (closed)
|
||||
'closed_at': DateTime.now().millisecondsSinceEpoch - (i + 1) * 60000,
|
||||
};
|
||||
}
|
||||
|
||||
JsonMap _openChatRow(int i, String id) {
|
||||
if (!_colors) {
|
||||
return {
|
||||
'id': id,
|
||||
@@ -305,6 +321,10 @@ JsonMap? perfChatReply(JsonMap request) {
|
||||
'type': 'chat_sessions',
|
||||
'chat_sessions': [for (var i = 0; i < _chats; i++) _chatRow(i)],
|
||||
};
|
||||
case 'chat_reopen':
|
||||
final query = request['chat_query'];
|
||||
_reopened.add(query is Map ? '${query['session_id'] ?? ''}' : '');
|
||||
return {'id': id, 'type': 'chat_reopen'};
|
||||
case 'chat_color':
|
||||
final query = request['chat_query'];
|
||||
final session = query is Map ? '${query['session_id'] ?? ''}' : '';
|
||||
|
||||
@@ -709,6 +709,25 @@ JsonMap? probeReply(JsonMap request) {
|
||||
// The app must send exactly the browser's SearchRequest body; anything
|
||||
// else is answered with a visible refusal so the capture cannot pass.
|
||||
final search = request['search'];
|
||||
if (search is Map && search['scope'] is String) {
|
||||
// Find in chat: every occurrence in history not loaded yet.
|
||||
final session = '${search['scope']}'.replaceFirst('chat:', '');
|
||||
return {
|
||||
'id': id,
|
||||
'type': 'search_results',
|
||||
'search_results': {
|
||||
'query': search['query'],
|
||||
'kind': 'chat',
|
||||
'results': chatScrollScopedHits(
|
||||
session,
|
||||
'${search['cursor'] ?? ''}',
|
||||
'${search['query'] ?? ''}',
|
||||
search['case_sensitive'] == true,
|
||||
),
|
||||
'cap': 200,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (search is! Map ||
|
||||
search.length != 3 ||
|
||||
search['query'] is! String ||
|
||||
|
||||
+10
@@ -480,6 +480,16 @@ history refresh without inventing text deltas or ending a queued prompt. Native
|
||||
step markers may include `step.turn_id`; a terminal marker for an older turn
|
||||
must not clear a newer turn's Stop control or release its queue slot.
|
||||
|
||||
A client that falls too far behind its chat stream (64 queued frames) is
|
||||
detached; its last frame is `chat_event.kind="resync"`, so it must send
|
||||
`chat_subscribe` again before re-reading history. Consecutive text or reasoning
|
||||
deltas of one part are joined while queued: a joined numbered frame carries
|
||||
`seq` (its last delta), `seq_from` (its first) and `delta_lens` (each delta's
|
||||
length in UTF-16 code units), so a client whose history page's `liveSeq`
|
||||
falls inside the range drops exactly the prefix the page already holds. A run
|
||||
subscriber that falls behind likewise receives a final `{"type":"runs_resync"}`
|
||||
and must send `subscribe` again for a fresh snapshot.
|
||||
|
||||
Native context compaction is reported as `chat_event.kind="compaction"`, with
|
||||
`compaction: {status: "running" | "completed" | "failed", id?: string}`.
|
||||
Optional `native_turn_id` scopes the activity to its real harness turn; ignore
|
||||
|
||||
@@ -474,14 +474,39 @@ func (s *session) emit(frame protocol.ChatEventFrame) {
|
||||
targets = append(targets, ch)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
lifecycle := frameIsLifecycle(frame)
|
||||
for _, ch := range targets {
|
||||
select {
|
||||
case ch <- frame:
|
||||
continue
|
||||
default:
|
||||
}
|
||||
if !lifecycle {
|
||||
continue
|
||||
}
|
||||
// A full watcher may lose a delta (the hub repairs text from
|
||||
// history), but never a step start or end: a lost end leaves the
|
||||
// turn "working" forever. Wait, bounded, for the watcher to drain.
|
||||
timer := time.NewTimer(lifecycleDeliveryTimeout)
|
||||
select {
|
||||
case ch <- frame:
|
||||
case <-timer.C:
|
||||
log.Printf("claude session %s: a watcher did not accept the %s frame within %s; it was dropped", s.id, frame.Kind, lifecycleDeliveryTimeout)
|
||||
}
|
||||
timer.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
// lifecycleDeliveryTimeout bounds how long emit waits for a full watcher to
|
||||
// accept a turn lifecycle frame before it gives up on that watcher.
|
||||
var lifecycleDeliveryTimeout = 5 * time.Second
|
||||
|
||||
// frameIsLifecycle reports whether a frame changes the turn's state, so it
|
||||
// must reach every watcher even when that watcher's buffer is full.
|
||||
func frameIsLifecycle(frame protocol.ChatEventFrame) bool {
|
||||
return frame.Kind == protocol.ChatEventStep || frame.Kind == protocol.ChatEventResync
|
||||
}
|
||||
|
||||
func (s *session) subscribe() chan protocol.ChatEventFrame {
|
||||
ch := make(chan protocol.ChatEventFrame, 256)
|
||||
s.mu.Lock()
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// A watcher whose buffer is full of streamed text may lose a delta, but never
|
||||
// the turn's end: a lost end left the chat "working" forever.
|
||||
func TestEmitDeliversTheTurnEndToAFullWatcher(t *testing.T) {
|
||||
c := newChat(context.Background())
|
||||
t.Cleanup(c.cancel)
|
||||
s := c.sessionFor("ses_full", t.TempDir())
|
||||
ch := s.subscribe()
|
||||
defer s.unsubscribe(ch)
|
||||
for len(ch) < cap(ch) {
|
||||
s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventText, Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "p", Text: "x"}})
|
||||
}
|
||||
emitted := make(chan struct{})
|
||||
go func() {
|
||||
defer close(emitted)
|
||||
s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_1"}})
|
||||
}()
|
||||
// The watcher is slow, not gone: it drains only after the end was emitted.
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
deadline := time.After(3 * time.Second)
|
||||
for {
|
||||
select {
|
||||
case frame := <-ch:
|
||||
if frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded {
|
||||
<-emitted
|
||||
return
|
||||
}
|
||||
case <-deadline:
|
||||
t.Fatal("the turn end never reached the full watcher")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A watcher that never drains does not hold the CLI reader forever.
|
||||
func TestEmitGivesUpOnAStuckWatcher(t *testing.T) {
|
||||
prior := lifecycleDeliveryTimeout
|
||||
lifecycleDeliveryTimeout = 50 * time.Millisecond
|
||||
t.Cleanup(func() { lifecycleDeliveryTimeout = prior })
|
||||
c := newChat(context.Background())
|
||||
t.Cleanup(c.cancel)
|
||||
s := c.sessionFor("ses_stuck", t.TempDir())
|
||||
ch := s.subscribe()
|
||||
defer s.unsubscribe(ch)
|
||||
for len(ch) < cap(ch) {
|
||||
s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventText, Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "p", Text: "x"}})
|
||||
}
|
||||
start := time.Now()
|
||||
s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_1"}})
|
||||
if waited := time.Since(start); waited > 2*time.Second {
|
||||
t.Fatalf("emit blocked %s on a stuck watcher", waited)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ChatNotification is one chat phone push (ntfy) in the durable outbox. It
|
||||
// follows the run notification outbox (run_notifications.go): a row is leased
|
||||
// for a bounded attempt, a crash during a lease is recovered when the lease
|
||||
// expires, and attempts are bounded. ID is the chat's app notification id, so
|
||||
// an enqueue is idempotent and a notification the operator already cleared in
|
||||
// the app is never published late.
|
||||
type ChatNotification struct {
|
||||
ID, SessionID, Title, Body, Click string
|
||||
// SequenceID is the ntfy sequence id the push is published with (so a later
|
||||
// clear dismisses it on the phone); "" publishes without one.
|
||||
SequenceID string
|
||||
Priority int
|
||||
Attempts int
|
||||
}
|
||||
|
||||
// ChatNotificationAttempts bounds publication attempts per chat push.
|
||||
const ChatNotificationAttempts = 5
|
||||
|
||||
// chatNotificationLease is how long one claimed attempt owns its row.
|
||||
const chatNotificationLease = 60
|
||||
|
||||
// chatNotificationRetention bounds how long settled rows are kept.
|
||||
const chatNotificationRetention = 7 * 24 * time.Hour
|
||||
|
||||
func (s *Store) initChatNotifications() error {
|
||||
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS chat_notifications (
|
||||
id TEXT PRIMARY KEY, session_id TEXT NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL, click TEXT NOT NULL,
|
||||
sequence_id TEXT NOT NULL DEFAULT '', priority INTEGER NOT NULL DEFAULT 0,
|
||||
status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0,
|
||||
next_attempt INTEGER NOT NULL DEFAULT 0, diagnostic TEXT NOT NULL DEFAULT '', message_id TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL);
|
||||
CREATE INDEX IF NOT EXISTS chat_notifications_due ON chat_notifications(status,next_attempt);`)
|
||||
return err
|
||||
}
|
||||
|
||||
// EnqueueChatNotification records one chat push once (by id) and prunes
|
||||
// settled rows past retention.
|
||||
func (s *Store) EnqueueChatNotification(ctx context.Context, n ChatNotification, now time.Time) error {
|
||||
if _, err := s.db.ExecContext(ctx, `DELETE FROM chat_notifications WHERE created_at<? AND status NOT IN ('pending','sending')`, now.Add(-chatNotificationRetention).Unix()); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `INSERT INTO chat_notifications(id,session_id,title,body,click,sequence_id,priority,created_at)
|
||||
VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(id) DO NOTHING`, n.ID, n.SessionID, n.Title, n.Body, n.Click, n.SequenceID, n.Priority, now.Unix())
|
||||
return err
|
||||
}
|
||||
|
||||
// ClaimChatNotification atomically leases one due push. A push whose app
|
||||
// notification was cleared before it went out (the operator already answered
|
||||
// in the app) is settled as cleared instead of published.
|
||||
func (s *Store) ClaimChatNotification(ctx context.Context, now int64) (*ChatNotification, error) {
|
||||
if _, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status='cleared',diagnostic='cleared in the app before publication'
|
||||
WHERE status IN ('pending','sending') AND next_attempt<=? AND EXISTS(SELECT 1 FROM app_notifications a WHERE a.id=chat_notifications.id AND a.cleared_at<>0)`, now); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status='failed',diagnostic='publisher acknowledgement unknown after final lease expired'
|
||||
WHERE status='sending' AND attempts>=? AND next_attempt<=?`, ChatNotificationAttempts, now); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n := new(ChatNotification)
|
||||
err := s.db.QueryRowContext(ctx, `UPDATE chat_notifications SET status='sending',attempts=attempts+1,next_attempt=?
|
||||
WHERE rowid=(SELECT rowid FROM chat_notifications WHERE status IN ('pending','sending') AND attempts<? AND next_attempt<=? ORDER BY next_attempt,rowid LIMIT 1)
|
||||
RETURNING id,session_id,title,body,click,sequence_id,priority,attempts`, now+chatNotificationLease, ChatNotificationAttempts, now).Scan(&n.ID, &n.SessionID, &n.Title, &n.Body, &n.Click, &n.SequenceID, &n.Priority, &n.Attempts)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// FinishChatNotification settles a claimed attempt: sent, or pending again
|
||||
// after an exponential backoff (5 s, 10 s, 20 s, ...) until attempts run out.
|
||||
func (s *Store) FinishChatNotification(ctx context.Context, n ChatNotification, now int64, messageID string, failure error) error {
|
||||
status, diagnostic, next := "sent", "", now
|
||||
if failure != nil {
|
||||
status, diagnostic = "pending", failure.Error()
|
||||
next = now + int64(5)<<min(n.Attempts-1, 8)
|
||||
if n.Attempts >= ChatNotificationAttempts {
|
||||
status = "failed"
|
||||
}
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status=?,diagnostic=?,message_id=?,next_attempt=?
|
||||
WHERE id=? AND status='sending' AND attempts=?`, status, diagnostic, messageID, next, n.ID, n.Attempts)
|
||||
return err
|
||||
}
|
||||
|
||||
// ChatNotificationStatus reports one push's outbox status ("" when absent)
|
||||
// and attempts.
|
||||
func (s *Store) ChatNotificationStatus(ctx context.Context, id string) (string, int, error) {
|
||||
var status string
|
||||
var attempts int
|
||||
err := s.db.QueryRowContext(ctx, `SELECT status,attempts FROM chat_notifications WHERE id=?`, id).Scan(&status, &attempts)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", 0, nil
|
||||
}
|
||||
return status, attempts, err
|
||||
}
|
||||
|
||||
// ChatNotificationCleared reports whether id's app notification has been
|
||||
// cleared; a publication that raced a clear then clears the phone too.
|
||||
func (s *Store) ChatNotificationCleared(ctx context.Context, id string) (bool, error) {
|
||||
var cleared bool
|
||||
err := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM app_notifications WHERE id=? AND cleared_at<>0)`, id).Scan(&cleared)
|
||||
return cleared, err
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user