Files
pipelines/app/lib/features/chat/domain/chat_shells.dart
T

182 lines
6.8 KiB
Dart

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;
/// 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;
}
}