feat(app): show a session's running background tasks

The conversation reads the session's recorded chat_shells snapshot and folds
pushed shell frames, so only tasks the server still reports as running appear.
The list is capped at three visible rows and scrolls beyond, and a task that
exits leaves it.

Selecting a task opens its recorded command, identity and running status plus
one bounded chat_shell_output page (cursor 0, 64 KiB). Empty, unavailable and
refused reads are reported with native Retry/Refresh controls, and a refused
snapshot is shown with its reason instead of claiming there are no tasks.
Both reads carry the session id, linking every task to its conversation.
This commit is contained in:
2026-10-22 17:14:56 +01:00
parent cf6da4acaa
commit 2cb4a0c555
6 changed files with 1370 additions and 0 deletions
@@ -0,0 +1,412 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/transport/connection_state.dart';
import 'package:pipelines_app/features/chat/conversation/chat_background_tasks.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'package:pipelines_app/features/chat/domain/chat_shells.dart';
/// A gateway that scripts the session snapshot and bounded output reads and can
/// push a shell frame for the selected conversation.
class _TasksGateway implements ApiGateway {
final calls = <({String type, JsonMap fields})>[];
final _frames = StreamController<JsonMap>.broadcast();
Future<JsonMap> Function()? shells;
Future<JsonMap> Function(JsonMap fields)? output;
@override
Stream<JsonMap> get frames => _frames.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add((type: type, fields: fields));
switch (type) {
case 'chat_shells':
return shells == null
? <String, dynamic>{'chat_shells': const []}
: shells!();
case 'chat_shell_output':
return output == null
? <String, dynamic>{'chat_shell_output': const {}}
: output!(fields);
case 'chat_subscribe':
return <String, dynamic>{};
case 'chat_messages':
return <String, dynamic>{
'chat_history': {
'messages': const [],
'next_cursor': '',
'has_more': false,
},
};
}
return <String, dynamic>{};
}
List<JsonMap> fieldsFor(String type) => [
for (final call in calls)
if (call.type == type) call.fields,
];
void emitShell(
String id,
String status, {
String command = '',
String session = 's',
}) => _frames.add({
'type': 'chat_event',
'chat_event': {
'session_id': session,
'kind': 'shell',
'shell': {'id': id, 'status': status, 'command': command},
},
});
void close() => _frames.close();
}
JsonMap _running(String id, {String command = 'go test ./...'}) => {
'id': id,
'status': 'running',
'command': command,
};
JsonMap _snapshot(List<JsonMap> shells) => {'chat_shells': shells};
Widget _host(
_TasksGateway gateway, {
bool cupertino = false,
int syncToken = 0,
}) {
final child = ChatBackgroundTasks(
gateway: gateway,
sessionId: 's',
syncToken: syncToken,
);
if (cupertino) {
return CupertinoApp(
home: CupertinoPageScaffold(child: SingleChildScrollView(child: child)),
);
}
return MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(body: SingleChildScrollView(child: child)),
);
}
Widget _thread(_TasksGateway gateway) => MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(
body: ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
Future<void> _tapTask(WidgetTester tester, String id) async {
await tester.tap(find.byKey(ValueKey<String>('chat-bg-task-$id')));
await tester.pumpAndSettle();
}
void main() {
testWidgets('shows only the session snapshot tasks that are still running', (
tester,
) async {
final gateway = _TasksGateway();
gateway.shells = () async => _snapshot([
_running('sh1'),
{'id': 'sh2', 'status': 'exited', 'command': 'pnpm build'},
{'id': '', 'status': 'running', 'command': 'no identity'},
]);
addTearDown(gateway.close);
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
expect(find.text('Background tasks'), findsOneWidget);
expect(find.text('1 running'), findsOneWidget);
expect(find.text('Running'), findsOneWidget);
expect(find.text('go test ./...'), findsOneWidget);
expect(find.text('pnpm build'), findsNothing);
expect(find.text('no identity'), findsNothing);
expect(gateway.fieldsFor('chat_shells'), [
{
'chat_query': {'session_id': 's'},
},
]);
});
testWidgets('an honest empty snapshot draws no task surface', (tester) async {
final gateway = _TasksGateway();
addTearDown(gateway.close);
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-background-tasks')), findsNothing);
expect(find.text('Background tasks'), findsNothing);
expect(gateway.fieldsFor('chat_shells'), hasLength(1));
});
testWidgets('pushed shell frames add and remove this session tasks', (
tester,
) async {
final gateway = _TasksGateway();
addTearDown(gateway.close);
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
expect(find.text('Background tasks'), findsNothing);
gateway.emitShell('sh1', 'running', command: 'tail -f server.log');
await tester.pumpAndSettle();
expect(find.text('Background tasks'), findsOneWidget);
expect(find.text('1 running'), findsOneWidget);
expect(find.text('tail -f server.log'), findsOneWidget);
gateway.emitShell('sh1', 'exited');
await tester.pumpAndSettle();
expect(find.text('Background tasks'), findsNothing);
gateway.emitShell('other', 'running', session: 'other-session');
await tester.pumpAndSettle();
expect(find.text('Background tasks'), findsNothing);
});
testWidgets('more than three running tasks scroll inside the bar', (
tester,
) async {
final gateway = _TasksGateway()
..shells = () async => _snapshot([
for (var index = 0; index < 4; index++) _running('sh$index'),
]);
addTearDown(gateway.close);
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
expect(find.text('4 running'), findsOneWidget);
expect(
find.descendant(
of: find.byType(ChatBackgroundTasks),
matching: find.byType(SingleChildScrollView),
),
findsOneWidget,
);
for (var index = 0; index < 4; index++) {
expect(
find.byKey(ValueKey<String>('chat-bg-task-sh$index')),
findsOneWidget,
);
}
});
testWidgets('selecting a task reads one bounded session-linked page', (
tester,
) async {
final gateway = _TasksGateway();
gateway.shells = () async => _snapshot([_running('sh1')]);
gateway.output = (fields) async => {
'chat_shell_output': {
'shell': _running('sh1'),
'output': 'ok example\n--- PASS: TestOne\n',
'cursor': 0,
'size': 8192,
'truncated': true,
},
};
addTearDown(gateway.close);
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
await _tapTask(tester, 'sh1');
expect(gateway.fieldsFor('chat_shell_output'), [
{
'chat_shell_output_query': {
'session_id': 's',
'shell_id': 'sh1',
'cursor': 0,
'limit': 64 * 1024,
},
},
]);
expect(find.byKey(const Key('chat-bg-task-detail')), findsOneWidget);
expect(find.text('Command'), findsOneWidget);
expect(find.text('Task identity'), findsOneWidget);
expect(find.text('sh1'), findsOneWidget);
expect(find.text('Status: running'), findsOneWidget);
expect(find.text('Output'), findsOneWidget);
expect(
tester
.widget<SelectableText>(find.byKey(const Key('chat-bg-task-output')))
.data,
'ok example\n--- PASS: TestOne\n',
);
expect(find.text('Output is bounded to 64 KiB.'), findsOneWidget);
expect(find.text('Refresh'), findsOneWidget);
// Selecting the open task again closes its detail without another read.
await _tapTask(tester, 'sh1');
expect(find.byKey(const Key('chat-bg-task-detail')), findsNothing);
expect(gateway.fieldsFor('chat_shell_output'), hasLength(1));
});
testWidgets('the output pane reports empty, unavailable and a refusal', (
tester,
) async {
final gateway = _TasksGateway()
..shells = () async => _snapshot([_running('sh1')]);
addTearDown(gateway.close);
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
gateway.output = (_) async => {
'chat_shell_output': {'shell': _running('sh1')},
};
await _tapTask(tester, 'sh1');
expect(find.text('No output yet.'), findsOneWidget);
gateway.output = (_) async => {
'chat_shell_output': {'shell': _running('sh1'), 'unavailable': true},
};
await _tapTask(tester, 'sh1');
await _tapTask(tester, 'sh1');
expect(find.text('Output unavailable for this task.'), findsOneWidget);
gateway.output = (_) async => throw ProtocolError('output refused');
await _tapTask(tester, 'sh1');
await _tapTask(tester, 'sh1');
expect(find.byKey(const Key('chat-bg-task-output-error')), findsOneWidget);
expect(find.text('output refused'), findsOneWidget);
expect(find.text('Retry'), findsOneWidget);
gateway.output = (_) async => {
'chat_shell_output': {'shell': _running('sh1'), 'output': 'fresh output'},
};
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',
);
});
testWidgets('a refused snapshot is reported and Retry rereads it', (
tester,
) async {
final gateway = _TasksGateway()
..shells = () async => throw ProtocolError('server down');
addTearDown(gateway.close);
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
expect(
find.textContaining('Background tasks unavailable. server down'),
findsOneWidget,
);
expect(find.text('0 running'), findsNothing);
gateway.shells = () async => _snapshot([_running('sh1')]);
await tester.tap(find.text('Retry'));
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-background-tasks-error')), findsNothing);
expect(find.text('Background tasks'), findsOneWidget);
expect(find.text('1 running'), findsOneWidget);
expect(gateway.fieldsFor('chat_shells'), hasLength(2));
});
testWidgets('an exit closes the selected pane and the bar', (tester) async {
final gateway = _TasksGateway();
gateway.shells = () async => _snapshot([_running('sh1')]);
gateway.output = (_) async => {
'chat_shell_output': {
'shell': _running('sh1'),
'output': 'still running',
},
};
addTearDown(gateway.close);
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
await _tapTask(tester, 'sh1');
expect(find.byKey(const Key('chat-bg-task-detail')), findsOneWidget);
gateway.emitShell('sh1', 'exited');
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-bg-task-detail')), findsNothing);
expect(find.text('Background tasks'), findsNothing);
});
testWidgets('a replaced socket drops held tasks and re-learns the snapshot', (
tester,
) async {
final gateway = _TasksGateway()
..shells = () async => _snapshot([_running('sh1')]);
addTearDown(gateway.close);
await tester.pumpWidget(_host(gateway));
await tester.pumpAndSettle();
expect(find.text('1 running'), findsOneWidget);
gateway.shells = () async => _snapshot(const []);
await tester.pumpWidget(_host(gateway, syncToken: 1));
await tester.pumpAndSettle();
expect(find.text('Background tasks'), findsNothing);
expect(gateway.fieldsFor('chat_shells'), hasLength(2));
});
testWidgets('the Cupertino host keeps native buttons and the same facts', (
tester,
) async {
final gateway = _TasksGateway();
gateway.shells = () async => _snapshot([_running('sh1')]);
gateway.output = (_) async => {
'chat_shell_output': {
'shell': _running('sh1'),
'output': 'native output',
},
};
addTearDown(gateway.close);
await tester.pumpWidget(_host(gateway, cupertino: true));
await tester.pumpAndSettle();
expect(find.byType(CupertinoButton), findsWidgets);
expect(find.text('1 running'), findsOneWidget);
await _tapTask(tester, 'sh1');
expect(find.text('Command'), findsOneWidget);
expect(find.text('Status: running'), findsOneWidget);
expect(
tester
.widget<SelectableText>(find.byKey(const Key('chat-bg-task-output')))
.data,
'native output',
);
});
testWidgets('the conversation mounts the session task surface', (
tester,
) async {
final gateway = _TasksGateway()
..shells = () async => _snapshot([_running('sh1')]);
addTearDown(gateway.close);
await tester.pumpWidget(_thread(gateway));
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-background-tasks')), findsOneWidget);
expect(find.text('Background tasks'), findsOneWidget);
expect(find.text('1 running'), findsOneWidget);
});
}
@@ -0,0 +1,160 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/domain/chat_shells.dart';
JsonMap _shell(String id, String status, {String command = ''}) => {
'id': id,
'status': status,
'command': command,
};
void main() {
group('recorded running tasks', () {
test('only a non-blank id with status running is a task', () {
final shells = [
_shell('sh1', 'running', command: 'go test ./...'),
_shell('sh2', 'exited', command: 'pnpm build'),
_shell('', 'running', command: 'no identity'),
{'status': 'running', 'command': 'no id'},
_shell('sh3', 'pending', command: 'not started'),
];
expect(runningShells(shells).map((shell) => shell['id']), ['sh1']);
});
test('a shell frame merges by id and keeps the command already known', () {
final first = mergeShellFrame(
const [],
_shell('sh1', 'running', command: 'go test ./...'),
);
final exited = mergeShellFrame(first, _shell('sh1', 'exited'));
final other = mergeShellFrame(
exited,
_shell('sh2', 'running', command: 'sleep 1'),
);
expect(other, hasLength(2));
expect(other.first['status'], 'exited');
expect(other.first['command'], 'go test ./...');
expect(runningShells(other).map((shell) => shell['id']), ['sh2']);
expect(mergeShellFrame(other, null), same(other));
expect(mergeShellFrame(other, _shell('', 'running')), same(other));
});
test('the retained observation tail is bounded', () {
var shells = const <JsonMap>[];
for (var index = 0; index < observedShellLimit + 4; index++) {
shells = mergeShellFrame(shells, _shell('sh$index', 'running'));
}
expect(shells, hasLength(observedShellLimit));
expect(shells.first['id'], 'sh4');
expect(shells.last['id'], 'sh${observedShellLimit + 3}');
});
test('a snapshot keeps observed exits and drops shells never seen', () {
final observed = [
_shell('exited', 'exited', command: 'pnpm build'),
_shell('running', 'running', command: 'go test ./...'),
_shell('gone', 'running', command: 'old fact'),
];
final loaded = shellsLoaded(observed, [
_shell('running', 'running', command: 'go test ./...'),
_shell('new', 'running', command: 'tail -f log'),
]);
expect(loaded.map((shell) => '${shell['id']}:${shell['status']}'), [
'exited:exited',
'running:running',
'new:running',
]);
expect(runningShells(loaded).map((shell) => shell['id']), [
'running',
'new',
]);
});
});
group('shell wording', () {
test('the command collapses whitespace and names a blank one', () {
expect(shellCommandSummary(' go test\n ./... '), 'go test ./...');
expect(shellCommandSummary(' '), 'background process');
expect(shellCommandSummary(null), 'background process');
});
test('a long command is elided to the tool-detail width', () {
final summary = shellCommandSummary('x' * 200);
expect(summary.length, shellCommandSummaryLength);
expect(summary.endsWith('…'), isTrue);
expect(summary, '${'x' * (shellCommandSummaryLength - 1)}…');
});
test('the heading keeps the recorded count', () {
expect(backgroundTasksTitle, 'Background tasks');
expect(backgroundTasksRunningLabel(0), '0 running');
expect(backgroundTasksRunningLabel(3), '3 running');
});
});
group('bounded output page', () {
test('a page carries its output, bound and reported shell', () {
final page = ChatShellOutputPage.fromReply({
'chat_shell_output': {
'shell': {'id': 'sh1', 'status': 'running', 'command': 'go test'},
'output': 'ok example\n',
'cursor': 0,
'size': 11,
'truncated': true,
},
});
expect(page.output, 'ok example\n');
expect(page.truncated, isTrue);
expect(page.unavailable, isFalse);
expect(page.shell?['command'], 'go test');
expect(chatShellOutputLimit, 64 * 1024);
});
test('an unknown reply parses as no page, never invented output', () {
final page = ChatShellOutputPage.fromReply(const {});
expect(page.output, '');
expect(page.shell, isNull);
expect(
const ChatShellOutputSnapshot(page: ChatShellOutputPage()).state,
ChatShellOutputState.empty,
);
});
test(
'the pane state follows loading, error, unavailable, empty, ready',
() {
expect(
const ChatShellOutputSnapshot().state,
ChatShellOutputState.none,
);
expect(
const ChatShellOutputSnapshot(loading: true).state,
ChatShellOutputState.loading,
);
expect(
const ChatShellOutputSnapshot(error: 'refused').state,
ChatShellOutputState.error,
);
expect(
const ChatShellOutputSnapshot(
page: ChatShellOutputPage(unavailable: true),
).state,
ChatShellOutputState.unavailable,
);
expect(
const ChatShellOutputSnapshot(
page: ChatShellOutputPage(output: 'ready'),
).state,
ChatShellOutputState.ready,
);
},
);
});
}