merge(app): land chat-tasks

This commit is contained in:
2026-10-22 17:56:21 +01:00
6 changed files with 1673 additions and 0 deletions
@@ -0,0 +1,251 @@
import 'dart:math' as math;
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';
/// One bounded output page: the web's 220 px pane is twelve 18 px monospace
/// lines (`web/chat.css`), so the bound is read from the host's own output type
/// and the user's text scale rather than a fixed pixel row. A longer page
/// scrolls inside this box and never moves the transcript or composer.
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.
const _outputMaxBudgetShare = 0.45;
/// 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.heightBudget,
required this.onRefresh,
});
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.
final double heightBudget;
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);
}
/// The host's own monospace body for one output page. `height` is set so the
/// visible-line bound below is measured on the same line box that is drawn.
TextStyle _outputStyle(BuildContext context, bool cupertino) =>
(cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodySmall ?? const TextStyle())
.copyWith(
fontFamily: 'monospace',
height: _outputLineHeight,
// Cupertino's style is not inheriting; a selectable body needs a
// baseline from its own style.
textBaseline: TextBaseline.alphabetic,
);
/// The number of output lines the pane shows before it scrolls: up to twelve,
/// fewer when the user's text scale or the bar's remaining height would let
/// the pane crowd out the conversation.
int _outputVisibleLineCount(BuildContext context, TextStyle style) {
final scaledLine =
MediaQuery.textScalerOf(context).scale(style.fontSize ?? 12) *
_outputLineHeight;
final fit = (heightBudget * _outputMaxBudgetShare / scaledLine).floor();
return math.max(2, math.min(_outputVisibleLines, fit));
}
/// 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,
TextStyle style,
int maxLines,
) {
final text = SelectableText(
output,
key: const Key('chat-bg-task-output'),
style: style,
// A multiline selectable body scrolls itself: the host's text control
// keeps the page selectable and gives it its own scrollbar/drag, so no
// nested scroller can steal the conversation's gestures.
maxLines: maxLines,
);
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!;
final style = _outputStyle(context, cupertino);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
spacing: 4,
children: [
_label(context, cupertino, shellOutputLabel),
_selectableOutput(
context,
cupertino,
page.output,
style,
_outputVisibleLineCount(context, style),
),
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,480 @@
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 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.
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;
int _outputGeneration = 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;
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());
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))),
),
],
),
),
),
);
}
/// 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),
),
),
],
),
),
);
}
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),
),
),
);
}
}
@@ -11,6 +11,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';
@@ -582,6 +583,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
_scheduleFollow();
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: NotificationListener<ScrollMetricsNotification>(
onNotification: _onScrollMetrics,
@@ -0,0 +1,185 @@
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'];
// A reply without the page is not evidence of an empty shell. Report it as
// unavailable (as the web refuses it) instead of inventing "No output yet.".
if (value is! Map) {
return const ChatShellOutputPage(unavailable: true);
}
final page = Map<String, dynamic>.from(value);
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;
}
}