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:
@@ -0,0 +1,201 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/chat_shells.dart';
|
||||
import '../ui/sessions/chat_adaptive.dart';
|
||||
|
||||
/// The selected background task's read-only detail and bounded output page.
|
||||
///
|
||||
/// Every value is a recorded fact: the server's command, the shell identity, the
|
||||
/// running status, and one lazy `chat_shell_output` page. The output area keeps
|
||||
/// the five states apart, so an unavailable or empty page and a refused read are
|
||||
/// never shown as output. Output is selectable and reads in a monospace body.
|
||||
class ChatBackgroundTaskDetail extends StatelessWidget {
|
||||
const ChatBackgroundTaskDetail({
|
||||
super.key,
|
||||
required this.shell,
|
||||
required this.output,
|
||||
required this.onRefresh,
|
||||
});
|
||||
|
||||
final JsonMap shell;
|
||||
final ChatShellOutputSnapshot? output;
|
||||
final VoidCallback onRefresh;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final content = DefaultTextStyle.merge(
|
||||
style: cupertino
|
||||
? CupertinoTheme.of(context).textTheme.textStyle
|
||||
: DefaultTextStyle.of(context).style,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
spacing: 4,
|
||||
children: [
|
||||
_label(context, cupertino, shellOutputCommandLabel),
|
||||
Text(
|
||||
blankShellValue(shell['command'])
|
||||
? shellOutputUnavailableLabel
|
||||
: '${shell['command']}',
|
||||
),
|
||||
_label(context, cupertino, shellOutputTaskIdentityLabel),
|
||||
Text(
|
||||
shellIdOf(shell),
|
||||
style: const TextStyle(fontFamily: 'monospace'),
|
||||
),
|
||||
Text(shellStatusRunningLabel),
|
||||
_outputArea(context, cupertino),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (cupertino) {
|
||||
return CupertinoListSection.insetGrouped(
|
||||
children: [Padding(padding: const EdgeInsets.all(12), child: content)],
|
||||
);
|
||||
}
|
||||
return Card(
|
||||
margin: EdgeInsets.zero,
|
||||
child: Padding(padding: const EdgeInsets.all(12), child: content),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _label(BuildContext context, bool cupertino, String text) {
|
||||
final style = cupertino
|
||||
? CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith(
|
||||
color: CupertinoColors.secondaryLabel.resolveFrom(context),
|
||||
)
|
||||
: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
);
|
||||
return Text(text, style: style);
|
||||
}
|
||||
|
||||
/// Selectable output in the host's own control. A Cupertino-only app has no
|
||||
/// `MaterialLocalizations`, which `SelectableText` asserts on, so one English
|
||||
/// default scope is supplied for its context menu (the chat markdown view's
|
||||
/// own pattern).
|
||||
Widget _selectableOutput(
|
||||
BuildContext context,
|
||||
bool cupertino,
|
||||
String output,
|
||||
) {
|
||||
final text = SelectableText(
|
||||
output,
|
||||
key: const Key('chat-bg-task-output'),
|
||||
style:
|
||||
(cupertino
|
||||
? CupertinoTheme.of(context).textTheme.textStyle
|
||||
: Theme.of(context).textTheme.bodySmall)
|
||||
?.copyWith(
|
||||
fontFamily: 'monospace',
|
||||
// Cupertino's style is not inheriting; a selectable body needs a
|
||||
// baseline from its own style.
|
||||
textBaseline: TextBaseline.alphabetic,
|
||||
),
|
||||
);
|
||||
if (!cupertino) return text;
|
||||
return Localizations(
|
||||
locale: Localizations.maybeLocaleOf(context) ?? const Locale('en'),
|
||||
delegates: const [
|
||||
DefaultWidgetsLocalizations.delegate,
|
||||
DefaultMaterialLocalizations.delegate,
|
||||
DefaultCupertinoLocalizations.delegate,
|
||||
],
|
||||
child: text,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _outputArea(BuildContext context, bool cupertino) {
|
||||
final state = output?.state ?? ChatShellOutputState.none;
|
||||
final muted = cupertino
|
||||
? CupertinoColors.secondaryLabel.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.onSurfaceVariant;
|
||||
final noteStyle =
|
||||
(cupertino
|
||||
? CupertinoTheme.of(context).textTheme.textStyle
|
||||
: Theme.of(context).textTheme.bodySmall)
|
||||
?.copyWith(color: muted);
|
||||
switch (state) {
|
||||
case ChatShellOutputState.none:
|
||||
return const SizedBox.shrink();
|
||||
case ChatShellOutputState.loading:
|
||||
return Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: cupertino
|
||||
? const CupertinoActivityIndicator()
|
||||
: const CircularProgressIndicator(),
|
||||
);
|
||||
case ChatShellOutputState.error:
|
||||
return Row(
|
||||
key: const Key('chat-bg-task-output-error'),
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
spacing: 8,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'${output?.error ?? ''}',
|
||||
style: noteStyle?.copyWith(
|
||||
color: cupertino
|
||||
? CupertinoColors.systemRed.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
),
|
||||
),
|
||||
ChatBackgroundTaskButton(
|
||||
label: shellOutputRetryLabel,
|
||||
onPressed: onRefresh,
|
||||
),
|
||||
],
|
||||
);
|
||||
case ChatShellOutputState.unavailable:
|
||||
return Text(shellOutputUnavailableNote, style: noteStyle);
|
||||
case ChatShellOutputState.empty:
|
||||
return Text(shellOutputEmptyNote, style: noteStyle);
|
||||
case ChatShellOutputState.ready:
|
||||
final page = output!.page!;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
spacing: 4,
|
||||
children: [
|
||||
_label(context, cupertino, shellOutputLabel),
|
||||
_selectableOutput(context, cupertino, page.output),
|
||||
if (page.truncated) Text(shellOutputBoundedNote, style: noteStyle),
|
||||
Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: ChatBackgroundTaskButton(
|
||||
label: shellOutputRefreshLabel,
|
||||
onPressed: onRefresh,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The host's own text button for a task action (Retry/Refresh).
|
||||
class ChatBackgroundTaskButton extends StatelessWidget {
|
||||
const ChatBackgroundTaskButton({
|
||||
super.key,
|
||||
required this.label,
|
||||
required this.onPressed,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final VoidCallback onPressed;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
|
||||
return CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: onPressed,
|
||||
child: Text(label),
|
||||
);
|
||||
}
|
||||
return TextButton(onPressed: onPressed, child: Text(label));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../core/error_reason.dart';
|
||||
import '../data/chat_repository.dart';
|
||||
import '../domain/chat_shells.dart';
|
||||
import '../ui/sessions/chat_adaptive.dart';
|
||||
import 'chat_background_task_detail.dart';
|
||||
|
||||
/// The running background tasks a chat session owns (C11).
|
||||
///
|
||||
/// The list is read from recorded facts only: the session's `chat_shells`
|
||||
/// snapshot on open and every pushed `shell` frame for that session. Every task
|
||||
/// is linked to its conversation because both reads carry this session's id.
|
||||
/// A task that exits leaves the list, so the bar disappears with the last exit
|
||||
/// instead of keeping a history of finished processes.
|
||||
///
|
||||
/// Selecting a task reveals its read-only detail and reads one bounded output
|
||||
/// page (`chat_shell_output`, cursor 0, the server's 64 KiB limit). The pane
|
||||
/// reports an unavailable or empty page and a refused read truthfully; it never
|
||||
/// invents output. A refused list read is reported with the server's reason and
|
||||
/// a native Retry rather than pretending there are no tasks.
|
||||
class ChatBackgroundTasks extends StatefulWidget {
|
||||
const ChatBackgroundTasks({
|
||||
super.key,
|
||||
required this.gateway,
|
||||
required this.sessionId,
|
||||
this.syncToken = 0,
|
||||
});
|
||||
|
||||
final ApiGateway gateway;
|
||||
final String sessionId;
|
||||
|
||||
/// Advances when the shared socket is replaced: a gap may have swallowed an
|
||||
/// exit, so the retained tasks are dropped and re-learned from the snapshot.
|
||||
final int syncToken;
|
||||
|
||||
@override
|
||||
State<ChatBackgroundTasks> createState() => _ChatBackgroundTasksState();
|
||||
}
|
||||
|
||||
class _ChatBackgroundTasksState extends State<ChatBackgroundTasks> {
|
||||
late ChatRepository _repository = ChatRepository(widget.gateway);
|
||||
StreamSubscription<JsonMap>? _frames;
|
||||
List<JsonMap> _shells = const [];
|
||||
String? _selectedId;
|
||||
ChatShellOutputSnapshot? _output;
|
||||
String? _listError;
|
||||
int _generation = 0;
|
||||
bool _disposed = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_listen();
|
||||
unawaited(_loadShells());
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ChatBackgroundTasks oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.gateway != widget.gateway ||
|
||||
oldWidget.sessionId != widget.sessionId) {
|
||||
unawaited(_frames?.cancel());
|
||||
_generation++;
|
||||
_repository = ChatRepository(widget.gateway);
|
||||
_shells = const [];
|
||||
_selectedId = null;
|
||||
_output = null;
|
||||
_listError = null;
|
||||
_listen();
|
||||
unawaited(_loadShells());
|
||||
return;
|
||||
}
|
||||
if (oldWidget.syncToken != widget.syncToken) {
|
||||
// The reconnect repair: an exit could have been lost in the gap.
|
||||
_shells = const [];
|
||||
_selectedId = null;
|
||||
_output = null;
|
||||
_listError = null;
|
||||
unawaited(_loadShells());
|
||||
}
|
||||
}
|
||||
|
||||
void _listen() =>
|
||||
_frames = widget.gateway.frames.listen(_onFrame, onError: (_) {});
|
||||
|
||||
void _onFrame(JsonMap envelope) {
|
||||
if (_disposed || envelope['type'] != 'chat_event') return;
|
||||
final value = envelope['chat_event'];
|
||||
if (value is! Map) return;
|
||||
final frame = Map<String, dynamic>.from(value);
|
||||
if ('${frame['session_id'] ?? ''}' != widget.sessionId) return;
|
||||
if (frame['kind'] != 'shell') return;
|
||||
final valueShell = frame['shell'];
|
||||
if (valueShell is! Map) return;
|
||||
final next = mergeShellFrame(
|
||||
_shells,
|
||||
Map<String, dynamic>.from(valueShell),
|
||||
);
|
||||
setState(() {
|
||||
_shells = next;
|
||||
_dropStaleSelection();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _loadShells() async {
|
||||
final token = ++_generation;
|
||||
try {
|
||||
final running = await _repository.shells(widget.sessionId);
|
||||
if (!mounted || token != _generation) return;
|
||||
setState(() {
|
||||
_shells = shellsLoaded(_shells, running);
|
||||
_listError = null;
|
||||
_dropStaleSelection();
|
||||
});
|
||||
} catch (error) {
|
||||
if (!mounted || token != _generation) return;
|
||||
setState(
|
||||
() => _listError = describeErrorReason(
|
||||
error,
|
||||
fallback: 'The server did not answer.',
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// An exit, or a fresh snapshot that no longer lists the selected task,
|
||||
/// closes its pane so a finished task never keeps showing output.
|
||||
void _dropStaleSelection() {
|
||||
final selected = _selectedId;
|
||||
if (selected == null) return;
|
||||
if (!runningShells(_shells).any((shell) => shellIdOf(shell) == selected)) {
|
||||
_selectedId = null;
|
||||
_output = null;
|
||||
}
|
||||
}
|
||||
|
||||
void _select(String shellId) {
|
||||
final closing = _selectedId == shellId;
|
||||
if (!closing &&
|
||||
!runningShells(_shells).any((shell) => shellIdOf(shell) == shellId)) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_selectedId = closing ? null : shellId;
|
||||
_output = null;
|
||||
});
|
||||
if (!closing) unawaited(_readOutput(shellId));
|
||||
}
|
||||
|
||||
Future<void> _readOutput(String shellId) async {
|
||||
if (_selectedId != shellId) return;
|
||||
setState(() => _output = const ChatShellOutputSnapshot(loading: true));
|
||||
try {
|
||||
final reply = await _repository.shellOutput(
|
||||
widget.sessionId,
|
||||
shellId,
|
||||
cursor: 0,
|
||||
limit: chatShellOutputLimit,
|
||||
);
|
||||
if (!mounted || _selectedId != shellId) return;
|
||||
final page = ChatShellOutputPage.fromReply(reply);
|
||||
final reported = page.shell;
|
||||
setState(() {
|
||||
if (reported != null && !blankShellValue(reported['id'])) {
|
||||
_shells = mergeShellFrame(_shells, reported);
|
||||
}
|
||||
_output = ChatShellOutputSnapshot(page: page);
|
||||
_dropStaleSelection();
|
||||
});
|
||||
} catch (error) {
|
||||
if (!mounted || _selectedId != shellId) return;
|
||||
setState(
|
||||
() => _output = ChatShellOutputSnapshot(
|
||||
error: describeErrorReason(
|
||||
error,
|
||||
fallback: 'The server did not answer.',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_generation++;
|
||||
unawaited(_frames?.cancel());
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final running = runningShells(_shells);
|
||||
final error = _listError;
|
||||
// Recorded facts only, honestly: no tasks and no refusal draws nothing.
|
||||
if (running.isEmpty && error == null) return const SizedBox.shrink();
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final selectedShell = _selectedShell(running);
|
||||
return Padding(
|
||||
key: const Key('chat-background-tasks'),
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 4),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
spacing: 4,
|
||||
children: [
|
||||
_heading(context, cupertino, running.length, error == null),
|
||||
if (error != null) _listFailure(context, cupertino, error),
|
||||
if (running.isNotEmpty) _taskList(context, cupertino, running),
|
||||
if (selectedShell != null)
|
||||
ChatBackgroundTaskDetail(
|
||||
key: const Key('chat-bg-task-detail'),
|
||||
shell: selectedShell,
|
||||
output: _output,
|
||||
onRefresh: () => unawaited(_readOutput(shellIdOf(selectedShell))),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// The running task this visit has selected, or null after it exited.
|
||||
JsonMap? _selectedShell(List<JsonMap> running) {
|
||||
for (final shell in running) {
|
||||
if (shellIdOf(shell) == _selectedId) return shell;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Widget _heading(
|
||||
BuildContext context,
|
||||
bool cupertino,
|
||||
int count,
|
||||
bool countKnown,
|
||||
) {
|
||||
final titleStyle = cupertino
|
||||
? CupertinoTheme.of(context).textTheme.textStyle
|
||||
: Theme.of(context).textTheme.labelLarge;
|
||||
final countStyle = cupertino
|
||||
? CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith(
|
||||
color: CupertinoColors.secondaryLabel.resolveFrom(context),
|
||||
)
|
||||
: Theme.of(context).textTheme.labelMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
);
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Semantics(
|
||||
header: true,
|
||||
child: Text(backgroundTasksTitle, style: titleStyle),
|
||||
),
|
||||
),
|
||||
if (countKnown)
|
||||
Text(backgroundTasksRunningLabel(count), style: countStyle),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _listFailure(BuildContext context, bool cupertino, String error) {
|
||||
final color = cupertino
|
||||
? CupertinoColors.systemRed.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.error;
|
||||
final style =
|
||||
(cupertino
|
||||
? CupertinoTheme.of(context).textTheme.textStyle
|
||||
: Theme.of(context).textTheme.bodySmall)
|
||||
?.copyWith(color: color);
|
||||
return Row(
|
||||
key: const Key('chat-background-tasks-error'),
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(
|
||||
cupertino
|
||||
? CupertinoIcons.exclamationmark_circle
|
||||
: Icons.error_outline,
|
||||
color: color,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Text('Background tasks unavailable. $error', style: style),
|
||||
),
|
||||
),
|
||||
ChatBackgroundTaskButton(
|
||||
label: shellOutputRetryLabel,
|
||||
onPressed: () => unawaited(_loadShells()),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _taskList(
|
||||
BuildContext context,
|
||||
bool cupertino,
|
||||
List<JsonMap> running,
|
||||
) {
|
||||
final rows = [
|
||||
for (final shell in running)
|
||||
_taskRow(context, cupertino, shell, shellIdOf(shell) == _selectedId),
|
||||
];
|
||||
final list = Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: rows,
|
||||
);
|
||||
if (rows.length <= backgroundTaskVisibleRows) return list;
|
||||
// More than the recorded visible-row cap: the list scrolls instead of
|
||||
// pushing the composer down. The bound is the host's own touch target.
|
||||
return ConstrainedBox(
|
||||
constraints: const BoxConstraints(
|
||||
maxHeight: kMinInteractiveDimension * backgroundTaskVisibleRows,
|
||||
),
|
||||
child: SingleChildScrollView(child: list),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _taskRow(
|
||||
BuildContext context,
|
||||
bool cupertino,
|
||||
JsonMap shell,
|
||||
bool selected,
|
||||
) {
|
||||
final id = shellIdOf(shell);
|
||||
final key = ValueKey<String>('chat-bg-task-$id');
|
||||
final command = shellCommandSummary(shell['command']);
|
||||
if (cupertino) {
|
||||
final primary = CupertinoTheme.of(context).primaryColor;
|
||||
final muted = CupertinoColors.secondaryLabel.resolveFrom(context);
|
||||
final style = CupertinoTheme.of(context).textTheme.textStyle;
|
||||
return Semantics(
|
||||
selected: selected,
|
||||
button: true,
|
||||
child: CupertinoButton(
|
||||
key: key,
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: () => _select(id),
|
||||
child: Row(
|
||||
spacing: 8,
|
||||
children: [
|
||||
Icon(CupertinoIcons.play_fill, color: primary),
|
||||
Text(shellRowLabel, style: style.copyWith(color: primary)),
|
||||
Expanded(
|
||||
child: Text(
|
||||
command,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: style.copyWith(color: muted),
|
||||
),
|
||||
),
|
||||
if (selected)
|
||||
Text(
|
||||
shellDetailsLabel,
|
||||
style: CupertinoTheme.of(
|
||||
context,
|
||||
).textTheme.tabLabelTextStyle.copyWith(color: muted),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final theme = Theme.of(context);
|
||||
return Semantics(
|
||||
selected: selected,
|
||||
child: ListTile(
|
||||
key: key,
|
||||
dense: true,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
leading: Icon(Icons.play_arrow, color: theme.colorScheme.tertiary),
|
||||
title: Row(
|
||||
spacing: 8,
|
||||
children: [
|
||||
Text(
|
||||
shellRowLabel,
|
||||
style: theme.textTheme.labelMedium?.copyWith(
|
||||
color: theme.colorScheme.tertiary,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
command,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.labelMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
trailing: selected
|
||||
? Text(shellDetailsLabel, style: theme.textTheme.labelSmall)
|
||||
: null,
|
||||
onTap: () => _select(id),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import '../domain/chat_transcript.dart';
|
||||
import '../ui/sessions/chat_adaptive.dart';
|
||||
import '../ui/transcript/chat_markdown_view.dart';
|
||||
import '../ui/transcript/chat_message_view.dart';
|
||||
import 'chat_background_tasks.dart';
|
||||
import 'chat_composer_bar.dart';
|
||||
import 'chat_composer_controller.dart';
|
||||
import 'chat_draft_store.dart';
|
||||
@@ -290,6 +291,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
final liveNotice = _noticeOf(notices, ChatNoticeKind.liveFailure);
|
||||
return Column(
|
||||
children: [
|
||||
// The session's still-running background tasks, above the transcript
|
||||
// and outside its scroller (web C11). It removes itself when the last
|
||||
// task exits and never draws a finished task.
|
||||
ChatBackgroundTasks(
|
||||
key: ValueKey<String>('chat-background-tasks-${widget.sessionId}'),
|
||||
gateway: widget.gateway,
|
||||
sessionId: widget.sessionId,
|
||||
syncToken: widget.syncToken,
|
||||
),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
key: ValueKey<String>('chat-thread-${widget.sessionId}'),
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// The background shells a chat session owns (C11).
|
||||
///
|
||||
/// These are recorded facts only: the status and command come from the server's
|
||||
/// `chat_shells` snapshot or a pushed `shell` frame. Nothing here invents an
|
||||
/// exit, an output or a command, and every read below is scoped to one session
|
||||
/// so a task stays linked to the conversation that owns it.
|
||||
const chatShellRunning = 'running';
|
||||
const chatShellExited = 'exited';
|
||||
|
||||
/// The retained shell tail a client keeps (mirrors ChatStore's observation
|
||||
/// bound). This is not task history, only what this client itself observed.
|
||||
const observedShellLimit = 16;
|
||||
|
||||
/// How many running-task rows are drawn before the list scrolls instead of
|
||||
/// growing, so a burst of tasks cannot push the composer off screen.
|
||||
const backgroundTaskVisibleRows = 3;
|
||||
|
||||
/// The server's absolute-byte bound for one lazy output page
|
||||
/// (ChatShellOutputLimit). Reads always start at cursor 0.
|
||||
const chatShellOutputLimit = 64 * 1024;
|
||||
|
||||
const backgroundTasksTitle = 'Background tasks';
|
||||
const shellRowLabel = 'Running';
|
||||
const shellDetailsLabel = 'Details';
|
||||
|
||||
String backgroundTasksRunningLabel(int count) => '$count running';
|
||||
|
||||
const shellOutputCommandLabel = 'Command';
|
||||
const shellOutputUnavailableLabel = 'Unavailable';
|
||||
const shellOutputTaskIdentityLabel = 'Task identity';
|
||||
const shellStatusRunningLabel = 'Status: running';
|
||||
const shellOutputUnavailableNote = 'Output unavailable for this task.';
|
||||
const shellOutputEmptyNote = 'No output yet.';
|
||||
const shellOutputLabel = 'Output';
|
||||
const shellOutputBoundedNote = 'Output is bounded to 64 KiB.';
|
||||
const shellOutputRetryLabel = 'Retry';
|
||||
const shellOutputRefreshLabel = 'Refresh';
|
||||
|
||||
/// The generic name for a running shell that reported no command, rather than
|
||||
/// an empty row. Mirrors the web and Android shellCommandSummary.
|
||||
const shellCommandFallback = 'background process';
|
||||
|
||||
/// A one-line command is elided past this width like a tool call's detail.
|
||||
const shellCommandSummaryLength = 72;
|
||||
|
||||
bool blankShellValue(Object? value) => value == null || '$value'.trim().isEmpty;
|
||||
|
||||
String shellIdOf(JsonMap shell) => '${shell['id'] ?? ''}';
|
||||
|
||||
/// Whether [shell] is a task that is still running: a non-blank id whose status
|
||||
/// the server recorded as running. An exited shell is never a task.
|
||||
bool isRunningShell(JsonMap shell) =>
|
||||
!blankShellValue(shell['id']) &&
|
||||
'${shell['status'] ?? ''}' == chatShellRunning;
|
||||
|
||||
/// The running tasks in the order they started. The visible-row cap is a view
|
||||
/// concern, so this never truncates the recorded list.
|
||||
List<JsonMap> runningShells(List<JsonMap> shells) => [
|
||||
for (final shell in shells)
|
||||
if (isRunningShell(shell)) shell,
|
||||
];
|
||||
|
||||
/// Folds one shell frame (or a snapshot entry) into the retained shells, keyed
|
||||
/// by id and kept in observation order.
|
||||
///
|
||||
/// A blank incoming command keeps the command already learned, so a later frame
|
||||
/// that omits it never blanks the row. The retained list is trimmed to the last
|
||||
/// [observedShellLimit] entries.
|
||||
List<JsonMap> mergeShellFrame(List<JsonMap> shells, JsonMap? shell) {
|
||||
if (shell == null || blankShellValue(shell['id'])) return shells;
|
||||
final id = shellIdOf(shell);
|
||||
final next = List<JsonMap>.of(shells);
|
||||
final index = next.indexWhere((candidate) => shellIdOf(candidate) == id);
|
||||
final prior = index >= 0 ? next[index] : null;
|
||||
final merged = <String, dynamic>{
|
||||
...shell,
|
||||
'id': id,
|
||||
'command': blankShellValue(shell['command'])
|
||||
? (prior?['command'] ?? '')
|
||||
: shell['command'],
|
||||
};
|
||||
if (index >= 0) {
|
||||
next[index] = merged;
|
||||
} else {
|
||||
next.add(merged);
|
||||
}
|
||||
return next.length <= observedShellLimit
|
||||
? next
|
||||
: next.sublist(next.length - observedShellLimit);
|
||||
}
|
||||
|
||||
/// Folds a `chat_shells` snapshot into the retained shells: an exit this client
|
||||
/// observed is kept, the server's current running list wins by id, and a shell
|
||||
/// the server no longer lists (and whose exit this client never saw) drops out.
|
||||
List<JsonMap> shellsLoaded(List<JsonMap> shells, List<JsonMap> running) {
|
||||
final byId = <String, JsonMap>{};
|
||||
for (final shell in shells) {
|
||||
if (!blankShellValue(shell['id']) &&
|
||||
'${shell['status'] ?? ''}' == chatShellExited) {
|
||||
byId[shellIdOf(shell)] = shell;
|
||||
}
|
||||
}
|
||||
for (final shell in running) {
|
||||
if (blankShellValue(shell['id'])) continue;
|
||||
byId[shellIdOf(shell)] = shell;
|
||||
}
|
||||
final values = byId.values.toList();
|
||||
return values.length <= observedShellLimit
|
||||
? values
|
||||
: values.sublist(values.length - observedShellLimit);
|
||||
}
|
||||
|
||||
/// The one-line command a background process is running: whitespace collapsed,
|
||||
/// elided past [shellCommandSummaryLength], and a generic word when the server
|
||||
/// reported no command.
|
||||
String shellCommandSummary(Object? command) {
|
||||
final text = '${command ?? ''}'.trim().replaceAll(RegExp(r'\s+'), ' ');
|
||||
if (text.isEmpty) return shellCommandFallback;
|
||||
if (text.length <= shellCommandSummaryLength) return text;
|
||||
return '${text.substring(0, shellCommandSummaryLength - 1).trimRight()}…';
|
||||
}
|
||||
|
||||
/// One bounded, read-only output page from a verified shell. Unknown fields stay
|
||||
/// empty/false instead of being guessed.
|
||||
class ChatShellOutputPage {
|
||||
const ChatShellOutputPage({
|
||||
this.output = '',
|
||||
this.truncated = false,
|
||||
this.unavailable = false,
|
||||
this.shell,
|
||||
});
|
||||
|
||||
factory ChatShellOutputPage.fromReply(JsonMap reply) {
|
||||
final value = reply['chat_shell_output'];
|
||||
final page = value is Map
|
||||
? Map<String, dynamic>.from(value)
|
||||
: const <String, dynamic>{};
|
||||
final shell = page['shell'];
|
||||
return ChatShellOutputPage(
|
||||
output: '${page['output'] ?? ''}',
|
||||
truncated: page['truncated'] == true,
|
||||
unavailable: page['unavailable'] == true,
|
||||
shell: shell is Map ? Map<String, dynamic>.from(shell) : null,
|
||||
);
|
||||
}
|
||||
|
||||
final String output;
|
||||
final bool truncated;
|
||||
final bool unavailable;
|
||||
|
||||
/// The shell the page reports, so a settled task can be folded back into the
|
||||
/// retained list without losing the command already learned.
|
||||
final JsonMap? shell;
|
||||
}
|
||||
|
||||
/// The five shapes a selected task's output area can take. Unknown fields are
|
||||
/// reported as unavailable or empty, never rendered as invented output.
|
||||
enum ChatShellOutputState { none, loading, error, unavailable, empty, ready }
|
||||
|
||||
class ChatShellOutputSnapshot {
|
||||
const ChatShellOutputSnapshot({
|
||||
this.loading = false,
|
||||
this.error = '',
|
||||
this.page,
|
||||
});
|
||||
|
||||
final bool loading;
|
||||
final String error;
|
||||
final ChatShellOutputPage? page;
|
||||
|
||||
ChatShellOutputState get state {
|
||||
if (loading) return ChatShellOutputState.loading;
|
||||
if (error.trim().isNotEmpty) return ChatShellOutputState.error;
|
||||
final current = page;
|
||||
if (current == null) return ChatShellOutputState.none;
|
||||
if (current.unavailable) return ChatShellOutputState.unavailable;
|
||||
if (current.output.isEmpty) return ChatShellOutputState.empty;
|
||||
return ChatShellOutputState.ready;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user