Show session automation counts in chat composer

This commit is contained in:
2026-11-08 16:40:53 +00:00
parent 3fbfb85ace
commit b7f439a94f
13 changed files with 716 additions and 89 deletions
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
@@ -54,6 +56,7 @@ class _ChatBackgroundTasksState extends State<ChatBackgroundTasks> {
void _open() {
if (_modal != null) return;
unawaited(controller.refreshAutomations());
FocusManager.instance.primaryFocus?.unfocus();
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
@@ -84,68 +87,138 @@ class _ChatBackgroundTasksState extends State<ChatBackgroundTasks> {
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: controller,
builder: (context, _) {
final count = controller.running.length;
final failed = controller.error != null;
// Nothing to show without running tasks: never a "0 tasks" caption. A
// list that cannot be read stays reachable so its refusal is reported.
if (count == 0 && !failed) return const SizedBox.shrink();
final label = failed
? 'Tasks'
: '$count ${count == 1 ? 'task' : 'tasks'}';
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final Widget button;
if (cupertino) {
final color = CupertinoColors.secondaryLabel.resolveFrom(context);
button = CupertinoButton(
key: const Key('chat-background-tasks-button'),
sizeStyle: CupertinoButtonSize.small,
padding: const EdgeInsets.symmetric(horizontal: 6),
onPressed: _open,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(CupertinoIcons.square_stack_3d_up, size: 16, color: color),
const SizedBox(width: 4),
Text(
Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) => ListenableBuilder(
listenable: controller,
builder: (context, _) {
final count = controller.running.length;
final automationCount = controller.automationStatus.count;
final failed = controller.error != null;
// Nothing to show without running tasks: never a "0 tasks" caption. A
// list that cannot be read stays reachable so its refusal is reported.
if (count == 0 &&
(automationCount == null || automationCount == 0) &&
!failed) {
return const SizedBox.shrink();
}
final labels = <String>[];
if (count > 0) labels.add('$count ${count == 1 ? 'task' : 'tasks'}');
if (automationCount != null && automationCount > 0) {
labels.add(
'$automationCount ${automationCount == 1 ? 'automation' : 'automations'}',
);
}
final label = failed && labels.isEmpty ? 'Tasks' : labels.join(', ');
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final labelStyle = cupertino
? CupertinoTheme.of(context).textTheme.tabLabelTextStyle
: Theme.of(context).textTheme.labelSmall;
final painter = TextPainter(
text: TextSpan(text: label, style: labelStyle),
textDirection: Directionality.of(context),
textScaler: MediaQuery.textScalerOf(context),
)..layout();
final compact =
constraints.maxWidth.isFinite &&
painter.width + (cupertino ? 32 : 40) > constraints.maxWidth;
painter.dispose();
Widget caption() => compact
? Wrap(
spacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (count > 0) Text('$count', style: labelStyle),
if ((automationCount ?? 0) > 0)
Row(
mainAxisSize: MainAxisSize.min,
children: [
if (count > 0) ...[
Icon(
cupertino ? CupertinoIcons.clock : Icons.schedule,
size: 16,
),
const SizedBox(width: 2),
],
Text('$automationCount', style: labelStyle),
],
),
if (labels.isEmpty) Text('Tasks', style: labelStyle),
],
)
: Text(
label,
style: CupertinoTheme.of(
context,
).textTheme.tabLabelTextStyle.copyWith(color: color),
),
],
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: labelStyle,
);
final automationOnly = count == 0 && (automationCount ?? 0) > 0;
final Widget button;
if (cupertino) {
final color = CupertinoColors.secondaryLabel.resolveFrom(context);
button = CupertinoButton(
key: const Key('chat-background-tasks-button'),
sizeStyle: CupertinoButtonSize.small,
padding: const EdgeInsets.symmetric(horizontal: 6),
onPressed: _open,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
automationOnly
? CupertinoIcons.clock
: CupertinoIcons.square_stack_3d_up,
size: 16,
color: color,
),
const SizedBox(width: 4),
Flexible(
child: DefaultTextStyle.merge(
style: TextStyle(color: color),
child: caption(),
),
),
],
),
);
} else {
final theme = Theme.of(context);
button = TextButton.icon(
key: const Key('chat-background-tasks-button'),
style: TextButton.styleFrom(
foregroundColor: theme.colorScheme.onSurfaceVariant,
padding: EdgeInsets.symmetric(horizontal: compact ? 4 : 8),
visualDensity: VisualDensity.compact,
),
onPressed: _open,
icon: Icon(
automationOnly ? Icons.schedule : Icons.layers_outlined,
size: 16,
),
label: caption(),
);
}
return Padding(
// Level with the field's single line, beside Send.
padding: const EdgeInsetsDirectional.only(end: 4, bottom: 4),
child: Semantics(
identifier: 'chat-background-tasks-button',
button: true,
excludeSemantics: true,
onTap: _open,
label: failed
? (labels.isEmpty
? 'Background tasks unavailable'
: 'Background work, $label; task list unavailable')
: 'Background work, $label',
child: Tooltip(
message: label,
excludeFromSemantics: true,
child: button,
),
),
);
} else {
final theme = Theme.of(context);
button = TextButton.icon(
key: const Key('chat-background-tasks-button'),
style: TextButton.styleFrom(
foregroundColor: theme.colorScheme.onSurfaceVariant,
padding: const EdgeInsets.symmetric(horizontal: 8),
visualDensity: VisualDensity.compact,
),
onPressed: _open,
icon: const Icon(Icons.layers_outlined, size: 16),
label: Text(label, style: theme.textTheme.labelSmall),
);
}
return Padding(
// Level with the field's single line, beside Send.
padding: const EdgeInsetsDirectional.only(end: 4, bottom: 4),
child: Semantics(
button: true,
excludeSemantics: true,
onTap: _open,
label: failed
? 'Background tasks unavailable'
: 'Background tasks, $label',
child: button,
),
);
},
},
),
);
}
@@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../../../core/error_reason.dart';
import '../data/chat_repository.dart';
import '../domain/chat_automations.dart';
import '../domain/chat_shells.dart';
/// One session's live background tasks and lazy, bounded output selection.
@@ -12,6 +13,7 @@ class ChatBackgroundTasksController extends ChangeNotifier {
ChatBackgroundTasksController(this.gateway, this.sessionId) {
_listen();
unawaited(refresh());
unawaited(refreshAutomations());
}
ApiGateway gateway;
@@ -27,10 +29,16 @@ class ChatBackgroundTasksController extends ChangeNotifier {
bool _disposed = false;
int _generation = 0;
int _outputGeneration = 0;
Timer? _automationDebounce;
Future<void>? _automationRequest;
bool _automationRefreshPending = false;
ChatAutomationStatus _automations = const ChatAutomationStatus();
int _automationGeneration = 0;
List<JsonMap> get running => runningShells(_shells);
JsonMap? get selectedShell =>
running.where((shell) => shellIdOf(shell) == selectedId).firstOrNull;
ChatAutomationStatus get automationStatus => _automations;
void replace(
ApiGateway nextGateway,
@@ -39,6 +47,8 @@ class ChatBackgroundTasksController extends ChangeNotifier {
}) {
if (_disposed) return;
unawaited(_frames?.cancel());
_automationRequest = null;
_automationRefreshPending = false;
gateway = nextGateway;
sessionId = nextSessionId;
_repository = ChatRepository(gateway);
@@ -53,12 +63,20 @@ class ChatBackgroundTasksController extends ChangeNotifier {
output = null;
error = null;
_outputGeneration++;
_automationGeneration++;
_automationRequest = null;
_automationRefreshPending = false;
_automationDebounce?.cancel();
_automationDebounce = null;
_automations = const ChatAutomationStatus();
unawaited(refresh(notify: notify));
unawaited(refreshAutomations(notify: notify));
}
void _listen() => _frames = gateway.frames.listen((envelope) {
if (_disposed || envelope['type'] != 'chat_event') return;
final frame = envelope['chat_event'];
_scheduleAutomationRefresh(frame);
if (frame is! Map ||
frame['session_id'] != sessionId ||
frame['kind'] != 'shell' ||
@@ -80,6 +98,35 @@ class ChatBackgroundTasksController extends ChangeNotifier {
notifyListeners();
}, onError: (_) {});
void _scheduleAutomationRefresh(Object frame) {
if (frame is! Map) return;
if (frame['session_id'] != sessionId) return;
final kind = '${frame['kind'] ?? ''}'.toLowerCase();
final step = frame['step'];
final part = frame['part'];
final stepEnded =
kind == 'step' &&
step is Map &&
'${step['status'] ?? ''}'.toLowerCase() == 'ended';
final toolCompleted =
kind == 'tool' &&
part is Map &&
(part['state'] is Map) &&
{
'completed',
'error',
}.contains('${(part['state'] as Map)['status'] ?? ''}'.toLowerCase());
if (!stepEnded && !toolCompleted) {
return;
}
if (_automationRequest != null) _automationRefreshPending = true;
_automationDebounce?.cancel();
_automationDebounce = Timer(const Duration(milliseconds: 250), () {
_automationDebounce = null;
unawaited(refreshAutomations());
});
}
Future<void> refresh({bool notify = true}) async {
if (_disposed) return;
final token = ++_generation;
@@ -109,6 +156,65 @@ class ChatBackgroundTasksController extends ChangeNotifier {
notifyListeners();
}
Future<void> refreshAutomations({bool notify = true}) async {
if (_disposed) return;
if (_automationRequest != null) {
_automationRefreshPending = true;
return;
}
final token = ++_automationGeneration;
final request = _readAutomations(token, notify: notify);
_automationRequest = request;
try {
await request;
} finally {
if (identical(_automationRequest, request)) {
_automationRequest = null;
if (_automationRefreshPending && !_disposed) {
_automationRefreshPending = false;
_automationDebounce?.cancel();
_automationDebounce = Timer(const Duration(milliseconds: 250), () {
_automationDebounce = null;
unawaited(refreshAutomations());
});
}
}
}
}
Future<void> _readAutomations(int token, {required bool notify}) async {
final repository = _repository;
final id = sessionId;
// A legacy gateway can throw before returning a Future. Always cross an
// async boundary before notifying listeners, including didUpdateWidget.
await Future<void>.value();
if (_disposed || token != _automationGeneration) return;
final previous = _automations;
try {
final reply = await repository.automations(id);
if (_disposed || token != _automationGeneration) return;
_automations = ChatAutomationStatus.fromReply(
reply,
expectedSessionId: id,
);
} catch (_) {
// Older servers do not know this optional command. Keep shell state
// usable and present capability absence in the inspector instead.
if (_disposed || token != _automationGeneration) return;
_automations = const ChatAutomationStatus();
}
// Unsupported/unknown is intentionally quiet in the composer; supported
// reports need to reveal their positive count.
final changed =
previous.supported != _automations.supported ||
previous.count != _automations.count ||
previous.reason != _automations.reason ||
previous.observedAt != _automations.observedAt;
if (changed || (notify && _automations.supported)) {
notifyListeners();
}
}
void _dropStaleSelection() {
if (selectedId == null || selectedShell != null) return;
selectedId = null;
@@ -167,6 +273,11 @@ class ChatBackgroundTasksController extends ChangeNotifier {
_disposed = true;
_generation++;
_outputGeneration++;
_automationGeneration++;
_automationDebounce?.cancel();
_automationDebounce = null;
_automationRequest = null;
_automationRefreshPending = false;
unawaited(_frames?.cancel());
super.dispose();
}
@@ -17,8 +17,16 @@ class ChatBackgroundTasksDialog extends StatelessWidget {
final VoidCallback onClose;
@override
Widget build(BuildContext context) {
Widget build(BuildContext context) => ListenableBuilder(
listenable: controller,
builder: (context, _) => _dialog(context),
);
Widget _dialog(BuildContext context) {
final cupertino = taskCupertino(context);
final title = (controller.automationStatus.count ?? 0) > 0
? (controller.running.isEmpty ? 'Automations' : 'Tasks and automations')
: backgroundTasksTitle;
final panel = Padding(
padding: const EdgeInsets.all(20),
child: ChatBackgroundTasksPanel(controller: controller),
@@ -36,7 +44,7 @@ class ChatBackgroundTasksDialog extends StatelessWidget {
navigationBar: CupertinoNavigationBar(
automaticallyImplyLeading: false,
leading: const Icon(CupertinoIcons.square_stack_3d_up),
middle: const Text(backgroundTasksTitle),
middle: Text(title),
trailing: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onClose,
@@ -75,7 +83,7 @@ class ChatBackgroundTasksDialog extends StatelessWidget {
const SizedBox(width: 12),
Flexible(
child: Text(
backgroundTasksTitle,
title,
style: Theme.of(context).textTheme.titleLarge,
),
),
@@ -7,6 +7,7 @@ import '../ui/sessions/chat_adaptive.dart';
import 'chat_background_task_card.dart';
import 'chat_background_task_detail.dart';
import 'chat_background_tasks_controller.dart';
import 'chat_task_presentation.dart';
/// Scrollable modal content, backed by the same live controller as its badge.
class ChatBackgroundTasksPanel extends StatefulWidget {
@@ -53,6 +54,7 @@ class _ChatBackgroundTasksPanelState extends State<ChatBackgroundTasksPanel> {
final running = controller.running;
final shell = controller.selectedShell;
final error = controller.error;
final automation = controller.automationStatus;
return Column(
key: const Key('chat-background-tasks'),
mainAxisSize: MainAxisSize.min,
@@ -62,6 +64,24 @@ class _ChatBackgroundTasksPanelState extends State<ChatBackgroundTasksPanel> {
cupertino
? const CupertinoActivityIndicator()
: const LinearProgressIndicator(),
if (automation.unavailable)
Text(
'Automation status is not available for this chat connection.',
key: const Key('chat-automations-unavailable'),
)
else ...[
Text(
automation.count == null
? 'Automation count is not available yet.'
: '${automation.count} ${automation.count == 1 ? 'automation' : 'automations'}',
key: const Key('chat-automations-count'),
),
if (automation.observedAt != null)
Text(
'Last reported: ${formatTaskDate(context, automation.observedAt!.toLocal())}',
key: const Key('chat-automations-observed-at'),
),
],
if (error != null) ...[
Text(
'Background tasks unavailable. $error',
@@ -858,28 +858,36 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
children: extras,
),
),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_attach(context, cupertino),
Expanded(
child: Focus(
canRequestFocus: false,
includeSemantics: false,
onKeyEvent: _onKey,
child: _field(cupertino),
LayoutBuilder(
builder: (context, constraints) => Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_attach(context, cupertino),
Expanded(
child: Focus(
canRequestFocus: false,
includeSemantics: false,
onKeyEvent: _onKey,
child: _field(cupertino),
),
),
),
// Shown only while tasks run (or their list
// cannot be read); a quiet control, not a
// caption.
?widget.backgroundTasks,
if (widget.running) ...[
_primary(context, cupertino, stop: true),
const SizedBox(width: 4),
// Shown only while tasks run (or their list
// cannot be read); a quiet control, not a
// caption.
if (widget.backgroundTasks != null)
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: constraints.maxWidth * .30,
),
child: widget.backgroundTasks!,
),
if (widget.running) ...[
_primary(context, cupertino, stop: true),
const SizedBox(width: 4),
],
_primary(context, cupertino),
],
_primary(context, cupertino),
],
),
),
],
),
@@ -88,6 +88,10 @@ class ChatRepository {
'chat_query': {'session_id': sessionId},
}))['chat_shells'],
);
Future<JsonMap> automations(String sessionId) => gateway.call('chat_automations', {
'chat_query': {'session_id': sessionId},
});
Future<List<String>> directories() async {
final value = (await gateway.call('chat_directories'))['chat_directories'];
if (value is! List) {
@@ -0,0 +1,51 @@
import '../../../core/api_gateway.dart';
/// The native provider's per-chat scheduled-work report. Missing fields remain
/// unknown; in particular, an absent count is never interpreted as zero.
class ChatAutomationStatus {
const ChatAutomationStatus({
this.supported = false,
this.count,
this.reason,
this.observedAt,
});
factory ChatAutomationStatus.fromReply(
JsonMap reply, {
required String expectedSessionId,
}) {
final value = reply['chat_automations'];
if (value is! Map) return const ChatAutomationStatus();
final map = value;
final reportedSession = '${map['session_id'] ?? ''}'.trim();
if (reportedSession.isEmpty || reportedSession != expectedSessionId) {
return const ChatAutomationStatus();
}
final count = map['active_count'];
final observed = map['observed_at_ms'];
final validCount = count is int && count >= 0 ? count : null;
DateTime? observedAt;
if (observed is int && observed > 0) {
try {
observedAt = DateTime.fromMillisecondsSinceEpoch(observed);
} on ArgumentError {
observedAt = null;
}
}
return ChatAutomationStatus(
supported: map['status'] == 'supported',
count: map['status'] == 'supported' ? validCount : null,
reason: '${map['reason'] ?? ''}'.trim().isEmpty
? null
: '${map['reason']}'.trim(),
observedAt: observedAt,
);
}
final bool supported;
final int? count;
final String? reason;
final DateTime? observedAt;
bool get unavailable => !supported;
}
@@ -0,0 +1,40 @@
# Composer automation manager review findings
Resolved manager review findings (covered by focused regressions):
- Refresh must use REAL protocol shapes, not guessed kind substrings. chat_event
kind is "step" with step.status="ended" (and intermediate=false for final turn)
or kind="tool" with part.state.status="completed"/"error". See existing
chat_foundation_test.dart / chat_thread_fixtures.dart. There are no kinds
containing "complete"/"finished"/"settled". Check session_id BEFORE scheduling;
events from other chats must not refresh this controller.
- Reset the automation in-flight/debounce state on server/session replacement.
Current reconnect leaves _automationRequest nonnull, so the new session skips
its initial read while the old request runs and never recovers. Drop old request
ownership (generation still rejects its result), load the new session, and
coalesce a trailing refresh if a real completion event arrives during a read.
- The domain parser must only expose count for status="supported", with a valid
nonnegative integer and matching expected session_id. Do not expose a number
supplied alongside unavailable, truncate fractional counts, or accept another
session. Guard malformed/out-of-range observed timestamps without throwing.
- Opening the existing inspector should refresh metadata. Preserve shell-list
failures separately from valid automation state and give accessible full text
for both rather than losing automation information behind a shell error label.
- Native automation-only chats need an appropriate inspector title, not a
misleading "Background tasks" title. Keep friendly UI availability copy.
- Exercise the combined caption inside the REAL composer at narrow width and
large text scale, not just a standalone chip. Keep input usable with stop/send
and attach controls, full accessible text and no overflow.
Add regressions for these behaviors, including late old-session results and an
actual step-ended frame causing a refreshed automation count. Preserve old-server
compatibility and background task details; no full suites or duplicate captures.
Manager has directly added the reconnect/request/debounce reset and an async
boundary around automation reads. Metadata changes notify after completion even
for reconnect(notify:false), otherwise a slower automation-only reply never
becomes visible after the shell list has already finished. Add a regression for
that delayed reply and preserve these compatible changes. Constructor/replace
with a synchronously throwing legacy gateway must not notify during widget build.
Final integration: 146 tests passed, analyzer clean; inspected browser captures.
+17
View File
@@ -0,0 +1,17 @@
# Chat automation count
The existing composer work control shows positive session-owned automation and
background task counts, with singular/plural labels and an automation-only state.
Unknown metadata stays unknown; the inspector explains unavailable connections
and shows the last native observation time. No extra composer row was added.
Manager recovered canceled run 293 directly after its wrong whole-suite command.
Real completion events refresh metadata; session replacement rejects stale replies
and resets request ownership. Tests cover reconnect races, protocol validation,
old-server compatibility, and a 360px composer at double text scale.
Verification: 146 focused integration tests passed (watchdog out.gjYPyi), analyzer
clean. Material dark and Cupertino light 560px captures plus 1280px automation-only
captures under /tmp/review/chat-automations-* were inspected. Captions and inspector
fit; initial Cupertino/wide shots caught message loading, subsequent inspector shots
show rendered content. No device verification or deployment in this commit.
@@ -0,0 +1,134 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_background_tasks_controller.dart';
JsonMap _report(String id, int count) => {
'chat_automations': {
'session_id': id,
'status': 'supported',
'active_count': count,
},
};
class _Gateway implements ApiGateway {
final events = StreamController<JsonMap>.broadcast();
final reads = <String>[];
late Future<JsonMap> Function(String id) automation;
@override
Stream<JsonMap> get frames => events.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
if (type == 'chat_shells') {
return Future.value({'chat_shells': <JsonMap>[]});
}
if (type == 'chat_automations') {
final id = (fields['chat_query'] as Map)['session_id'] as String;
reads.add(id);
return automation(id);
}
throw UnsupportedError(type);
}
void ended(String id) => events.add({
'type': 'chat_event',
'chat_event': {
'session_id': id,
'kind': 'step',
'step': {'status': 'ended', 'intermediate': false},
},
});
}
void main() {
testWidgets('replacement loads while old server reply is still pending', (
tester,
) async {
final oldReply = Completer<JsonMap>();
final nextReply = Completer<JsonMap>();
final old = _Gateway()..automation = (_) => oldReply.future;
final next = _Gateway()..automation = (_) => nextReply.future;
final controller = ChatBackgroundTasksController(old, 'same-id');
final notifications = <int?>[];
controller.addListener(
() => notifications.add(controller.automationStatus.count),
);
addTearDown(() async {
controller.dispose();
await old.events.close();
await next.events.close();
});
await tester.pump();
controller.replace(next, 'same-id', notify: false);
await tester.pump();
expect(next.reads, ['same-id']);
expect(controller.loading, isFalse);
notifications.clear();
// The shell list already settled. This slower response must still notify.
nextReply.complete(_report('same-id', 2));
await tester.pump();
expect(controller.automationStatus.count, 2);
expect(notifications, contains(2));
oldReply.complete(_report('same-id', 99));
await tester.pump();
expect(controller.automationStatus.count, 2);
expect(notifications, isNot(contains(99)));
});
testWidgets('a real completion during a read receives one trailing refresh', (
tester,
) async {
final first = Completer<JsonMap>();
final gateway = _Gateway();
gateway.automation = (id) =>
gateway.reads.length == 1 ? first.future : Future.value(_report(id, 1));
final controller = ChatBackgroundTasksController(gateway, 'chat');
addTearDown(() async {
controller.dispose();
await gateway.events.close();
});
await tester.pump();
gateway.ended('chat');
await tester.pump();
await tester.pump(const Duration(milliseconds: 251));
expect(gateway.reads.length, 1);
first.complete(_report('chat', 0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 251));
expect(gateway.reads.length, 2);
expect(controller.automationStatus.count, 1);
gateway.ended('another-chat');
gateway.events.add({
'type': 'chat_event',
'chat_event': {'session_id': 'chat', 'kind': 'text', 'text': 'token'},
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 251));
expect(gateway.reads.length, 2);
});
testWidgets('losing metadata notifies and clears the old positive count', (
tester,
) async {
final gateway = _Gateway()..automation = (id) async => _report(id, 3);
final controller = ChatBackgroundTasksController(gateway, 'chat');
addTearDown(() async {
controller.dispose();
await gateway.events.close();
});
await tester.pump();
expect(controller.automationStatus.count, 3);
var notifications = 0;
controller.addListener(() => notifications++);
gateway.automation = (_) => throw UnsupportedError('older server');
unawaited(controller.refreshAutomations());
await tester.pump();
expect(controller.automationStatus.count, isNull);
expect(notifications, greaterThan(0));
expect(controller.error, isNull);
});
}
@@ -15,6 +15,7 @@ class _TasksGateway implements ApiGateway {
final calls = <({String type, JsonMap fields})>[];
final _frames = StreamController<JsonMap>.broadcast();
Future<JsonMap> Function()? shells;
Future<JsonMap> Function()? automations;
Future<JsonMap> Function(JsonMap fields)? output;
@override
@@ -28,6 +29,12 @@ class _TasksGateway implements ApiGateway {
return shells == null
? <String, dynamic>{'chat_shells': const []}
: shells!();
case 'chat_automations':
return automations == null
? <String, dynamic>{
'chat_automations': {'status': 'unavailable'},
}
: automations!();
case 'chat_shell_output':
return output == null
? <String, dynamic>{'chat_shell_output': const {}}
@@ -156,6 +163,39 @@ void main() {
]);
});
testWidgets(
'shows an automation-only count and its native report in inspector',
(tester) async {
final gateway = _TasksGateway()
..automations = () async => {
'chat_automations': {
'session_id': 's',
'provider': 'claude',
'status': 'supported',
'active_count': 1,
'observed_at_ms': 1700000000000,
},
};
addTearDown(gateway.close);
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
expect(find.text('1 automation'), findsOneWidget);
await _openTasks(tester);
expect(find.text('1 automation'), findsNWidgets(2));
expect(find.textContaining('Last reported:'), findsOneWidget);
expect(gateway.fieldsFor('chat_automations'), [
{
'chat_query': {'session_id': 's'},
},
{
'chat_query': {'session_id': 's'},
},
]);
},
);
testWidgets('an empty snapshot shows no task control, never "0 tasks"', (
tester,
) async {
@@ -315,12 +355,7 @@ void main() {
await tester.tap(find.text('Retry'));
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-bg-task-output-error')), findsNothing);
expect(
tester
.widget<SelectableText>(find.byKey(const Key('chat-bg-task-output')))
.data,
'fresh output',
);
expect(find.text('Retry'), findsNothing);
});
testWidgets('a refused snapshot is reported and Retry rereads it', (
@@ -658,4 +693,70 @@ void main() {
expect(find.byKey(const Key('chat-background-tasks-button')), findsNothing);
expect(find.byKey(const Key('chat-composer-primary')), findsOneWidget);
});
testWidgets(
'combined caption leaves a usable input on a narrow running chat',
(tester) async {
tester.view.physicalSize = const Size(360, 800);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final gateway = _TasksGateway();
gateway.shells = () async =>
_snapshot([_running('sh1'), _running('sh2')]);
gateway.automations = () async => {
'chat_automations': {
'session_id': 's',
'status': 'supported',
'active_count': 12,
},
};
addTearDown(gateway.close);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(2)),
child: child!,
),
home: Scaffold(
body: ChatThreadView(
gateway: gateway,
sessionId: 's',
onBack: () {},
),
),
),
);
await tester.pumpAndSettle();
gateway._frames.add({
'type': 'chat_event',
'chat_event': {
'session_id': 's',
'kind': 'step',
'step': {
'status': 'started',
'turn_id': 'turn',
'intermediate': false,
},
},
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
expect(find.byTooltip('2 tasks, 12 automations'), findsOneWidget);
final counter = find.byKey(const Key('chat-background-tasks-button'));
expect(
find.descendant(of: counter, matching: find.text('2')),
findsOneWidget,
);
expect(
find.descendant(of: counter, matching: find.text('12')),
findsOneWidget,
);
expect(tester.getSize(find.byType(EditableText)).width, greaterThan(64));
expect(tester.takeException(), isNull);
},
);
}
@@ -0,0 +1,42 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/domain/chat_automations.dart';
void main() {
test(
'only supported integer counts from the selected chat are displayed',
() {
ChatAutomationStatus read(Map<String, dynamic> fields) =>
ChatAutomationStatus.fromReply({
'chat_automations': {'session_id': 'chat', ...fields},
}, expectedSessionId: 'chat');
expect(read({'status': 'supported', 'active_count': 0}).count, 0);
expect(read({'status': 'supported', 'active_count': 2}).count, 2);
for (final fields in <Map<String, dynamic>>[
{'status': 'unavailable', 'active_count': 2},
{'status': 'unknown', 'active_count': 2},
{'status': 'supported', 'active_count': 1.5},
{'status': 'supported', 'active_count': -1},
{'status': 'supported'},
{'session_id': 'foreign', 'status': 'supported', 'active_count': 2},
]) {
expect(read(fields).count, isNull, reason: '$fields');
}
},
);
test('invalid report times remain unknown without losing a valid count', () {
for (final stamp in [null, 'yesterday', -1, 1.5, 9223372036854775807]) {
final result = ChatAutomationStatus.fromReply({
'chat_automations': {
'session_id': 'chat',
'status': 'supported',
'active_count': 1,
'observed_at_ms': stamp,
},
}, expectedSessionId: 'chat');
expect(result.count, 1);
expect(result.observedAt, isNull);
}
});
}
+18
View File
@@ -12,6 +12,7 @@
// them, and keeps colours picked with chat_color;
// `?activity=1` (with `?chats=N`) lists a running chat, one with
// background tasks and idle ones;
// `?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).
// `?question=` pushes an agent question (tool/perf/chat_question_fixture.dart).
@@ -282,6 +283,23 @@ JsonMap? perfChatReply(JsonMap request) {
? backgroundTaskFixture()
: const [],
};
case 'chat_automations':
final query = request['chat_query'];
final session = query is Map ? '${query['session_id'] ?? ''}' : '';
final count = int.tryParse(_params['automations'] ?? '');
return {
'id': id,
'type': 'chat_automations',
'chat_automations': count == null
? {'session_id': session, 'status': 'unavailable'}
: {
'session_id': session,
'provider': _harness,
'status': 'supported',
'active_count': count,
'observed_at_ms': DateTime.now().millisecondsSinceEpoch,
},
};
case 'chat_shell_output':
final outputQuery = request['chat_shell_output_query'];
final outputId = outputQuery is Map ? outputQuery['shell_id'] : null;