Move live background tasks into a composer badge and modal
This commit is contained in:
@@ -16,9 +16,8 @@ import '../../../ui/text/monospace.dart';
|
||||
const _outputVisibleLines = 12;
|
||||
const _outputLineHeight = 1.5;
|
||||
|
||||
/// Even at a large text scale one pane keeps this share of the bar's own height
|
||||
/// budget, so the bar's chrome and list keep room and the conversation below it
|
||||
/// is never crowded out.
|
||||
/// Even at a large text scale the selected output stays bounded within the
|
||||
/// modal's viewport budget; the native dialog scrolls the surrounding details.
|
||||
const _outputMaxBudgetShare = 0.45;
|
||||
|
||||
/// The selected background task's read-only detail and bounded output page.
|
||||
@@ -39,9 +38,7 @@ class ChatBackgroundTaskDetail extends StatelessWidget {
|
||||
final JsonMap shell;
|
||||
final ChatShellOutputSnapshot? output;
|
||||
|
||||
/// The space the enclosing task bar has for its whole body. The output pane is
|
||||
/// measured against this, not the window, so a list of rows, a narrow phone or
|
||||
/// a large text scale cannot make the detail outgrow its own bar.
|
||||
/// The modal viewport's height budget, used to bound its selectable output.
|
||||
final double heightBudget;
|
||||
|
||||
final VoidCallback onRefresh;
|
||||
@@ -135,6 +132,7 @@ class ChatBackgroundTaskDetail extends StatelessWidget {
|
||||
) {
|
||||
final text = SelectableText(
|
||||
output,
|
||||
semanticsLabel: output,
|
||||
key: const Key('chat-bg-task-output'),
|
||||
style: style,
|
||||
// A multiline selectable body scrolls itself: the host's text control
|
||||
|
||||
@@ -1,34 +1,13 @@
|
||||
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';
|
||||
import 'chat_background_tasks_controller.dart';
|
||||
import 'chat_background_tasks_panel.dart';
|
||||
|
||||
/// The bar is pinned above the transcript, so the whole surface keeps at most
|
||||
/// this share of the window and scrolls inside itself. The transcript and the
|
||||
/// composer therefore always keep most of the window, however many tasks are
|
||||
/// listed and however large the selected page is.
|
||||
const backgroundTaskViewportShare = 0.5;
|
||||
|
||||
/// 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.
|
||||
/// Compact live task count, mounted above Send. Details live only in its modal.
|
||||
class ChatBackgroundTasks extends StatefulWidget {
|
||||
const ChatBackgroundTasks({
|
||||
super.key,
|
||||
@@ -39,9 +18,6 @@ class ChatBackgroundTasks extends StatefulWidget {
|
||||
|
||||
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
|
||||
@@ -49,432 +25,128 @@ class ChatBackgroundTasks extends StatefulWidget {
|
||||
}
|
||||
|
||||
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;
|
||||
int _outputGeneration = 0;
|
||||
bool _disposed = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_listen();
|
||||
unawaited(_loadShells());
|
||||
}
|
||||
late final controller = ChatBackgroundTasksController(
|
||||
widget.gateway,
|
||||
widget.sessionId,
|
||||
);
|
||||
TransitionRoute<void>? _modal;
|
||||
|
||||
@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());
|
||||
_closeModal();
|
||||
controller.replace(widget.gateway, widget.sessionId, notify: false);
|
||||
} else if (oldWidget.syncToken != widget.syncToken) {
|
||||
controller.reconnect(notify: false);
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
void _closeModal() {
|
||||
final route = _modal;
|
||||
_modal = null;
|
||||
if (route == null || !route.isActive) return;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (route.isActive) route.navigator?.removeRoute(route);
|
||||
});
|
||||
}
|
||||
|
||||
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.',
|
||||
),
|
||||
);
|
||||
void _open() {
|
||||
if (_modal != null) return;
|
||||
FocusManager.instance.primaryFocus?.unfocus();
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
Widget dialog(BuildContext context) {
|
||||
final content = ChatBackgroundTasksPanel(controller: controller);
|
||||
void close() => Navigator.of(context).pop();
|
||||
return cupertino
|
||||
? CupertinoAlertDialog(
|
||||
key: const Key('chat-background-tasks-modal'),
|
||||
title: const Text(backgroundTasksTitle),
|
||||
content: content,
|
||||
actions: [
|
||||
CupertinoDialogAction(
|
||||
onPressed: close,
|
||||
child: const Text('Done'),
|
||||
),
|
||||
],
|
||||
)
|
||||
: AlertDialog(
|
||||
key: const Key('chat-background-tasks-modal'),
|
||||
title: const Text(backgroundTasksTitle),
|
||||
scrollable: true,
|
||||
content: content,
|
||||
actions: [
|
||||
TextButton(onPressed: close, child: const Text('Done')),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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;
|
||||
final TransitionRoute<void> route = cupertino
|
||||
? CupertinoDialogRoute<void>(
|
||||
context: context,
|
||||
barrierDismissible: true,
|
||||
builder: dialog,
|
||||
)
|
||||
: DialogRoute<void>(context: context, builder: dialog);
|
||||
_modal = route;
|
||||
Navigator.of(context, rootNavigator: true).push(route);
|
||||
route.completed.then((_) {
|
||||
if (_modal == route) _modal = null;
|
||||
});
|
||||
if (!closing) unawaited(_readOutput(shellId));
|
||||
}
|
||||
|
||||
Future<void> _readOutput(String shellId) async {
|
||||
if (_selectedId != shellId) return;
|
||||
final token = ++_outputGeneration;
|
||||
setState(() => _output = const ChatShellOutputSnapshot(loading: true));
|
||||
try {
|
||||
final reply = await _repository.shellOutput(
|
||||
widget.sessionId,
|
||||
shellId,
|
||||
cursor: 0,
|
||||
limit: chatShellOutputLimit,
|
||||
);
|
||||
if (!mounted || token != _outputGeneration || _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 || token != _outputGeneration || _selectedId != shellId) {
|
||||
return;
|
||||
}
|
||||
setState(
|
||||
() => _output = ChatShellOutputSnapshot(
|
||||
error: describeErrorReason(
|
||||
error,
|
||||
fallback: 'The server did not answer.',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_generation++;
|
||||
unawaited(_frames?.cancel());
|
||||
_closeModal();
|
||||
controller.dispose();
|
||||
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);
|
||||
// The bar is pinned above the transcript, so it keeps a bounded share of
|
||||
// the window and scrolls its own body. Even three rows plus an open detail
|
||||
// can then never push the transcript or the composer out of the viewport.
|
||||
return ConstrainedBox(
|
||||
key: const Key('chat-background-tasks'),
|
||||
constraints: BoxConstraints(
|
||||
maxHeight:
|
||||
MediaQuery.sizeOf(context).height * backgroundTaskViewportShare,
|
||||
),
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) => SingleChildScrollView(
|
||||
key: const Key('chat-background-tasks-scroll'),
|
||||
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,
|
||||
// The detail derives its output pane from the space this bar
|
||||
// actually has left instead of the whole window.
|
||||
heightBudget: constraints.maxHeight,
|
||||
onRefresh: () =>
|
||||
unawaited(_readOutput(shellIdOf(selectedShell))),
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: controller,
|
||||
builder: (context, _) {
|
||||
final count = controller.running.length;
|
||||
final label = controller.error != null
|
||||
? 'Tasks'
|
||||
: controller.loading && count == 0
|
||||
? 'Tasks…'
|
||||
: '$count ${count == 1 ? 'task' : 'tasks'}';
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final button = cupertino
|
||||
? CupertinoButton(
|
||||
key: const Key('chat-background-tasks-button'),
|
||||
sizeStyle: CupertinoButtonSize.small,
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: _open,
|
||||
child: Text(
|
||||
label,
|
||||
style: CupertinoTheme.of(context).textTheme.tabLabelTextStyle
|
||||
.copyWith(color: CupertinoTheme.of(context).primaryColor),
|
||||
),
|
||||
)
|
||||
: TextButton(
|
||||
key: const Key('chat-background-tasks-button'),
|
||||
onPressed: _open,
|
||||
child: Text(
|
||||
label,
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 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(
|
||||
spacing: 8,
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Semantics(
|
||||
header: true,
|
||||
child: Text(
|
||||
backgroundTasksTitle,
|
||||
// One compact line like the web's head: a large text scale elides
|
||||
// rather than wrapping the heading into a tall stack.
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: titleStyle,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (countKnown)
|
||||
Flexible(
|
||||
child: Text(
|
||||
backgroundTasksRunningLabel(count),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
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(
|
||||
key: const Key('chat-bg-task-list'),
|
||||
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,
|
||||
child: CupertinoButton(
|
||||
key: key,
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: () => _select(id),
|
||||
child: Row(
|
||||
spacing: 8,
|
||||
children: [
|
||||
Icon(CupertinoIcons.play_fill, color: primary),
|
||||
Flexible(
|
||||
child: Text(
|
||||
shellRowLabel,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: style.copyWith(color: primary),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
flex: 3,
|
||||
child: Text(
|
||||
command,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: style.copyWith(color: muted),
|
||||
),
|
||||
),
|
||||
if (selected)
|
||||
Flexible(
|
||||
child: Text(
|
||||
shellDetailsLabel,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: CupertinoTheme.of(
|
||||
context,
|
||||
).textTheme.tabLabelTextStyle.copyWith(color: muted),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
button: true,
|
||||
excludeSemantics: true,
|
||||
onTap: _open,
|
||||
label: controller.error != null
|
||||
? 'Background tasks unavailable'
|
||||
: 'Background tasks, $label',
|
||||
child: button,
|
||||
);
|
||||
}
|
||||
final theme = Theme.of(context);
|
||||
final fullCommand = '${shell['command'] ?? ''}'.trim();
|
||||
final rowStyle = theme.textTheme.labelMedium;
|
||||
return Semantics(
|
||||
selected: selected,
|
||||
child: Tooltip(
|
||||
// The row elides its command; the full recorded one stays reachable,
|
||||
// as the web row's `title` attribute does.
|
||||
message: fullCommand.isEmpty ? command : fullCommand,
|
||||
excludeFromSemantics: true,
|
||||
child: ListTile(
|
||||
key: key,
|
||||
dense: true,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
leading: Icon(Icons.play_arrow, color: theme.colorScheme.tertiary),
|
||||
title: Row(
|
||||
spacing: 8,
|
||||
children: [
|
||||
// Every part of the row is flexible: at a large text scale or a
|
||||
// narrow phone the labels elide instead of overflowing the row.
|
||||
Flexible(
|
||||
child: Text(
|
||||
shellRowLabel,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: rowStyle?.copyWith(color: theme.colorScheme.tertiary),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
flex: 3,
|
||||
child: Text(
|
||||
command,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: rowStyle?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (selected)
|
||||
Flexible(
|
||||
child: Text(
|
||||
shellDetailsLabel,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.labelSmall,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
onTap: () => _select(id),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../core/error_reason.dart';
|
||||
import '../data/chat_repository.dart';
|
||||
import '../domain/chat_shells.dart';
|
||||
|
||||
/// One session's live background tasks and lazy, bounded output selection.
|
||||
class ChatBackgroundTasksController extends ChangeNotifier {
|
||||
ChatBackgroundTasksController(this.gateway, this.sessionId) {
|
||||
_listen();
|
||||
unawaited(refresh());
|
||||
}
|
||||
|
||||
ApiGateway gateway;
|
||||
String sessionId;
|
||||
late ChatRepository _repository = ChatRepository(gateway);
|
||||
StreamSubscription<JsonMap>? _frames;
|
||||
List<JsonMap> _shells = const [];
|
||||
Map<String, JsonMap>? _loadFrames;
|
||||
String? selectedId;
|
||||
ChatShellOutputSnapshot? output;
|
||||
String? error;
|
||||
bool loading = true;
|
||||
bool _disposed = false;
|
||||
int _generation = 0;
|
||||
int _outputGeneration = 0;
|
||||
|
||||
List<JsonMap> get running => runningShells(_shells);
|
||||
JsonMap? get selectedShell =>
|
||||
running.where((shell) => shellIdOf(shell) == selectedId).firstOrNull;
|
||||
|
||||
void replace(
|
||||
ApiGateway nextGateway,
|
||||
String nextSessionId, {
|
||||
bool notify = true,
|
||||
}) {
|
||||
if (_disposed) return;
|
||||
unawaited(_frames?.cancel());
|
||||
gateway = nextGateway;
|
||||
sessionId = nextSessionId;
|
||||
_repository = ChatRepository(gateway);
|
||||
_listen();
|
||||
reconnect(notify: notify);
|
||||
}
|
||||
|
||||
void reconnect({bool notify = true}) {
|
||||
if (_disposed) return;
|
||||
_shells = const [];
|
||||
selectedId = null;
|
||||
output = null;
|
||||
error = null;
|
||||
_outputGeneration++;
|
||||
unawaited(refresh(notify: notify));
|
||||
}
|
||||
|
||||
void _listen() => _frames = gateway.frames.listen((envelope) {
|
||||
if (_disposed || envelope['type'] != 'chat_event') return;
|
||||
final frame = envelope['chat_event'];
|
||||
if (frame is! Map ||
|
||||
frame['session_id'] != sessionId ||
|
||||
frame['kind'] != 'shell' ||
|
||||
frame['shell'] is! Map) {
|
||||
return;
|
||||
}
|
||||
_shells = mergeShellFrame(
|
||||
_shells,
|
||||
Map<String, dynamic>.from(frame['shell'] as Map),
|
||||
);
|
||||
final id = shellIdOf(Map<String, dynamic>.from(frame['shell'] as Map));
|
||||
if (_loadFrames != null && !blankShellValue(id)) {
|
||||
_loadFrames![id] = _shells.firstWhere((shell) => shellIdOf(shell) == id);
|
||||
if (_loadFrames!.length > observedShellLimit) {
|
||||
_loadFrames!.remove(_loadFrames!.keys.first);
|
||||
}
|
||||
}
|
||||
_dropStaleSelection();
|
||||
notifyListeners();
|
||||
}, onError: (_) {});
|
||||
|
||||
Future<void> refresh({bool notify = true}) async {
|
||||
if (_disposed) return;
|
||||
final token = ++_generation;
|
||||
final observed = <String, JsonMap>{};
|
||||
_loadFrames = observed;
|
||||
loading = true;
|
||||
if (notify) notifyListeners();
|
||||
try {
|
||||
final shells = await _repository.shells(sessionId);
|
||||
if (_disposed || token != _generation) return;
|
||||
_shells = shellsLoaded(_shells, shells);
|
||||
// Live frames are newer than a snapshot requested before they arrived.
|
||||
for (final frame in observed.values) {
|
||||
_shells = mergeShellFrame(_shells, frame);
|
||||
}
|
||||
error = null;
|
||||
_dropStaleSelection();
|
||||
} catch (failure) {
|
||||
if (_disposed || token != _generation) return;
|
||||
error = describeErrorReason(
|
||||
failure,
|
||||
fallback: 'The server did not answer.',
|
||||
);
|
||||
}
|
||||
loading = false;
|
||||
_loadFrames = null;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _dropStaleSelection() {
|
||||
if (selectedId == null || selectedShell != null) return;
|
||||
selectedId = null;
|
||||
output = null;
|
||||
_outputGeneration++;
|
||||
}
|
||||
|
||||
void select(String id) {
|
||||
if (_disposed) return;
|
||||
if (selectedId == id) {
|
||||
selectedId = null;
|
||||
output = null;
|
||||
_outputGeneration++;
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
if (!running.any((shell) => shellIdOf(shell) == id)) return;
|
||||
selectedId = id;
|
||||
unawaited(readOutput());
|
||||
}
|
||||
|
||||
Future<void> readOutput() async {
|
||||
final id = selectedId;
|
||||
if (_disposed || id == null) return;
|
||||
final token = ++_outputGeneration;
|
||||
output = const ChatShellOutputSnapshot(loading: true);
|
||||
notifyListeners();
|
||||
try {
|
||||
final reply = await _repository.shellOutput(
|
||||
sessionId,
|
||||
id,
|
||||
cursor: 0,
|
||||
limit: chatShellOutputLimit,
|
||||
);
|
||||
if (_disposed || token != _outputGeneration || selectedId != id) return;
|
||||
final page = ChatShellOutputPage.fromReply(reply);
|
||||
if (page.shell case final shell? when !blankShellValue(shell['id'])) {
|
||||
_shells = mergeShellFrame(_shells, shell);
|
||||
}
|
||||
output = ChatShellOutputSnapshot(page: page);
|
||||
_dropStaleSelection();
|
||||
} catch (failure) {
|
||||
if (_disposed || token != _outputGeneration || selectedId != id) return;
|
||||
output = ChatShellOutputSnapshot(
|
||||
error: describeErrorReason(
|
||||
failure,
|
||||
fallback: 'The server did not answer.',
|
||||
),
|
||||
);
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_generation++;
|
||||
_outputGeneration++;
|
||||
unawaited(_frames?.cancel());
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../domain/chat_shells.dart';
|
||||
import '../ui/sessions/chat_adaptive.dart';
|
||||
import 'chat_background_task_detail.dart';
|
||||
import 'chat_background_tasks_controller.dart';
|
||||
|
||||
/// Scrollable modal content, backed by the same live controller as its badge.
|
||||
class ChatBackgroundTasksPanel extends StatelessWidget {
|
||||
const ChatBackgroundTasksPanel({super.key, required this.controller});
|
||||
|
||||
final ChatBackgroundTasksController controller;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: controller,
|
||||
builder: (context, _) {
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final running = controller.running;
|
||||
final shell = controller.selectedShell;
|
||||
final error = controller.error;
|
||||
return Column(
|
||||
key: const Key('chat-background-tasks'),
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (controller.loading)
|
||||
cupertino
|
||||
? const CupertinoActivityIndicator()
|
||||
: const LinearProgressIndicator(),
|
||||
if (error != null) ...[
|
||||
Text(
|
||||
'Background tasks unavailable. $error',
|
||||
key: const Key('chat-background-tasks-error'),
|
||||
),
|
||||
ChatBackgroundTaskButton(
|
||||
label: 'Retry',
|
||||
onPressed: controller.refresh,
|
||||
),
|
||||
] else if (!controller.loading && running.isEmpty)
|
||||
const Text('No background tasks running.'),
|
||||
if (running.isNotEmpty)
|
||||
Text(backgroundTasksRunningLabel(running.length)),
|
||||
for (final task in running) ...[
|
||||
_taskRow(context, task, cupertino),
|
||||
if (shell != null && shellIdOf(task) == controller.selectedId)
|
||||
ChatBackgroundTaskDetail(
|
||||
key: const Key('chat-bg-task-detail'),
|
||||
shell: shell,
|
||||
output: controller.output,
|
||||
heightBudget: MediaQuery.sizeOf(context).height,
|
||||
onRefresh: controller.readOutput,
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
Widget _taskRow(
|
||||
BuildContext context,
|
||||
Map<String, dynamic> shell,
|
||||
bool cupertino,
|
||||
) {
|
||||
final id = shellIdOf(shell);
|
||||
final selected = controller.selectedId == id;
|
||||
final title = Text(
|
||||
shellCommandSummary(shell['command']),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
);
|
||||
if (cupertino) {
|
||||
return Semantics(
|
||||
selected: selected,
|
||||
child: CupertinoListTile(
|
||||
key: ValueKey('chat-bg-task-$id'),
|
||||
title: title,
|
||||
subtitle: const Text(shellRowLabel),
|
||||
backgroundColor: selected
|
||||
? CupertinoColors.tertiarySystemFill.resolveFrom(context)
|
||||
: null,
|
||||
onTap: () => controller.select(id),
|
||||
),
|
||||
);
|
||||
}
|
||||
return ListTile(
|
||||
key: ValueKey('chat-bg-task-$id'),
|
||||
title: title,
|
||||
subtitle: const Text(shellRowLabel),
|
||||
selected: selected,
|
||||
onTap: () => controller.select(id),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,7 @@ class ChatComposerBar extends StatefulWidget {
|
||||
this.picker,
|
||||
this.commands,
|
||||
this.paste,
|
||||
this.backgroundTasks,
|
||||
});
|
||||
|
||||
final ChatComposerController composer;
|
||||
@@ -88,6 +89,7 @@ class ChatComposerBar extends StatefulWidget {
|
||||
|
||||
/// The host clipboard-file seam; production uses [hostChatClipboardPaste].
|
||||
final ChatClipboardPaste? paste;
|
||||
final Widget? backgroundTasks;
|
||||
|
||||
@override
|
||||
State<ChatComposerBar> createState() => _ChatComposerBarState();
|
||||
@@ -627,11 +629,24 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
if (widget.running) ...[
|
||||
_primary(context, cupertino, stop: true),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
_primary(context, cupertino),
|
||||
Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
if (widget.backgroundTasks != null)
|
||||
widget.backgroundTasks!,
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (widget.running) ...[
|
||||
_primary(context, cupertino, stop: true),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
_primary(context, cupertino),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
|
||||
@@ -782,15 +782,6 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
},
|
||||
),
|
||||
),
|
||||
// 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: NotificationListener<ScrollMetricsNotification>(
|
||||
onNotification: _onScrollMetrics,
|
||||
@@ -910,6 +901,12 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
running: _controller.running,
|
||||
commands: _commandActions(),
|
||||
picker: widget.attachmentPicker,
|
||||
backgroundTasks: ChatBackgroundTasks(
|
||||
key: ValueKey('chat-background-tasks-${widget.sessionId}'),
|
||||
gateway: widget.gateway,
|
||||
sessionId: widget.sessionId,
|
||||
syncToken: widget.syncToken,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -13,10 +13,6 @@ const chatShellExited = 'exited';
|
||||
/// 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;
|
||||
|
||||
Reference in New Issue
Block a user