Merge branch 'worktree-agent-a717651aa412e3b7c'

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 01:00:02 +00:00
60 changed files with 4265 additions and 222 deletions
+23 -1
View File
@@ -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,
@@ -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(
+17 -3
View File
@@ -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,
),
),
),
);
}
}
@@ -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;
}
+146
View File
@@ -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;
@@ -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,
];
+9 -1
View File
@@ -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);
@@ -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,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,
@@ -265,6 +274,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
child: ChatTranscriptHorizontalScrollView(
label: 'code block',
child: Text.rich(
key: codeKey,
TextSpan(
children: _linked(
context,
@@ -280,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,
+17
View File
@@ -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,
@@ -285,22 +308,16 @@ class PipelineListPanel extends StatelessWidget {
_statusLine(badge, badge.ranAgo),
),
),
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),
),
menu: pipelineRowActions(
pipeline: pipeline,
wide: wide,
onRun: onRun == null
? null
: (context) => onRun!(context, pipeline),
onOpenInChat: onOpenInChat == null
? null
: (context) => onOpenInChat!(context, pipeline, run),
),
);
},
);
@@ -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']) &&
+1 -1
View File
@@ -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();
}
@@ -7,6 +7,7 @@ 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';
@@ -20,6 +21,7 @@ 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';
@@ -58,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;
@@ -122,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
@@ -138,6 +158,7 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
@override
void dispose() {
HardwareKeyboard.instance.removeHandler(_tabDigitKey);
_inputSection.dispose();
_outputSection.dispose();
_liveRun.dispose();
@@ -485,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,
@@ -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(
@@ -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,
],
],
),
),
@@ -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,
@@ -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',
+30 -1
View File
@@ -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';
}
@@ -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);
},
);
}
@@ -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,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');
});
});
}
@@ -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?>>(),
);
});
}
@@ -0,0 +1,72 @@
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 'run_detail_graph_support.dart';
int _current(WidgetTester tester) => tester
.widget<FloatingDestinationBar>(
find.descendant(
of: find.byKey(const Key('run-detail-tabs')),
matching: find.byType(FloatingDestinationBar),
),
)
.currentIndex;
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);
});
}
@@ -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);
});
}
@@ -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);
}
@@ -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" }
]
}
+39
View File
@@ -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;
}
+20
View File
@@ -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 ||
+26
View File
@@ -84,8 +84,22 @@ type SearchRequest struct {
// and private/ scratch, see ClassifyArtifacts). Off by default: artifact
// search surfaces only deliverables.
IncludeDebug bool `json:"include_debug,omitempty"`
// Scope narrows a kind=chat search to one chat ("chat:<session id>").
// A scoped search returns every text-part occurrence of Query in that
// chat's messages, newest message first, one result per occurrence with
// its message id, part index and offset, paged by Cursor/NextCursor.
Scope string `json:"scope,omitempty"`
// Cursor continues a scoped chat search: a previous reply's NextCursor,
// or a chat_messages next_cursor to start just before the messages a
// client already holds. Empty starts at the newest message.
Cursor string `json:"cursor,omitempty"`
// CaseSensitive makes a scoped chat search match case exactly.
CaseSensitive bool `json:"case_sensitive,omitempty"`
}
// SearchChatScope is a scoped chat search's Scope for one session.
func SearchChatScope(sessionID string) string { return "chat:" + sessionID }
// SearchResponse is the bounded set of matches. Results are ordered by recency
// descending (a chat's last use for kind chat), numeric entity/visit IDs
// descending, then target ascending, before the cap applies; Score records the
@@ -105,6 +119,11 @@ type SearchResponse struct {
// ScannedChats is how many chat transcripts a chat search read message
// text from (kind chat only); additive, so older peers ignore it.
ScannedChats int `json:"scanned_chats,omitempty"`
// NextCursor continues a scoped chat search that stopped before the
// chat's oldest message (result cap or scan budget); empty when done.
NextCursor string `json:"next_cursor,omitempty"`
// ScannedMessages is how many messages a scoped chat search read.
ScannedMessages int `json:"scanned_messages,omitempty"`
}
// SearchResult is one typed, navigable match. Kind selects which payload is
@@ -202,6 +221,13 @@ type SearchChat struct {
MessageID string `json:"message_id,omitempty"`
Role string `json:"role,omitempty"`
Snippet string `json:"snippet,omitempty"`
// Part and Offset locate one occurrence in a scoped chat search: the
// index of the text part in the message's parts and the match's start
// in that part's text, in UTF-16 code units (as a browser or Dart string
// counts). Length is the match's length in the same units.
Part int `json:"part,omitempty"`
Offset int `json:"offset,omitempty"`
Length int `json:"length,omitempty"`
}
// SearchChatTarget is a chat hit's target token.
+210
View File
@@ -0,0 +1,210 @@
package server
import (
"context"
"errors"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf16"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Scoped chat search ("find in chat"): every occurrence of a query in one
// chat's message text, newest message first, paged. A client uses it to count
// and reach matches in history it has not loaded yet.
const (
// scopedChatPageMessages is how many messages one broker read returns.
scopedChatPageMessages = 200
// scopedChatMaxMessages bounds the messages one scoped request reads;
// a longer history continues through NextCursor.
scopedChatMaxMessages = 2000
)
// scopedChatBudget bounds how long one scoped request reads history before it
// replies with what it found and a cursor. A variable so a test can shorten it.
var scopedChatBudget = 2 * time.Second
// scopedChatSession returns the session id a chat search's Scope names, or ""
// when the request is not scoped.
func scopedChatSession(req protocol.SearchRequest) string {
scope := strings.TrimSpace(req.Scope)
if scope == "" {
return ""
}
return strings.TrimPrefix(scope, "chat:")
}
// scopedCursor is where a scoped search resumes: the broker's history cursor
// for a page (empty for the newest) and how many of that page's newest
// messages were already searched. It travels as "<skip>|<history cursor>"; a
// cursor without the separator is a chat_messages next_cursor.
type scopedCursor struct {
history string
skip int
}
func parseScopedCursor(value string) scopedCursor {
skip, history, found := strings.Cut(value, "|")
if !found {
return scopedCursor{history: value}
}
n, err := strconv.Atoi(skip)
if err != nil || n < 0 {
return scopedCursor{history: history}
}
return scopedCursor{history: history, skip: n}
}
func (c scopedCursor) String() string { return strconv.Itoa(c.skip) + "|" + c.history }
// searchChatScoped answers a scoped chat search. Results hold one hit per
// occurrence; a message's occurrences are never split across replies, so a
// reply may exceed the cap by one message's worth.
func searchChatScoped(ctx context.Context, req protocol.SearchRequest, broker chatBroker) (*protocol.SearchResponse, error) {
sessionID := scopedChatSession(req)
if !validChatSessionID(sessionID) {
return nil, errors.New("a valid chat session id is required in scope chat:<id>")
}
if broker == nil {
return nil, errors.New("chat is not configured on this server")
}
response := &protocol.SearchResponse{
Query: req.Query,
Kind: protocol.SearchKindChat,
Results: []protocol.SearchResult{},
Cap: chatSearchLimit(req.Limit),
ScanBoundBytes: protocol.SearchMaxScanBytes,
}
// Find matches the query as typed, spaces included, like the client's
// own matching of the loaded transcript.
query := []rune(req.Query)
if strings.TrimSpace(req.Query) == "" {
return response, nil
}
ctx, cancel := context.WithTimeout(ctx, scopedChatBudget)
defer cancel()
cursor := parseScopedCursor(req.Cursor)
for {
page, err := broker.Messages(ctx, sessionID, scopedChatPageMessages, cursor.history)
if err != nil {
if ctx.Err() != nil && response.ScannedMessages > 0 {
// Out of time: what was found stands; the client continues.
response.Truncated = true
response.NextCursor = cursor.String()
return response, nil
}
return nil, err
}
messages := page.Messages
for index := len(messages) - 1 - cursor.skip; index >= 0; index-- {
message := messages[index]
response.Results = append(response.Results, scopedMessageHits(sessionID, message, query, req.CaseSensitive)...)
response.ScannedMessages++
cursor.skip++
done := index == 0 && (!page.HasMore || page.NextCursor == "")
if done {
return response, nil
}
if len(response.Results) >= response.Cap ||
response.ScannedMessages >= scopedChatMaxMessages || ctx.Err() != nil {
response.Truncated = true
if index == 0 {
cursor = scopedCursor{history: page.NextCursor}
}
response.NextCursor = cursor.String()
return response, nil
}
}
if !page.HasMore || page.NextCursor == "" {
return response, nil
}
cursor = scopedCursor{history: page.NextCursor}
}
}
// scopedMessageHits is one hit per occurrence of query in message's text parts.
func scopedMessageHits(sessionID string, message protocol.ChatMessage, query []rune, caseSensitive bool) []protocol.SearchResult {
var hits []protocol.SearchResult
for partIndex, part := range message.Parts {
if part.Type != protocol.ChatPartText || part.Text == "" {
continue
}
for _, match := range runeMatches([]rune(part.Text), query, caseSensitive) {
hits = append(hits, protocol.SearchResult{
Kind: protocol.SearchKindChat,
Target: protocol.SearchChatTarget(sessionID),
Score: chatScoreMessage,
MatchedField: "message",
Chat: &protocol.SearchChat{
SessionID: sessionID,
MessageID: message.ID,
Role: message.Role,
Snippet: protocol.SearchSnippet(part.Text, string(query)),
Part: partIndex,
Offset: match.offset,
Length: match.length,
},
})
}
}
return hits
}
type runeMatch struct{ offset, length int }
// runeMatches finds the non-overlapping occurrences of query in text, folding
// case unless caseSensitive, and reports each in UTF-16 code units.
func runeMatches(text, query []rune, caseSensitive bool) []runeMatch {
if len(query) == 0 || len(query) > len(text) {
return nil
}
var matches []runeMatch
units := 0 // UTF-16 units before text[i]
for i := 0; i <= len(text)-len(query); {
if runesEqual(text[i:i+len(query)], query, caseSensitive) {
length := utf16Len(text[i : i+len(query)])
matches = append(matches, runeMatch{offset: units, length: length})
units += length
i += len(query)
continue
}
units += utf16.RuneLen(text[i])
i++
}
return matches
}
func runesEqual(a, b []rune, caseSensitive bool) bool {
for i := range a {
if a[i] == b[i] {
continue
}
if caseSensitive || !foldEqual(a[i], b[i]) {
return false
}
}
return true
}
func foldEqual(a, b rune) bool {
if unicode.ToLower(a) == unicode.ToLower(b) {
return true
}
for folded := unicode.SimpleFold(a); folded != a; folded = unicode.SimpleFold(folded) {
if folded == b {
return true
}
}
return false
}
func utf16Len(runes []rune) int {
n := 0
for _, r := range runes {
n += utf16.RuneLen(r)
}
return n
}
+147
View File
@@ -0,0 +1,147 @@
package server
import (
"context"
"fmt"
"strconv"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// scopedHistoryChat serves one session's history oldest first in pages of the
// requested size; a cursor is the index one past the page's oldest message.
type scopedHistoryChat struct {
*fakeChat
messages []protocol.ChatMessage
}
func (c *scopedHistoryChat) Messages(_ context.Context, _ string, limit int, cursor string) (protocol.ChatHistoryPage, error) {
end := len(c.messages)
if cursor != "" {
n, err := strconv.Atoi(cursor)
if err != nil {
return protocol.ChatHistoryPage{}, err
}
end = n
}
start := max(end-limit, 0)
page := protocol.ChatHistoryPage{Messages: c.messages[start:end]}
if start > 0 {
page.HasMore = true
page.NextCursor = strconv.Itoa(start)
}
return page, nil
}
func pagedHistory(n int) []protocol.ChatMessage {
messages := make([]protocol.ChatMessage, n)
for i := range messages {
text := fmt.Sprintf("message %d", i)
if i%10 == 0 {
text = fmt.Sprintf("Needle %d and needle again", i)
}
messages[i] = chatText(fmt.Sprintf("m%d", i), protocol.ChatRoleAssistant, text)
}
return messages
}
func TestScopedChatSearchReturnsEveryOccurrenceNewestFirst(t *testing.T) {
broker := &scopedHistoryChat{fakeChat: scriptedChat(), messages: pagedHistory(450)}
response, err := searchChatScoped(context.Background(), protocol.SearchRequest{
Query: "needle", Kind: protocol.SearchKindChat, Scope: protocol.SearchChatScope("ses_a"), Limit: 200,
}, broker)
if err != nil {
t.Fatal(err)
}
if len(response.Results) != 90 || response.NextCursor != "" || response.Truncated {
t.Fatalf("results=%d cursor=%q truncated=%v", len(response.Results), response.NextCursor, response.Truncated)
}
first := response.Results[0].Chat
if first.MessageID != "m440" || first.Offset != 0 || first.Length != 6 {
t.Fatalf("first hit = %+v", first)
}
second := response.Results[1].Chat
if second.MessageID != "m440" || second.Offset != len("Needle 440 and ") {
t.Fatalf("second hit = %+v", second)
}
if last := response.Results[89].Chat; last.MessageID != "m0" {
t.Fatalf("last hit = %+v", last)
}
}
func TestScopedChatSearchPagesThroughCursor(t *testing.T) {
broker := &scopedHistoryChat{fakeChat: scriptedChat(), messages: pagedHistory(450)}
request := protocol.SearchRequest{Query: "needle", Kind: protocol.SearchKindChat, Scope: "chat:ses_a", Limit: 7}
var ids []string
for pages := 0; ; pages++ {
if pages > 50 {
t.Fatal("cursor never ended")
}
response, err := searchChatScoped(context.Background(), request, broker)
if err != nil {
t.Fatal(err)
}
for _, hit := range response.Results {
ids = append(ids, hit.Chat.MessageID)
}
if response.NextCursor == "" {
break
}
request.Cursor = response.NextCursor
}
if len(ids) != 90 {
t.Fatalf("hits across pages = %d", len(ids))
}
seen := map[string]int{}
for _, id := range ids {
seen[id]++
}
if len(seen) != 45 || seen["m0"] != 2 || seen["m440"] != 2 {
t.Fatalf("each needle message twice, got %v", seen)
}
}
func TestScopedChatSearchStartsAtHistoryCursorAndMatchesCase(t *testing.T) {
broker := &scopedHistoryChat{fakeChat: scriptedChat(), messages: pagedHistory(450)}
response, err := searchChatScoped(context.Background(), protocol.SearchRequest{
Query: "Needle", Kind: protocol.SearchKindChat, Scope: "chat:ses_a", Cursor: "250", CaseSensitive: true,
}, broker)
if err != nil {
t.Fatal(err)
}
if len(response.Results) != 25 || response.Results[0].Chat.MessageID != "m240" {
t.Fatalf("results=%d first=%+v", len(response.Results), response.Results[0].Chat)
}
}
func TestScopedChatSearchCountsUTF16Offsets(t *testing.T) {
matches := runeMatches([]rune("😀 Ünïcode ünïcode"), []rune("ÜNÏ"), false)
if len(matches) != 2 || matches[0].offset != 3 || matches[1].offset != 11 || matches[0].length != 3 {
t.Fatalf("matches = %+v", matches)
}
if got := runeMatches([]rune("aaaa"), []rune("aa"), true); len(got) != 2 {
t.Fatalf("overlapping matches counted: %+v", got)
}
}
func TestScopedChatSearchRejectsAnInvalidScope(t *testing.T) {
broker := &scopedHistoryChat{fakeChat: scriptedChat()}
if _, err := searchChatScoped(context.Background(), protocol.SearchRequest{Query: "x", Scope: "chat:../etc"}, broker); err == nil {
t.Fatal("invalid scope accepted")
}
}
func TestScopedChatSearchOverTheSocket(t *testing.T) {
broker := &transcriptChat{fakeChat: scriptedChat(), pages: map[string][]protocol.ChatMessage{}}
ctx, conn := chatSearchFixture(t, broker)
writeChat(t, ctx, conn, protocol.Message{Type: protocol.Search, ID: "scoped", Search: &protocol.SearchRequest{
Query: "flaky", Kind: protocol.SearchKindChat, Scope: "chat:ses_text",
}})
reply := readReply(t, ctx, conn, "scoped")
// transcriptChat refuses any page size but the global search's, so the
// scoped search's own read comes back as an error reply.
if reply.Type != protocol.Error {
t.Fatalf("reply = %+v", reply)
}
}
+7
View File
@@ -40,6 +40,13 @@ func isChatSearch(request protocol.Message) bool {
// chatSearchReply answers one kind=chat search request.
func chatSearchReply(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry) protocol.Message {
if scopedChatSession(*request.Search) != "" {
response, err := searchChatScoped(ctx, *request.Search, broker)
if err != nil {
return protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}
}
return protocol.Message{Type: protocol.SearchResults, ID: request.ID, SearchResults: response}
}
if registry == nil {
return protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat search unavailable: operator session registry is not configured on this server"}
}
+11 -3
View File
@@ -286,8 +286,11 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
// A chat search runs beside the read loop so its transcript readback
// never delays the run search sent with it; a newer one cancels the
// previous, whose reply the client would discard as stale anyway.
// A newer chat search replaces an older one of the same mode: the
// chat list's search and a find-in-chat search never cancel each other.
cancelChatSearch := func() {}
defer func() { cancelChatSearch() }()
cancelScopedChatSearch := func() {}
defer func() { cancelChatSearch(); cancelScopedChatSearch() }()
// Keystrokes and sizes take their own lane (terminal_lane.go), so
// they never wait behind a slow request read before them. The lane
// is drained before the deferred detaches above run.
@@ -313,9 +316,14 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
continue
}
if isChatSearch(request) {
cancelChatSearch()
searchCtx, cancel := context.WithCancel(connCtx)
cancelChatSearch = cancel
if scopedChatSession(*request.Search) != "" {
cancelScopedChatSearch()
cancelScopedChatSearch = cancel
} else {
cancelChatSearch()
cancelChatSearch = cancel
}
go func(request protocol.Message) {
defer cancel()
_ = write(chatSearchReply(searchCtx, request, options.Chat, registry))