Files

3145 lines
108 KiB
Dart
Raw Permalink Normal View History

2026-11-18 19:08:06 +08:00
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
2026-11-18 19:08:06 +08:00
import 'package:flutter/services.dart';
import '../api/client.dart';
2026-11-18 19:08:06 +08:00
import '../api/models.dart';
import '../api/shells.dart';
import '../background_jobs.dart';
2026-11-18 19:08:06 +08:00
import '../state.dart';
import '../widgets/composer_attachment.dart';
import '../widgets/markdown_view.dart';
import '../widgets/composer_box.dart';
import '../widgets/diff_view.dart';
import '../widgets/image_viewer.dart';
import '../widgets/pet_sprite.dart';
import '../widgets/model_controls.dart';
import '../widgets/shell_jobs.dart';
import '../widgets/slash_palette.dart';
2026-11-18 19:08:06 +08:00
import '../widgets/usage_ring.dart';
import 'files_panel.dart';
import '../l10n.dart';
2026-11-18 19:08:06 +08:00
/// The chat: streaming Markdown, tool rows, composer and sheets.
class ChatScreen extends StatefulWidget {
final AppState app;
final Session session;
/// Opens the session drawer. Null where the list is always on screen (a
/// wide layout), so no menu button is shown there.
final VoidCallback? onOpenSessions;
/// The soft keyboard's height, from above the shell's Scaffold (which
/// removes the bottom inset from its body).
final double keyboardInset;
const ChatScreen({
super.key,
required this.app,
required this.session,
this.keyboardInset = 0,
this.onOpenSessions,
});
2026-11-18 19:08:06 +08:00
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
/// The chat this page shows. Held rather than read from `app.chat` each
/// time: switching servers clears `app.chat` while this widget is still on
/// screen for one frame, and its timers and dispose must not trip on that.
late final ChatState _chat;
ChatState get chat => _chat;
2026-11-18 19:08:06 +08:00
final TextEditingController _draftCtrl = TextEditingController();
final FocusNode _inputFocus = FocusNode();
2026-11-18 19:08:06 +08:00
final ScrollController _scroll = ScrollController();
bool _stick = true;
List<ComposerAttachment> _attachments = [];
2026-11-18 19:08:06 +08:00
bool _attaching = false;
/// Decoded user attachments, so a rebuild does not base64-decode again.
final Map<String, Uint8List> _userImages = {};
/// `/` palette: the highlighted row, and the draft Esc closed it at.
int _slashIndex = 0;
String? _slashDismissed;
/// Assistant turns show their reasoning/tool parts as a run of steps; the
/// header of each run folds it away (key: message id and start part).
/// These are the runs the person folded or unfolded, overriding the
/// default (finished folded, running open).
final Set<String> _collapsedSteps = {};
final Set<String> _expandedSteps = {};
/// Ticks the activity strip's clock while a turn runs.
Timer? _runClock;
/// Background commands of this session (and its known children): seeded
/// from the transcript, kept alive by the shell list.
ShellTasks? _shells;
2026-11-18 19:08:06 +08:00
@override
void initState() {
super.initState();
_chat = widget.app.chat!;
2026-11-18 19:08:06 +08:00
chat.addListener(_onChat);
_inputFocus.addListener(_onFocusChanged);
if (chat.running) _startClock();
final client = widget.app.client;
if (client != null) {
_shells = ShellTasks(client, sessionId: chat.session.id)
..addListener(_onShells);
_syncShells();
}
// The list is reversed: offset 0 is the newest message (the bottom), and
// older pages grow above without moving what is on screen.
2026-11-18 19:08:06 +08:00
_scroll.addListener(() {
final atBottom = _scroll.position.pixels <= 40;
if (_stick != atBottom) setState(() => _stick = atBottom);
final remaining =
_scroll.position.maxScrollExtent - _scroll.position.pixels;
if (remaining < 240 && chat.hasMore && !chat.loadingOlder) {
_loadOlder();
}
2026-11-18 19:08:06 +08:00
});
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scroll.hasClients) _scroll.jumpTo(0);
2026-11-18 19:08:06 +08:00
});
}
void _onChat() {
if (mounted) setState(() {});
_syncShells();
if (chat.running) {
_startClock();
} else {
_stopClock();
}
2026-11-18 19:08:06 +08:00
if (_stick) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scroll.hasClients) _scroll.jumpTo(0);
2026-11-18 19:08:06 +08:00
});
}
}
void _startClock() {
_runClock ??= Timer.periodic(const Duration(seconds: 1), (_) {
if (mounted && chat.running) setState(() {});
});
}
void _stopClock() {
_runClock?.cancel();
_runClock = null;
}
void _onFocusChanged() {
if (mounted) setState(() {});
}
void _onShells() {
if (mounted) setState(() {});
}
2026-11-18 19:08:06 +08:00
@override
void dispose() {
chat.removeListener(_onChat);
_inputFocus.removeListener(_onFocusChanged);
_stopClock();
_shells?.dispose();
2026-11-18 19:08:06 +08:00
_draftCtrl.dispose();
_inputFocus.dispose();
2026-11-18 19:08:06 +08:00
_scroll.dispose();
super.dispose();
}
/// The session plus every child the session list knows about, so a
/// subagent's background command is listed too.
Set<String> _sessionTree() {
final ids = <String>{chat.session.id};
var grew = true;
while (grew) {
grew = false;
for (final session in widget.app.sessions) {
final parent = session.parentID;
if (parent != null &&
parent.isNotEmpty &&
ids.contains(parent) &&
ids.add(session.id)) {
grew = true;
}
}
}
return ids;
}
/// What the transcript says is detached, handed to the watcher; the shell
/// list then decides which of them are still running.
void _syncShells() {
final shells = _shells;
if (shells == null) return;
shells.seed(backgroundShellsFromMessages(chat.msgs, chat.session.id));
shells.watch(directory: chat.dir, sessionIds: _sessionTree());
}
Future<void> _openShellSheet(ShellTask task,
{ShellCompletionNote? completion}) async {
final client = widget.app.client;
if (client == null) return;
await showShellOutput(
context,
client: client,
task: task,
directory: chat.dir,
onStop: () => _stopShell(task),
finalOutput: completion == null ? null : _completionText(task.id, completion),
done: completion != null,
);
}
/// What a finished command's output reads as: the report, or that the user
/// stopped it (the report itself is a `Shell.NotFoundError` then).
String _completionText(String shellId, ShellCompletionNote completion) =>
shellWasStopped(chat.msgs, shellId) ? tr('You stopped this command.') : completion.output;
Future<void> _stopShell(ShellTask task) async {
final shells = _shells;
if (shells == null) return;
try {
await shells.stop(task, chat.dir);
} on ApiError catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: AppText(trArgs('Could not stop: {0}', [e.message]))));
}
}
/// The task the transcript row is about: the strip's copy when it has one
/// (real start time), otherwise what the part itself says.
ShellTask _shellTaskFor(ContentPart part, String shellId, int startedAt) {
final known = _shells?.task(shellId);
if (known != null) return known;
final input = part.state?.input ?? const <String, dynamic>{};
return ShellTask(
id: shellId,
sessionId: chat.session.id,
command: '${input['command'] ?? ''}'.trim(),
startedAt: startedAt,
);
}
/// A subagent is view-only unless the server allows prompting subagents;
/// a lead's operator worker stays view-only until it is taken over.
bool get _promptReadOnly =>
widget.app.promptReadOnlyFor(widget.session);
Widget _readOnlyBanner(ThemeData theme) {
final scheme = theme.colorScheme;
final openchamber = widget.session.metadata['openchamber'];
final operator =
openchamber is Map && openchamber['kind'] == 'operator-child';
return Container(
width: double.infinity,
padding: EdgeInsets.fromLTRB(
16, 12, 16, 12 + widget.keyboardInset),
decoration: BoxDecoration(
color: scheme.surfaceContainerHighest,
border: Border(
top: BorderSide(color: theme.dividerColor, width: 0.5),
),
),
child: Row(
children: [
Icon(Icons.lock_outline, size: 16, color: theme.hintColor),
const SizedBox(width: 8),
Expanded(
child: AppText(
operator
? 'This session is managed by a Lead; take it over to continue.'
: 'Cannot send prompts to a subagent session.',
style: TextStyle(
fontSize: 12.5, color: scheme.onSurfaceVariant),
),
),
],
),
);
}
/// The session that started this one, when it is a subagent.
Session? get _parentSession {
final parentID = widget.session.parentID;
if (parentID == null || parentID.isEmpty) return null;
for (final session in widget.app.sessions) {
if (session.id == parentID) return session;
}
return null;
}
2026-11-18 19:08:06 +08:00
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final parent = _parentSession;
2026-11-18 19:08:06 +08:00
return Scaffold(
appBar: AppBar(
// A subagent opened from its parent's row goes back there; its own
// sessions menu would lose that way back on a phone.
leading: parent != null
? IconButton(
icon: const Icon(Icons.arrow_back),
tooltip: tr('Back to parent session'),
onPressed: () => widget.app.openChat(parent),
)
: widget.onOpenSessions == null
? null
: IconButton(
icon: const Icon(Icons.menu),
tooltip: tr('Sessions'),
onPressed: widget.onOpenSessions,
),
title: Row(
children: [
if (widget.session.isChild) ...[
Icon(Icons.smart_toy_outlined,
size: 16, color: theme.hintColor),
const SizedBox(width: 6),
],
Expanded(
child: Text(_title(),
maxLines: 1, overflow: TextOverflow.ellipsis),
),
],
),
2026-11-18 19:08:06 +08:00
actions: [
IconButton(
icon: const Icon(Icons.view_sidebar_outlined),
tooltip: tr('Files'),
onPressed: () => showFilesPanel(context, widget.app, chat.dir),
2026-11-18 19:08:06 +08:00
),
],
),
body: Column(
children: [
if (chat.error != null)
Container(
color: theme.colorScheme.errorContainer,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
child: Row(
children: [
Expanded(
child: Text(chat.error!,
2026-11-18 19:08:06 +08:00
style: TextStyle(
color: theme.colorScheme.onErrorContainer, fontSize: 13))),
TextButton(onPressed: chat.load, child: const AppText('Retry')),
2026-11-18 19:08:06 +08:00
],
),
),
Expanded(
child: Stack(
children: [
Positioned.fill(child: _messageList()),
// Over the messages, not in the column: the list keeps its
// full height and shows through around the pet.
Positioned.fill(
child: PetLayer(
state: _petState(),
footOffset: _petFootOffset,
)),
],
),
),
2026-11-18 19:08:06 +08:00
_permissions(),
_forms(),
if (chat.running) _activityStrip(),
if (_shells != null && _shells!.tasks.isNotEmpty) _shellTasksBar(),
if (_promptReadOnly)
_readOnlyBanner(theme)
else
_composer(widget.keyboardInset),
2026-11-18 19:08:06 +08:00
],
),
);
}
// --------------------------------------------------------------- messages
Widget _messageList() {
if (chat.loading && chat.msgs.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
final rows = _rows();
final olderSlot = chat.hasMore || chat.loadingOlder ? 1 : 0;
// Only the conversation itself is selectable: each message bubble, the
// answer text, an opened tool call's details and the turn's model line.
// Status lines and folded tool rows stay plain, so a long-press there does
// not start a selection.
return ListView.builder(
controller: _scroll,
reverse: true,
itemCount: rows.length + olderSlot,
itemBuilder: (context, i) {
// i counts from the newest row up.
if (i < rows.length) return _row(rows[rows.length - 1 - i]);
if (chat.loadingOlder) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 12),
child: Center(
child: SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(strokeWidth: 2)),
),
);
}
return Center(
child: TextButton(
onPressed: _loadOlder,
child: const AppText('Load earlier messages'),
),
);
},
2026-11-18 19:08:06 +08:00
);
}
/// Loads an older page; the reversed list keeps the viewport in place.
Future<void> _loadOlder() async {
if (!chat.hasMore || chat.loadingOlder) return;
await chat.loadOlder();
}
2026-11-18 19:08:06 +08:00
List<_Row> _rows() {
final out = <_Row>[];
for (var mi = 0; mi < chat.msgs.length; mi++) {
final m = chat.msgs[mi];
switch (m.type) {
case 'user':
out.add(_Row('user', m.id, -1));
out.add(_Row('useractions', m.id, -1));
break;
case 'assistant':
// A turn is one or more assistant messages: the server writes a
// message per step, so the whole turn is shown as one run.
var end = mi;
while (end + 1 < chat.msgs.length &&
chat.msgs[end + 1].type == 'assistant') {
end++;
2026-11-18 19:08:06 +08:00
}
_turnRows(out, mi, end);
mi = end;
2026-11-18 19:08:06 +08:00
break;
case 'idle':
// A failed turn also records its error on the idle message. The
// step that failed already prints it, so do not repeat it.
final err = m.error;
if (err != null && !err.isEmpty) {
final prev = mi > 0 ? chat.msgs[mi - 1] : null;
final same = prev?.error;
if (same == null ||
same.message != err.message ||
same.type != err.type) {
out.add(_Row('error', m.id, -1));
}
}
break;
case 'compaction':
if (m.status == 'failed' ||
(m.error != null && !m.error!.isEmpty)) {
out.add(_Row('error', m.id, -1));
} else {
out.add(_Row('compaction', m.id, -1));
}
break;
2026-11-18 19:08:06 +08:00
case 'shell':
out.add(_Row('shell', m.id, -1));
break;
case 'synthetic':
out.add(_Row('note', m.id, -1));
break;
}
}
// Prompts waiting in the inbox stand after the transcript, as dsh-Go's
// pending bubbles do.
for (final item in chat.inbox) {
out.add(_Row('pending', item.id, -1));
}
2026-11-18 19:08:06 +08:00
return out;
}
void _turnRows(List<_Row> out, int from, int to) {
final pending = <_Step>[];
void flush() {
if (pending.isEmpty) return;
final first = pending.first;
// A lone thought needs no foldable header above it.
if (pending.length == 1 && first.part.type == 'reasoning') {
out.add(_Row('step', first.msgId, first.index));
pending.clear();
return;
}
out.add(_Row('steps', first.msgId, first.index));
pending.clear();
}
for (var i = from; i <= to; i++) {
final m = chat.msgs[i];
if (m.content.isEmpty && m.completed == 0) {
flush();
out.add(_Row('thinking', m.id, -1));
continue;
}
for (var p = 0; p < m.content.length; p++) {
final part = m.content[p];
if (part.type == 'tool' && generatedImagePaths(part).isNotEmpty) {
// A generated picture is shown where the call ran, as the
// first-party client draws it, not folded into the run above.
flush();
out.add(_Row('images', m.id, p));
} else if (part.type == 'reasoning' || part.type == 'tool') {
pending.add(_Step(m.id, p, part));
} else if (part.type == 'text') {
flush();
out.add(_Row('text', m.id, p));
}
}
}
flush();
final last = chat.msgs[to];
// Only the step that ended the turn speaks for it: a step that failed and
// was followed by another one is not the turn's outcome.
if (last.error != null && !last.error!.isEmpty) {
out.add(_Row('error', last.id, -1));
}
// A running turn has no "done" strip (nor its copy/fork menu): the
// activity strip above the composer speaks for it instead.
if (last.completed > 0 && _turnEndsAt(to) && !chat.running) {
out.add(_Row('footer', last.id, -1));
}
}
/// A finished run is folded (as in dsh-Go), a running one is open so its
/// steps show while they happen. A tap overrides either default.
bool _groupCollapsed(String id, int start, bool running) {
final k = '$id/$start';
if (_expandedSteps.contains(k)) return false;
if (_collapsedSteps.contains(k)) return true;
return !running;
}
void _toggleGroup(String id, int start, bool collapsed) {
final k = '$id/$start';
setState(() {
if (collapsed) {
_collapsedSteps.remove(k);
_expandedSteps.add(k);
} else {
_expandedSteps.remove(k);
_collapsedSteps.add(k);
}
});
}
/// Whether a step of this run is still going: its own state says so, or the
/// message that carries it has not finished yet.
bool _groupRunning(List<_Step> steps) => steps.any((s) {
final m = chat.byId[s.msgId];
final st = s.part.state?.status ?? '';
return (m != null && m.completed == 0) ||
st == 'running' ||
st == 'streaming' ||
st == 'pending';
});
/// The steps of the run that begins at [msgId]/[index]: consecutive
/// reasoning/tool parts, continuing into the following assistant messages.
List<_Step> _collectGroup(String msgId, int index) {
final out = <_Step>[];
var i = chat.msgs.indexWhere((m) => m.id == msgId);
var p = index;
while (i >= 0 && i < chat.msgs.length) {
final m = chat.msgs[i];
if (p >= m.content.length) {
if (i + 1 < chat.msgs.length &&
chat.msgs[i + 1].type == 'assistant') {
i++;
p = 0;
continue;
}
break;
}
final part = m.content[p];
if (part.type != 'reasoning' && part.type != 'tool') break;
// A generated picture is its own card; the run stops before it.
if (generatedImagePaths(part).isNotEmpty) break;
out.add(_Step(m.id, p, part));
p++;
}
return out;
}
2026-11-18 19:08:06 +08:00
bool _turnEndsAt(int i) {
for (var j = i + 1; j < chat.msgs.length; j++) {
if (chat.msgs[j].type == 'assistant') return false;
if (chat.msgs[j].type == 'user' || chat.msgs[j].type == 'synthetic') return true;
}
return true;
}
Widget _row(_Row r) {
switch (r.kind) {
case 'user':
return _userRow(r.msgId);
case 'useractions':
return _userActions(r.msgId);
case 'pending':
return _pendingBubble(r.msgId);
2026-11-18 19:08:06 +08:00
case 'thinking':
return const Padding(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 6),
child: AppText('Thinking…', style: TextStyle(color: Colors.grey, fontSize: 13)),
2026-11-18 19:08:06 +08:00
);
case 'text':
return _textRow(r.msgId, r.part);
case 'steps':
return _stepsBlock(r.msgId, r.part);
case 'images':
return _imagesRow(r.msgId, r.part);
case 'step':
return _stepRow(r.msgId, r.part);
2026-11-18 19:08:06 +08:00
case 'footer':
return _footerRow(r.msgId);
case 'error':
return _errorRow(r.msgId);
case 'compaction':
return _compactionRow(r.msgId);
2026-11-18 19:08:06 +08:00
case 'shell':
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Text(chat.byId[r.msgId]?.text ?? '',
2026-11-18 19:08:06 +08:00
style: const TextStyle(color: Colors.grey, fontSize: 13)),
);
default:
return const SizedBox.shrink();
}
}
/// The session's title as the list has it: the server names a session from
/// its first message, which arrives after this screen was built.
String _title() {
for (final session in widget.app.sessions) {
if (session.id == widget.session.id && session.title.isNotEmpty) {
return session.title;
}
}
return widget.session.title.isEmpty ? 'Sessions' : widget.session.title;
}
/// A prompt in the server's inbox: dimmer than a sent message, with the
/// label dsh-Go uses and its actions (switch between steering and queueing,
/// or take it back into the composer).
Widget _pendingBubble(String id) {
final item = chat.inbox.where((i) => i.id == id).firstOrNull;
if (item == null) return const SizedBox.shrink();
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final steering = item.delivery == 'steer';
return Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Align(
alignment: Alignment.centerRight,
child: Container(
constraints: const BoxConstraints(maxWidth: 320),
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: scheme.primary.withValues(alpha: 0.55),
borderRadius: BorderRadius.circular(16),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
if (item.text.isNotEmpty)
SelectionArea(
child: Text(item.text,
style: TextStyle(color: scheme.onPrimary)),
),
if (item.files.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: AppText(trArgs('📎 {0} attachments', [item.files.length]),
style: TextStyle(
color: scheme.onPrimary, fontSize: 12.5)),
),
],
),
),
),
Padding(
padding: const EdgeInsets.only(right: 6),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(steering ? Icons.alt_route : Icons.schedule,
size: 13, color: theme.hintColor),
const SizedBox(width: 3),
AppText(
!chat.running
? 'Not sent'
: steering
? 'Joining this turn…'
: 'Queued; sends after this turn',
style: TextStyle(fontSize: 12, color: theme.hintColor),
),
const SizedBox(width: 4),
TextButton(
onPressed: () => chat.changeInboxDelivery(
item.id, steering ? 'queue' : 'steer'),
child: AppText(steering ? 'Queue instead' : 'Steer instead',
style: const TextStyle(fontSize: 12.5)),
),
TextButton(
onPressed: () async {
final ok = await chat.withdrawInbox(item.id);
if (!ok || !mounted) return;
_draftCtrl.text = chat.draft;
_draftCtrl.selection = TextSelection.collapsed(
offset: _draftCtrl.text.length);
_inputFocus.requestFocus();
},
child: const AppText('Withdraw',
style: TextStyle(fontSize: 12.5)),
),
],
),
),
],
);
}
2026-11-18 19:08:06 +08:00
Widget _userRow(String id) {
final m = chat.byId[id]!;
final theme = Theme.of(context);
// The server keeps attached images in the message; the paths only cover
// the moment between sending and the next refresh.
final attachedImages = [
for (var i = 0; i < m.files.length; i++)
if (m.files[i].isImage) i,
];
final localImages = attachedImages.isEmpty ? chat.imagePaths[id] ?? [] : const <String>[];
final attachmentSlides = [
for (final i in attachedImages)
ImageSlide(
m.files[i].name.isEmpty ? tr('Image') : m.files[i].name,
'data:${m.files[i].mime};base64,${m.files[i].data}'),
];
final localSlides = [
for (final path in localImages) ImageSlide(path.split('/').last, path),
];
final otherFiles = m.files.where((f) => !f.isImage).toList();
2026-11-18 19:08:06 +08:00
return Align(
alignment: Alignment.centerRight,
child: Container(
constraints: const BoxConstraints(maxWidth: 320),
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: theme.colorScheme.primary,
borderRadius: BorderRadius.circular(16),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
if (m.text.isNotEmpty)
SelectionArea(
child: Text(m.text,
style: TextStyle(color: theme.colorScheme.onPrimary)),
),
for (var pos = 0; pos < attachedImages.length; pos++)
2026-11-18 19:08:06 +08:00
Padding(
padding: const EdgeInsets.only(top: 6),
child: GestureDetector(
onTap: () => _showImages(attachmentSlides, pos),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: _attachmentImage(id, attachedImages[pos], m.files[attachedImages[pos]]),
),
2026-11-18 19:08:06 +08:00
),
),
for (var pos = 0; pos < localImages.length; pos++)
2026-11-18 19:08:06 +08:00
Padding(
padding: const EdgeInsets.only(top: 4),
child: GestureDetector(
onTap: () => _showImages(localSlides, pos),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.file(File(localImages[pos]),
width: 200, height: 150, fit: BoxFit.cover),
),
),
),
for (final f in otherFiles)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: theme.colorScheme.onPrimary.withValues(alpha: 0.14),
borderRadius: BorderRadius.circular(8),
),
child: AppText('📎 ${f.name.isEmpty ? tr('Attachments') : f.name}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: theme.colorScheme.onPrimary, fontSize: 12.5)),
2026-11-18 19:08:06 +08:00
),
),
],
),
),
);
}
Widget _attachmentImage(String messageId, int index, FileAttachment f) {
final key = '$messageId/$index';
Uint8List? bytes = _userImages[key];
if (bytes == null) {
try {
bytes = base64Decode(f.data);
_userImages[key] = bytes;
} catch (_) {
return const SizedBox(
width: 200, height: 60, child: Center(child: AppText('Cannot display image')));
}
}
return Image.memory(bytes, width: 200, height: 150, fit: BoxFit.cover);
}
2026-11-18 19:08:06 +08:00
Widget _userActions(String id) {
final m = chat.byId[id]!;
final stamp = m.created > 0
? '${DateTime.fromMillisecondsSinceEpoch(m.created).hour.toString().padLeft(2, '0')}:'
'${DateTime.fromMillisecondsSinceEpoch(m.created).minute.toString().padLeft(2, '0')}'
: '';
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
if (stamp.isNotEmpty)
Padding(
padding: const EdgeInsets.only(right: 8),
child: Text(stamp, style: const TextStyle(color: Colors.grey, fontSize: 12)),
2026-11-18 19:08:06 +08:00
),
TextButton(
onPressed: () => _copyText(m.text),
child: const AppText('Copy'),
2026-11-18 19:08:06 +08:00
),
PopupMenuButton<String>(
onSelected: (v) => _userAction(v, m),
itemBuilder: (_) => const [
PopupMenuItem(value: 'copy', child: AppText('Copy message')),
PopupMenuItem(value: 'revert', child: AppText('Withdraw this and later messages')),
PopupMenuItem(value: 'fork', child: AppText('Fork from here')),
2026-11-18 19:08:06 +08:00
],
),
],
);
}
void _userAction(String v, Message m) {
switch (v) {
case 'copy':
_copyText(m.text);
break;
case 'revert':
_confirm(
title: 'Withdraw message?',
message: 'This message and everything after it will be removed from the session and cannot be recovered.',
confirm: 'Withdraw',
2026-11-18 19:08:06 +08:00
onConfirm: () => chat.revert(m.id),
);
break;
case 'fork':
chat.fork(before: m.id);
break;
}
}
Widget _textRow(String id, int part) {
final m = chat.byId[id]!;
if (part < 0 || part >= m.content.length) return const SizedBox.shrink();
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
child: SelectionArea(child: MarkdownView(m.content[part].text)),
);
}
/// A run of steps: the header, then its rows revealed with an animation.
/// Revealing grows the list below the header, so [_Reveal] reports the
/// height it just added and the list scrolls by it, keeping the header
/// under the finger instead of throwing it off screen.
Widget _stepsBlock(String id, int start) {
final steps = _collectGroup(id, start);
final running = _groupRunning(steps);
final failed = steps.any((s) => s.part.state?.status == 'error');
final collapsed = _groupCollapsed(id, start, running);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_stepsHeader(id, start, steps, collapsed, running, failed),
_Reveal(
open: !collapsed,
onGrow: _grow,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (final step in steps) _stepRow(step.msgId, step.index),
],
),
),
],
);
}
/// A picture a tool generated, drawn in the conversation where the call
/// ran. The first-party client hoists `image.generate` results this way
/// (ShownToolCard → GeneratedImages) instead of folding them with Activity.
Widget _imagesRow(String id, int part) {
final m = chat.byId[id]!;
if (part < 0 || part >= m.content.length) return const SizedBox.shrink();
final paths = generatedImagePaths(m.content[part]);
if (paths.isEmpty) return const SizedBox.shrink();
final slides = [for (final path in paths) ImageSlide(pathLeaf(path), path)];
return Padding(
padding: const EdgeInsets.fromLTRB(16, 6, 16, 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (var i = 0; i < paths.length; i++)
Padding(
padding: EdgeInsets.only(bottom: i == paths.length - 1 ? 0 : 8),
child: _GeneratedImage(
source: paths[i],
directory: chat.dir,
client: widget.app.client!,
onTap: () => _showImages(slides, i),
),
),
],
),
);
}
/// Keeps the list under a growing run: the reversed list would otherwise
/// push the header up by exactly the height that was just revealed.
void _grow(double delta) { if (!mounted || !_scroll.hasClients || delta.abs() < 0.01) return;
final p = _scroll.position;
final target = (p.pixels + delta).clamp(p.minScrollExtent, p.maxScrollExtent);
if ((target - p.pixels).abs() > 0.01) _scroll.jumpTo(target);
}
/// "已完成 · 3 次工具调用", with a chevron that folds the whole run.
Widget _stepsHeader(String id, int start, List<_Step> steps, bool collapsed,
bool running, bool failed) {
final theme = Theme.of(context);
final tools = steps.where((s) => s.part.type == 'tool').length;
final label = tools == 0
? (running ? 'Thinking…' : 'Thought process')
: failed
? trArgs('A step failed · {0} tool calls', [tools])
: running
? trArgs('Running · {0} tool calls', [tools])
: trArgs('Done · {0} tool calls', [tools]);
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => _toggleGroup(id, start, collapsed),
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 12, 2),
child: Row(
children: [
if (running)
const SizedBox(
width: 15,
height: 15,
child: CircularProgressIndicator(strokeWidth: 1.6))
else
Icon(failed ? Icons.error_outline : Icons.check_circle_outline,
size: 16,
color: failed ? theme.colorScheme.error : theme.hintColor),
const SizedBox(width: 8),
Expanded(
child: Text(label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 13, color: theme.hintColor)),
),
AnimatedRotation(
turns: collapsed ? 0 : 0.5,
duration: const Duration(milliseconds: 180),
child: Icon(Icons.expand_more, size: 18, color: theme.hintColor),
),
],
2026-11-18 19:08:06 +08:00
),
),
2026-11-18 19:08:06 +08:00
);
}
/// One step: a rounded icon, a label, the one-line summary, and details
/// when opened.
Widget _stepRow(String id, int part) {
2026-11-18 19:08:06 +08:00
final m = chat.byId[id]!;
if (part < 0 || part >= m.content.length) return const SizedBox.shrink();
final p = m.content[part];
final theme = Theme.of(context);
final reasoning = p.type == 'reasoning';
2026-11-18 19:08:06 +08:00
final status = p.state?.status ?? '';
final busy = status == 'running' || status == 'streaming' || status == 'pending';
final key = 'step/$id/$part';
final open = chat.expanded.contains(key);
final label = _stepLabel(p);
final summary = _stepSummary(p);
// A read of an image is a link to the picture, not a fold.
final image = _imageArg(p);
final refs = reasoning || image != null
? const <_ImageRef>[]
: toolImages(p, chat.dir);
final subagentId = _subagentSessionId(p);
final shellId = reasoning ? null : backgroundShellId(p);
final diffFiles = reasoning ? const <DiffFile>[] : toolDiffFiles(p);
var diffAdded = 0;
var diffRemoved = 0;
for (final file in diffFiles) {
diffAdded += file.added;
diffRemoved += file.removed;
}
return Container(
margin: const EdgeInsets.only(left: 22),
decoration: BoxDecoration(
border: Border(left: BorderSide(color: theme.dividerColor, width: 1)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InkWell(
onTap: subagentId != null
? () => _openSubagent(subagentId)
: image != null
? () =>
_openPreview(_ImageRef(image, summary.split('/').last))
: () {
setState(() {
open
? chat.expanded.remove(key)
: chat.expanded.add(key);
});
if (!open && !reasoning) chat.ensureToolLoaded(id);
},
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 3, 10, 3),
2026-11-18 19:08:06 +08:00
child: Row(
children: [
Container(
width: 26,
height: 26,
decoration: BoxDecoration(
color: status == 'error'
? theme.colorScheme.errorContainer
: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(7),
),
child: busy
? const Padding(
padding: EdgeInsets.all(6),
child: CircularProgressIndicator(strokeWidth: 1.6),
)
: Icon(_stepIcon(p),
size: 15,
color: status == 'error'
? theme.colorScheme.onErrorContainer
: theme.colorScheme.onSurfaceVariant),
2026-11-18 19:08:06 +08:00
),
const SizedBox(width: 10),
Text(label,
style: TextStyle(
fontSize: 13.5, color: theme.colorScheme.onSurface)),
if (summary.isEmpty)
const Spacer()
else ...[
const SizedBox(width: 6),
AppText('·', style: TextStyle(fontSize: 13, color: theme.hintColor)),
const SizedBox(width: 6),
Expanded(
child: Text(summary,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
color: image != null
? theme.colorScheme.primary
: theme.hintColor)),
),
],
if (diffFiles.isNotEmpty &&
!busy &&
status != 'error' &&
diffAdded + diffRemoved > 0)
Padding(
padding: const EdgeInsets.only(left: 6, right: 2),
child: DiffStats(added: diffAdded, removed: diffRemoved),
),
if (shellId != null)
Padding(
padding: const EdgeInsets.only(left: 6),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 6, vertical: 1),
decoration: BoxDecoration(
color: theme.colorScheme.primary
.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(6),
),
child: AppText('Background',
style: TextStyle(
fontSize: 11,
color: theme.colorScheme.primary)),
),
),
if (subagentId != null)
Icon(Icons.chevron_right,
size: 18, color: theme.hintColor)
else if (image != null)
Icon(Icons.open_in_full,
size: 14, color: theme.colorScheme.primary)
else
Icon(open ? Icons.expand_less : Icons.expand_more,
size: 16, color: theme.hintColor),
2026-11-18 19:08:06 +08:00
],
),
),
),
for (var i = 0; i < refs.length; i++)
Padding(
padding: const EdgeInsets.fromLTRB(10, 0, 10, 2),
child: InkWell(
onTap: () => _showImages(
[for (final ref in refs) ImageSlide(ref.label, ref.source)],
i),
child: Row(
children: [
const AppText('🖼', style: TextStyle(fontSize: 12)),
const SizedBox(width: 6),
Flexible(
child: Text(refs[i].label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12, color: theme.colorScheme.primary)),
),
],
),
2026-11-18 19:08:06 +08:00
),
),
if (image == null)
_Reveal(
open: open,
onGrow: _grow,
// An opened call shows its command, arguments and output; those
// are conversation text like the answer is.
child: SelectionArea(
child:
_stepDetails(p, reasoning, diffFiles, shellId, m.created),
),
),
],
),
2026-11-18 19:08:06 +08:00
);
}
static const _imageExts = {
'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'avif',
};
/// The child session a subagent tool call started: the server puts it in the
/// tool metadata, and older results carry `sessionID: ses_…` in the text.
static String? _subagentSessionId(ContentPart p) {
if (p.type != 'tool') return null;
if (p.name != 'subagent' && p.name != 'task') return null;
final meta = p.state?.metadata;
if (meta != null) {
for (final key in const [
'sessionID',
'sessionId',
'childSessionID',
'childSessionId',
]) {
final value = meta[key];
if (value is String && value.isNotEmpty) return value;
}
}
final pattern =
RegExp(r'(?:sessionID|sessionId)["\s:=]+(ses_[A-Za-z0-9]+)');
final texts = <String>[
for (final part in p.state?.content ?? const <ContentPart>[]) part.text,
if (p.state?.error != null) p.state!.error!,
];
for (final text in texts) {
final match = pattern.firstMatch(text);
if (match != null) return match.group(1);
}
return null;
}
Future<void> _openSubagent(String id) async {
final ok = await widget.app.openSubagent(id);
if (ok || !mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: AppText(widget.app.lastError ?? 'Cannot open the subagent session')),
);
widget.app.clearLastError();
}
/// The file a read/write/edit step points at, when it is an image.
String? _imageArg(ContentPart p) {
if (p.type != 'tool') return null;
// A failed read has no picture to show; it stays a normal, foldable step.
if (p.state?.status == 'error') return null;
final name = p.name ?? '';
if (name != 'read' && name != 'write' && name != 'edit') return null;
final input = p.state?.input ?? const <String, dynamic>{};
final v = input['filePath'] ?? input['path'] ?? input['file'];
if (v is! String || v.isEmpty) return null;
final ext = v.contains('.') ? v.split('.').last.toLowerCase() : '';
if (!_imageExts.contains(ext)) return null;
if (v.startsWith('/') || chat.dir.isEmpty) return v;
return '${chat.dir}/$v';
}
/// The input field already shown by the row's summary.
static String? _primaryInput(ContentPart p) {
switch (p.name ?? '') {
case 'bash':
case 'shell':
case 'execute':
return 'command';
case 'read':
case 'write':
case 'edit':
return 'filePath';
case 'grep':
case 'glob':
case 'find':
return 'pattern';
case 'webfetch':
case 'web_fetch':
return 'url';
case 'task':
case 'subagent':
return 'description';
case 'skill':
return 'id';
default:
return null;
}
}
static bool _isShell(ContentPart p) =>
const {'bash', 'shell', 'execute'}.contains(p.name ?? '');
/// What the step actually did: the command or path, the rest of the input,
/// and the result — never the request JSON as a blob.
Widget _stepDetails(ContentPart p, bool reasoning, List<DiffFile> diffFiles,
String? shellId, int startedAt) {
final theme = Theme.of(context);
if (shellId != null) {
final task = _shellTaskFor(p, shellId, startedAt);
final completion = shellCompletionFor(chat.msgs, shellId);
return Padding(
padding: const EdgeInsets.fromLTRB(10, 4, 10, 8),
child: ShellOutputInline(
client: widget.app.client!,
task: task,
directory: chat.dir,
finalOutput: completion == null
? null
: _completionText(shellId, completion),
done: completion != null,
onOpen: () => _openShellSheet(task, completion: completion),
onStop: () => _stopShell(task),
),
);
}
if (diffFiles.isNotEmpty) return _diffDetails(p, diffFiles);
if (reasoning) {
if (p.text.isEmpty) return const SizedBox.shrink();
// The model writes Markdown here too; render it as such, a touch
// smaller and quieter than the answer.
return Padding(
padding: const EdgeInsets.fromLTRB(10, 2, 10, 8),
child: MarkdownView(p.text, fontSize: 12.5, color: theme.hintColor),
);
}
final input = p.state?.input ?? const <String, dynamic>{};
final primary = _primaryInput(p);
final extras = <MapEntry<String, String>>[
for (final e in input.entries)
if (e.key != primary && '${e.value}'.trim().isNotEmpty)
MapEntry(e.key, '${e.value}'),
];
final shell = _isShell(p);
final command = shell ? '${input['command'] ?? ''}'.trim() : '';
final output = toolOutput(p);
// A big output arrives as an empty shell until the message is fetched;
// that is not the same as a command that printed nothing.
final shelled = shell &&
(p.state?.metadata?.containsKey('openchamberContentShell') ?? false);
const mono = TextStyle(fontSize: 12, height: 1.45, fontFamily: 'monospace');
return Padding(
padding: const EdgeInsets.fromLTRB(10, 2, 10, 8),
child: Container(
width: double.infinity,
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (command.isNotEmpty)
Text(command,
style: mono.copyWith(color: theme.colorScheme.onSurface)),
if (command.isNotEmpty) const SizedBox(height: 6),
for (final e in extras)
Padding(
padding: const EdgeInsets.only(bottom: 2),
child: Text('${e.key}: ${e.value}',
style: mono.copyWith(
fontSize: 11.5, color: theme.hintColor)),
),
if (extras.isNotEmpty) const SizedBox(height: 4),
Text(
output.isNotEmpty
? output
: shelled
? tr('Large output, loading…')
: (shell ? tr('No output') : tr('No content')),
style: mono.copyWith(
color: p.state?.error != null
? theme.colorScheme.error
: theme.colorScheme.onSurfaceVariant,
),
),
],
),
),
);
}
/// An edit/write/patch opened: the before/after as tinted diff lines, with
/// the tool's own result in one quiet line under it.
Widget _diffDetails(ContentPart p, List<DiffFile> diffFiles) {
final theme = Theme.of(context);
final output = toolOutput(p).trim();
return Padding(
padding: const EdgeInsets.fromLTRB(10, 2, 10, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
DiffView(files: [
// The row already names the file; a path inside the session's
// directory drops the prefix so it fits a phone.
for (final file in diffFiles)
DiffFile(
path: file.path == null
? null
: relativePath(file.path!, chat.dir),
lines: file.lines,
),
]),
if (output.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 6),
child: AppText(
output,
maxLines: 4,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11.5,
color: p.state?.error != null
? theme.colorScheme.error
: theme.hintColor,
),
),
),
],
),
);
}
static IconData _stepIcon(ContentPart p) {
if (p.type == 'reasoning') return Icons.psychology_outlined;
switch (p.name ?? '') {
case 'bash':
case 'shell':
case 'execute':
return Icons.terminal;
case 'read':
return Icons.description_outlined;
case 'write':
return Icons.note_add_outlined;
case 'edit':
return Icons.edit_outlined;
case 'openchamber_image':
return Icons.image_outlined;
case 'patch':
case 'apply_patch':
return Icons.difference_outlined;
case 'grep':
return Icons.search;
case 'glob':
case 'find':
return Icons.travel_explore;
case 'list':
return Icons.format_list_bulleted;
case 'webfetch':
case 'web_fetch':
return Icons.language;
case 'todowrite':
return Icons.checklist_rtl;
case 'task':
case 'subagent':
return Icons.smart_toy_outlined;
case 'skill':
return Icons.extension_outlined;
default:
return Icons.handyman_outlined;
}
}
static String _stepLabel(ContentPart p) {
if (p.type == 'reasoning') return tr('Thinking');
switch (p.name ?? '') {
case 'bash':
case 'shell':
case 'execute':
return tr('Run');
case 'read':
return tr('Read');
case 'write':
return tr('Write');
case 'edit':
return tr('Edit');
case 'patch':
case 'apply_patch':
return tr('Patch');
case 'grep':
case 'glob':
case 'find':
return tr('Search');
case 'list':
return tr('List');
case 'webfetch':
case 'web_fetch':
return tr('Fetch');
case 'todowrite':
return tr('Task');
case 'task':
case 'subagent':
return tr('Subagent');
case 'skill':
return tr('Skill');
case 'openchamber_image':
return tr('Generate image');
default:
return p.name == null || p.name!.isEmpty ? tr('Tool') : p.name!;
}
}
/// One line that says what the step is about, so a folded run stays useful.
String _stepSummary(ContentPart p) {
if (p.type == 'reasoning') return _firstLine(p.text);
final input = p.state?.input ?? const <String, dynamic>{};
String one(Object? v) =>
(v ?? '').toString().replaceAll(RegExp(r'\s+'), ' ').trim();
switch (p.name ?? '') {
case 'bash':
case 'shell':
case 'execute':
return one(input['command']);
case 'read':
case 'write':
case 'edit':
return relativePath(
one(input['filePath'] ?? input['path'] ?? input['file']), chat.dir);
case 'grep':
case 'glob':
case 'find':
return one(input['pattern']);
case 'webfetch':
case 'web_fetch':
return one(input['url']);
case 'task':
case 'subagent':
return one(input['description'] ?? input['prompt']);
case 'skill':
return one(input['id'] ?? input['name']);
default:
for (final k in const [
'description', 'filePath', 'path', 'command', 'query', 'url',
'pattern', 'name', 'id',
]) {
var v = one(input[k]);
if (v.isEmpty) continue;
if (k == 'filePath' || k == 'path') v = relativePath(v, chat.dir);
return v;
}
if (input.isEmpty) return '';
return one(const JsonEncoder().convert(input));
}
}
static String _firstLine(String text) {
for (final line in const LineSplitter().convert(text)) {
final t = line.replaceAll(RegExp(r'^[\s#>*\-]+'), '').trim();
if (t.isNotEmpty) return t;
}
return '';
}
2026-11-18 19:08:06 +08:00
Widget _footerRow(String id) {
final m = chat.byId[id]!;
final parts = <String>[];
if (m.model != null) parts.add(widget.app.modelName(m.model));
if (m.agent.isNotEmpty) parts.add(m.agent);
if (m.completed > 0) parts.add(_turnDuration(m));
return Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: SelectionArea(
child: Text(parts.join(' · '),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(color: Colors.grey, fontSize: 13)),
),
2026-11-18 19:08:06 +08:00
),
),
PopupMenuButton<String>(
onSelected: (v) => _footerAction(v, m),
itemBuilder: (_) => const [
PopupMenuItem(value: 'copy', child: AppText('Copy answer')),
PopupMenuItem(value: 'fork', child: AppText('Fork from here')),
2026-11-18 19:08:06 +08:00
],
),
],
);
}
/// Whether an error detail looks like an authentication failure (the same
/// reading the official client does, so the sentence matches).
static bool _isAuthError(String detail) {
final d = detail.toLowerCase().trim();
if (d.isEmpty) return false;
if (d.contains('token refresh failed') ||
d.contains('unauthorized') ||
d.contains('invalid token') ||
d.contains('expired token')) {
return true;
}
if (d.contains('oauth') &&
(d.contains('failed') || d.contains('invalid') || d.contains('expired'))) {
return true;
}
final has401 = RegExp(r'\b401\b').hasMatch(d);
return has401 &&
(d.contains('auth') || d.contains('token') || d.contains('unauthorized'));
}
/// What a failed step says in the transcript, close to the official
/// client's wording; the provider's raw response is kept for details.
static ({String text, String? body}) _errorNotice(Message m) {
final e = m.error;
final detail = (e != null && e.message.isNotEmpty)
? e.message
: (e != null && e.type.isNotEmpty ? e.type : tr('Unknown error'));
final type = (e?.type ?? '').toLowerCase();
final plain = detail.trim().toLowerCase().replaceFirst(RegExp(r'\.$'), '');
if (m.type == 'compaction') {
return (text: trArgs('Compaction failed: {0}', [detail]), body: e?.body);
}
if (type == 'sessionretry') {
return (text: trArgs('OpenCode could not send the message; retrying: {0}', [detail]), body: e?.body);
}
if (_isAuthError(detail)) {
return (
text: tr('The model failed to authenticate. Sign in again on the server or check the API key.'),
body: e?.body
);
}
if (type == 'messageabortederror' ||
plain == 'aborted' ||
plain == 'step interrupted') {
return (text: tr('This turn was stopped.'), body: null);
}
return (text: trArgs('OpenCode could not send the message: {0}', [detail]), body: e?.body);
}
static String _prettyBody(String raw) {
try {
return const JsonEncoder.withIndent(' ').convert(jsonDecode(raw));
} catch (_) {
return raw;
}
}
/// A compaction in the timeline: one line ("对话已压缩") that opens into the
/// summary the model wrote to replace the older history.
Widget _compactionRow(String id) {
final m = chat.byId[id];
if (m == null) return const SizedBox.shrink();
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final running = m.status == 'running';
final summary = m.summary.trim();
final open = chat.expanded.contains('compaction/$id');
final label = running ? 'Compacting conversation' : 'Conversation compacted';
final header = GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => setState(() {
final k = 'compaction/$id';
open ? chat.expanded.remove(k) : chat.expanded.add(k);
}),
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 8, 12, 2),
child: Row(
children: [
if (running)
const SizedBox(
width: 15,
height: 15,
child: CircularProgressIndicator(strokeWidth: 1.6))
else
Icon(Icons.content_cut, size: 16, color: theme.hintColor),
const SizedBox(width: 8),
Expanded(
child: AppText(label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 13, color: theme.hintColor)),
),
if (summary.isNotEmpty)
AppText(open ? 'Hide summary' : 'Show summary',
style: TextStyle(fontSize: 12, color: scheme.primary)),
const SizedBox(width: 4),
AnimatedRotation(
turns: open ? 0.5 : 0,
duration: const Duration(milliseconds: 180),
child: Icon(Icons.expand_more, size: 18, color: theme.hintColor),
),
],
),
),
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
header,
_Reveal(
open: open,
onGrow: _grow,
child: Container(
margin: const EdgeInsets.fromLTRB(22, 2, 16, 8),
padding: const EdgeInsets.fromLTRB(10, 8, 10, 8),
decoration: BoxDecoration(
color: scheme.surfaceContainerHighest.withValues(alpha: 0.5),
border: Border(
left: BorderSide(color: theme.dividerColor, width: 1)),
borderRadius: BorderRadius.circular(8),
),
child: summary.isEmpty
? AppText(running ? 'Generating summary…' : '(No summary)',
style: TextStyle(fontSize: 13, color: theme.hintColor))
: MarkdownView(summary, fontSize: 14),
),
),
],
);
}
/// A failed turn's error, as a quiet block under its last step: what went
/// wrong, and the provider's response behind a "详情" toggle.
Widget _errorRow(String id) {
final m = chat.byId[id];
if (m == null) return const SizedBox.shrink();
final notice = _errorNotice(m);
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final key = 'error/$id';
final open = chat.expanded.contains(key);
final raw = notice.body?.trim() ?? '';
final body = raw.isEmpty ? null : _prettyBody(raw);
return Padding(
padding: const EdgeInsets.fromLTRB(16, 6, 16, 4),
child: Container(
padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),
decoration: BoxDecoration(
color: scheme.error.withValues(alpha: 0.08),
border: Border.all(color: scheme.error.withValues(alpha: 0.28)),
borderRadius: BorderRadius.circular(14),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.error_outline, size: 18, color: scheme.error),
const SizedBox(width: 8),
Expanded(
child: SelectableText(notice.text,
style: const TextStyle(fontSize: 13.5, height: 1.45)),
),
],
),
if (body != null) ...[
Padding(
padding: const EdgeInsets.only(left: 26),
child: TextButton(
style: TextButton.styleFrom(
padding: EdgeInsets.zero,
minimumSize: const Size(0, 30),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
alignment: Alignment.centerLeft,
foregroundColor: scheme.onSurfaceVariant,
),
onPressed: () => setState(() {
open ? chat.expanded.remove(key) : chat.expanded.add(key);
}),
child: AppText(open ? 'Hide details' : 'Show details',
style: const TextStyle(fontSize: 12.5)),
),
),
if (open)
Container(
width: double.infinity,
margin: const EdgeInsets.only(left: 26, top: 4),
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: scheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
child: SelectableText(body,
style: const TextStyle(
fontSize: 11.5, height: 1.45, fontFamily: 'monospace')),
),
],
],
),
),
);
}
/// Where the pet's feet rest: on the composer's capsule, or on the status
/// capsule when one is the last thing above the composer. That strip keeps
/// a 4px top margin of its own, so the feet stop on its edge instead of
/// sinking into it.
double get _petFootOffset {
final strip = chat.running || (_shells?.tasks.isNotEmpty ?? false);
return strip ? 4 : 6;
}
/// The mood the pet draws: the same activity the strip shows, then a failed
/// last turn, then idle.
String _petState() {
if (chat.running) {
return _activity().title == 'Thinking' ? 'thinking' : 'working';
}
for (var i = chat.msgs.length - 1; i >= 0; i--) {
final m = chat.msgs[i];
if (m.type == 'assistant' || m.type == 'idle') {
return m.error != null && !m.error!.isEmpty ? 'error' : 'idle';
}
}
return 'idle';
}
/// What the agent is doing right now, for the strip above the composer.
({String title, String detail}) _activity() {
for (var i = chat.msgs.length - 1; i >= 0; i--) {
final m = chat.msgs[i];
if (m.type != 'assistant') continue;
for (var p = m.content.length - 1; p >= 0; p--) {
final part = m.content[p];
final st = part.state?.status ?? '';
if (part.type == 'tool' &&
(st == 'running' || st == 'streaming' || st == 'pending')) {
return (title: trArgs('{0} in progress', [_stepLabel(part)]), detail: _stepSummary(part));
}
}
if (m.completed == 0) {
// No tool running yet: say which part of the reply is being written.
final text =
m.content.any((p) => p.type == 'text' && p.text.trim().isNotEmpty);
final reasoning = m.content
.any((p) => p.type == 'reasoning' && p.text.trim().isNotEmpty);
if (text) return (title: 'Replying', detail: '');
if (reasoning) return (title: 'Thinking', detail: '');
}
break;
}
return (title: 'Thinking', detail: '');
}
/// The running turn started with the newest user message.
int _runningStart() {
for (var i = chat.msgs.length - 1; i >= 0; i--) {
if (chat.msgs[i].type == 'user') return chat.msgs[i].created;
}
return 0;
}
String _elapsedSince(int start) {
if (start <= 0) return '';
final secs =
((DateTime.now().millisecondsSinceEpoch - start) / 1000).round();
if (secs <= 0) return '0:00';
return '${secs ~/ 60}:${(secs % 60).toString().padLeft(2, '0')}';
}
/// The background commands of this session, above the composer: what is
/// running, for how long, and the way into its output.
Widget _shellTasksBar() {
final tasks = _shells?.tasks ?? const <ShellTask>[];
return ShellTaskBar(
tasks: tasks,
sessionId: chat.session.id,
onOpen: _openShellSheet,
);
}
/// dsh-Go's activity cap: a stadium above the input with the current step
/// on the left and its clock on the right. Its top edge is where the
/// input-box pet will later perch.
Widget _activityStrip() {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final act = _activity();
final elapsed = _elapsedSince(_runningStart());
return Padding(
// The same 8px side margin as the composer, so the two capsules agree.
padding: const EdgeInsets.fromLTRB(8, 4, 8, 4),
child: Container(
constraints: const BoxConstraints(minHeight: 36),
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
decoration: ShapeDecoration(
color: scheme.surfaceContainerHighest.withValues(alpha: 0.7),
shape: const StadiumBorder(),
),
child: Row(
children: [
Expanded(
child: Row(
children: [
AppText(
act.title,
style: theme.textTheme.labelMedium?.copyWith(
fontSize: 13,
fontWeight: FontWeight.w600,
color: scheme.onSurface,
),
),
if (act.detail.isNotEmpty) ...[
const SizedBox(width: 6),
Flexible(
child: AppText(
act.detail,
maxLines: 1,
softWrap: false,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodySmall?.copyWith(
fontSize: 12,
color: scheme.onSurfaceVariant,
),
),
),
],
],
),
),
if (elapsed.isNotEmpty) ...[
const SizedBox(width: 8),
AppText(
elapsed,
style: TextStyle(
fontSize: 12,
color: theme.hintColor,
fontFeatures: const [FontFeature.tabularFigures()],
),
),
],
],
),
),
);
}
2026-11-18 19:08:06 +08:00
String _turnDuration(Message m) {
var start = 0;
final idx = chat.msgs.indexWhere((x) => x.id == m.id);
for (var i = idx - 1; i >= 0; i--) {
if (chat.msgs[i].type == 'user') {
start = chat.msgs[i].created;
break;
}
}
if (start <= 0) return '';
final secs = ((m.completed - start) / 1000).round();
if (secs <= 0) return '';
if (secs < 60) return trArgs('{0}s', [secs]);
2026-11-18 19:08:06 +08:00
return '${secs ~/ 60}:${(secs % 60).toString().padLeft(2, '0')}';
}
void _footerAction(String v, Message m) {
switch (v) {
case 'copy':
_copyText(m.partText);
break;
case 'fork':
chat.fork();
break;
}
}
Future<void> _copyText(String text) async {
if (text.trim().isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: AppText('Nothing to copy')));
2026-11-18 19:08:06 +08:00
return;
}
await Clipboard.setData(ClipboardData(text: text));
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: AppText('Copied')));
2026-11-18 19:08:06 +08:00
}
}
// ------------------------------------------------------------ composer
2026-11-18 20:48:12 +08:00
// The composer follows dsh-Go's input bar: a rounded capsule holding a
// leading key, an auto-growing borderless field, the usage ring and a
// trailing send/stop key, all 36px round keys (MIT, app/lib/ui/chat/
// composer.dart, referenced rather than copied).
/// Chinese faces for the first-party commands, as dsh-Go shows them; the
/// registry's name is what is sent.
/// Rows for the current draft, or null when the palette is closed. It
/// stays up while the command name is being typed and closes once an
/// argument has started.
List<SlashItem>? _slashMatches() => matchSlashItems(
items: chat.slashItems,
text: _draftCtrl.text,
dismissed: _slashDismissed,
);
void _moveSlash(List<SlashItem> items, int delta) {
if (items.isEmpty) return;
setState(() {
_slashIndex = (_slashIndex + delta).clamp(0, items.length - 1);
});
}
void _dismissSlash() {
setState(() => _slashDismissed = _draftCtrl.text);
}
/// A row was picked. Commands that take no argument run right away (as in
/// dsh-Go); the rest complete the name and wait for the arguments.
void _pickSlash(SlashItem item) {
HapticFeedback.selectionClick();
final text = _draftCtrl.text;
final lead = text.length - text.trimLeft().length;
final rest = text.trimLeft();
final match = RegExp(r'\s').firstMatch(rest);
final suffix = match == null ? '' : rest.substring(match.start);
final completes = item.skill || item.takesArgs;
if (!completes) {
final command = '/${item.name}';
_draftCtrl.value = TextEditingValue(
text: command,
selection: TextSelection.collapsed(offset: command.length),
);
chat.draft = command;
setState(() {});
_send();
return;
}
final prefix = '${text.substring(0, lead)}/${item.name}';
final separator =
suffix.isEmpty || !RegExp(r'^\s').hasMatch(suffix) ? ' ' : '';
final next = '$prefix$separator$suffix';
_draftCtrl.value = TextEditingValue(
text: next,
selection: TextSelection.collapsed(offset: prefix.length + 1),
);
chat.draft = next;
_inputFocus.requestFocus();
setState(() {});
}
/// The palette above the composer: dsh-Go's `/` menu, on the app's theme.
Widget _slashPalette(List<SlashItem> items) => SlashPalette(
items: items,
index: _slashIndex,
loading: chat.slashLoading,
onPick: _pickSlash,
);
Widget _composer(double keyboardInset) {
2026-11-18 19:08:06 +08:00
final usage = chat.usageReading();
2026-11-18 20:48:12 +08:00
final scheme = Theme.of(context).colorScheme;
final canSend = _draftCtrl.text.trim().isNotEmpty || _attachments.isNotEmpty;
// The key is stop only while running with nothing to send.
final showStop = chat.running && !canSend;
final slash = _slashMatches();
final slashRows = slash ?? const <SlashItem>[];
Widget body = Padding(
padding: const EdgeInsets.fromLTRB(8, 6, 8, 6),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_attachments.isNotEmpty) _attachmentTray(),
if (slash != null) ...[
KeyedSubtree(
key: const ValueKey('slash-palette'),
child: _slashPalette(slashRows),
2026-11-18 19:08:06 +08:00
),
const SizedBox(height: 6),
2026-11-18 19:08:06 +08:00
],
ComposerBox(
controller: _draftCtrl,
focusNode: _inputFocus,
hint: chat.running ? tr('Generating; you can still type…') : tr('Send a message…'),
maxLines: 5,
keyboardInset: keyboardInset,
// While the palette is up, the keyboard's action key picks the
// highlighted row instead of writing a newline.
textInputAction:
slash != null ? TextInputAction.send : TextInputAction.newline,
onSubmitted: slash == null || slashRows.isEmpty
? null
: (_) => _pickSlash(
slashRows[_slashIndex.clamp(0, slashRows.length - 1)]),
onChanged: (v) {
chat.draft = v;
_slashIndex = 0;
if (_slashDismissed != null && v != _slashDismissed) {
_slashDismissed = null;
}
if (v.trimLeft().startsWith('/')) chat.ensureSlash();
setState(() {});
// A soft keyboard whose action key still writes a newline
// commits the highlighted row instead of leaving a stray blank
// line in the draft.
if (slash != null && v.endsWith('\n')) {
final trimmed = v.trimRight();
_draftCtrl.value = TextEditingValue(
text: trimmed,
selection: TextSelection.collapsed(offset: trimmed.length),
);
chat.draft = trimmed;
final rows = _slashMatches() ?? const <SlashItem>[];
if (rows.isNotEmpty) {
_pickSlash(rows[_slashIndex.clamp(0, rows.length - 1)]);
}
}
},
leading: _roundKey(
icon: Icons.attach_file,
label: tr('Add attachment'),
onTap: _pickFiles,
busy: _attaching,
),
model: ModelPill(
app: widget.app,
model: chat.selectedModel ?? widget.session.model,
onModel: (m) => chat.switchModel(m),
),
mode: ModeChip(
app: widget.app,
agent: chat.selectedAgent,
onAgent: (a) => chat.switchAgent(a),
),
accessory: usage.$5
? InkWell(
onTap: () => _usageSheet(context),
borderRadius: BorderRadius.circular(20),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 2),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
UsageRing(
pct: usage.$4,
size: 16,
accent: scheme.primary),
const SizedBox(width: 3),
AppText(
usage.$6
? '~${usage.$4.round()}%'
: '${usage.$4.round()}%',
style: TextStyle(
fontSize: 12,
color: scheme.onSurfaceVariant)),
],
),
),
)
: null,
// Stop only while the turn runs with an empty draft; once there is
// something to send the key sends again, as dsh-Go's does.
trailing: _roundKey(
icon: showStop ? Icons.stop_rounded : Icons.arrow_upward_rounded,
label: showStop ? tr('Stop') : tr('Send'),
filled: true,
enabled: showStop || canSend,
onTap: showStop ? chat.stop : _send,
onLongPress: showStop ? null : _sendOptions,
),
),
],
),
);
// Always wrapped: re-parenting the field when the palette opens would
// drop its focus, and with it the characters typed after `/`.
return SafeArea(
top: false,
child: CallbackShortcuts(
bindings: slash == null
? const {}
: {
const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
_moveSlash(slashRows, 1),
const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
_moveSlash(slashRows, -1),
const SingleActivator(LogicalKeyboardKey.enter): () =>
_pickSlash(slashRows[
_slashIndex.clamp(0, slashRows.length - 1)]),
const SingleActivator(LogicalKeyboardKey.numpadEnter): () =>
_pickSlash(slashRows[
_slashIndex.clamp(0, slashRows.length - 1)]),
const SingleActivator(LogicalKeyboardKey.escape): _dismissSlash,
},
child: body,
2026-11-18 19:08:06 +08:00
),
);
}
2026-11-18 20:48:12 +08:00
/// One 36px round key of the input bar.
Widget _roundKey({
required IconData icon,
required String label,
required VoidCallback onTap,
VoidCallback? onLongPress,
2026-11-18 20:48:12 +08:00
bool filled = false,
bool enabled = true,
bool busy = false,
}) {
final scheme = Theme.of(context).colorScheme;
final on = enabled && !busy;
final bg = filled
? (on ? scheme.primary : scheme.onSurface.withValues(alpha: 0.12))
: scheme.onSurface.withValues(alpha: 0.06);
final fg = filled
? (on ? scheme.onPrimary : scheme.onSurface.withValues(alpha: 0.38))
: scheme.onSurface;
return Semantics(
button: true,
enabled: on,
label: label,
child: Material(
color: bg,
shape: const CircleBorder(),
child: InkWell(
customBorder: const CircleBorder(),
onTap: on ? onTap : null,
onLongPress: on ? onLongPress : null,
2026-11-18 20:48:12 +08:00
child: SizedBox(
width: 36,
height: 36,
child: Center(
child: busy
? SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2, color: fg),
)
: Icon(icon, size: 20, color: fg),
),
),
),
),
);
}
/// Attachment chips with a thumbnail, unfolded above the input bar.
Widget _attachmentTray() => AttachmentTray(
items: _attachments,
onRemove: (i) => setState(() => _attachments.removeAt(i)),
);
2026-11-18 20:48:12 +08:00
/// Long-press on send while a turn runs: join it (steer) or wait for it to
/// end (queue). Only the deliveries the server offers are listed.
Future<void> _sendOptions() async {
if (!chat.running) return _send();
2026-11-18 19:08:06 +08:00
final text = _draftCtrl.text.trim();
if (text.isEmpty && _attachments.isEmpty) return;
// The configured behavior is what a short press does; mark it here too.
final fallback = widget.app.followUpBehavior;
final scheme = Theme.of(context).colorScheme;
final picked = await showModalBottomSheet<String>(
context: context,
showDragHandle: true,
builder: (sheet) => SafeArea(
top: false,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Padding(
padding: EdgeInsets.fromLTRB(20, 4, 20, 8),
child: AppText('Delivery',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700)),
),
ListTile(
leading: const Icon(Icons.alt_route),
title: const AppText('Steer into this turn'),
subtitle: const AppText('Join at the next step; work continues'),
trailing: fallback == 'steer'
? Icon(Icons.check, size: 20, color: scheme.primary)
: null,
onTap: () => Navigator.pop(sheet, 'steer'),
),
ListTile(
leading: const Icon(Icons.schedule),
title: const AppText('Queue'),
subtitle: const AppText('Send after this turn ends'),
trailing: fallback == 'queue'
? Icon(Icons.check, size: 20, color: scheme.primary)
: null,
onTap: () => Navigator.pop(sheet, 'queue'),
),
const SizedBox(height: 8),
],
),
),
);
if (picked == null || !mounted) return;
await _send(delivery: picked);
}
Future<void> _send({String? delivery}) async {
final text = _draftCtrl.text.trim();
if (text.isEmpty && _attachments.isEmpty) return;
// A short send while a turn runs uses the configured follow-up behavior;
// the long-press sheet can choose the other one for this message.
final effective =
chat.running ? (delivery ?? widget.app.followUpBehavior) : null;
2026-11-18 19:08:06 +08:00
// Files ride with the prompt as data URLs.
final files = <Map<String, String>>[];
final images = <String>[];
for (final a in _attachments) {
files.add({'uri': a.dataUrl, 'name': a.name});
if (a.mime.startsWith('image/') && a.path != null) {
images.add(a.path!);
}
}
final id = await chat.send(text: text, files: files, delivery: effective);
if (id == null) {
// The prompt failed: keep the text for a retry.
_draftCtrl.text = chat.draft;
return;
}
2026-11-18 19:08:06 +08:00
_draftCtrl.clear();
setState(() => _attachments = []);
if (images.isNotEmpty && id.isNotEmpty) {
2026-11-18 19:08:06 +08:00
chat.imagePaths[id] = images;
chat.touch();
}
2026-11-18 20:48:12 +08:00
HapticFeedback.lightImpact();
2026-11-18 19:08:06 +08:00
}
Future<void> _pickFiles() async {
setState(() => _attaching = true);
try {
final picked = await pickComposerAttachments(context);
if (picked.isEmpty) return;
setState(() {
for (final file in picked) {
if (_attachments.length >= 5) break;
_attachments.add(file);
2026-11-18 19:08:06 +08:00
}
});
2026-11-18 19:08:06 +08:00
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: AppText(trArgs('Could not attach: {0}', ['$e']))));
2026-11-18 19:08:06 +08:00
}
} finally {
if (mounted) setState(() => _attaching = false);
}
}
2026-11-18 19:08:06 +08:00
// ---------------------------------------------------------- permissions
/// The agent's blocking questions sit just above the composer, like the
/// permissions dock: answering one lets the turn continue.
Widget _forms() {
if (chat.forms.isEmpty) return const SizedBox.shrink();
final form = chat.forms.first;
return _FormDock(key: ValueKey(form.id), chat: chat, form: form);
}
2026-11-18 19:08:06 +08:00
Widget _permissions() {
final perms = widget.app.perms
.where((p) => p.sessionId.isEmpty || p.sessionId == chat.id)
.toList();
if (perms.isEmpty) return const SizedBox.shrink();
return Column(
children: [
for (final p in perms)
Card(
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
AppText(trArgs('Permission requested: {0}', [p.action]),
2026-11-18 19:08:06 +08:00
style: const TextStyle(fontWeight: FontWeight.w600)),
Text(p.resources.join(', '),
2026-11-18 19:08:06 +08:00
style: const TextStyle(color: Colors.grey, fontSize: 13)),
const SizedBox(height: 6),
Row(
children: [
TextButton(
onPressed: () => chat.replyPermission(p.id, 'once'),
child: const AppText('Allow once')),
2026-11-18 19:08:06 +08:00
TextButton(
onPressed: () => chat.replyPermission(p.id, 'always'),
child: const AppText('Always allow')),
2026-11-18 19:08:06 +08:00
TextButton(
onPressed: () => chat.replyPermission(p.id, 'reject'),
child: const AppText('Deny')),
2026-11-18 19:08:06 +08:00
],
),
],
),
),
),
],
);
}
// -------------------------------------------------------------- sheets
void _confirm({required String title, required String message, required String confirm, required VoidCallback onConfirm}) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: AppText(title),
content: AppText(message),
2026-11-18 19:08:06 +08:00
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const AppText('Cancel')),
2026-11-18 19:08:06 +08:00
FilledButton(
onPressed: () {
Navigator.pop(context);
onConfirm();
},
child: AppText(confirm),
2026-11-18 19:08:06 +08:00
),
],
),
);
}
// ------------------------------------------------------------ previews
Future<void> _openPreview(_ImageRef ref) =>
_showImageDialog(ref.label, source: ref.source);
Future<void> _showImageDialog(String title, {required String source}) =>
_showImages([ImageSlide(title, source)], 0);
Future<void> _showImages(List<ImageSlide> images, int initial) async {
final client = widget.app.client;
if (client == null || images.isEmpty) return;
await showImageViewer(
context,
images: images,
initial: initial,
directory: chat.dir,
client: client,
2026-11-18 19:08:06 +08:00
);
}
// ------------------------------------------------------------ usage
void _usageSheet(BuildContext context) {
final r = chat.usageReading();
showModalBottomSheet(
context: context,
builder: (context) => Padding(
padding: const EdgeInsets.fromLTRB(20, 12, 20, 24),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const AppText('Context usage', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
2026-11-18 19:08:06 +08:00
const SizedBox(height: 12),
_usageRow('Model', widget.app.modelName(chat.selectedModel ?? _lastModel())),
_usageRow('Tokens used', _fmtTokens(r.$1)),
2026-11-18 19:08:06 +08:00
if (r.$5) ...[
_usageRow('Context limit', _fmtTokens(r.$2)),
_usageRow('Reserved output', _fmtTokens(r.$3)),
_usageRow('Usage', '${r.$4.toStringAsFixed(1)}%'),
2026-11-18 19:08:06 +08:00
],
if (chat.turnCost > 0) _usageRow('Turn cost', '\$${chat.turnCost.toStringAsFixed(4)}'),
2026-11-18 19:08:06 +08:00
const SizedBox(height: 8),
if (r.$6)
const AppText(
'The model is not in the catalog; the context window is estimated.',
style: TextStyle(color: Colors.grey, fontSize: 12))
else
const AppText(
'Reserved output assumes at most 32K tokens, matching the official client.',
style: TextStyle(color: Colors.grey, fontSize: 12)),
2026-11-18 19:08:06 +08:00
],
),
),
);
2026-11-18 19:08:06 +08:00
}
ModelRef? _lastModel() {
for (var i = chat.msgs.length - 1; i >= 0; i--) {
if (chat.msgs[i].model != null) return chat.msgs[i].model;
}
return null;
}
Widget _usageRow(String label, String value) => Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
children: [
Expanded(child: AppText(label, style: const TextStyle(color: Colors.grey))),
Text(value),
2026-11-18 19:08:06 +08:00
],
),
);
static String _fmtTokens(int n) {
if (n >= 1000000) return '${(n / 1000000).toStringAsFixed(1)}M';
if (n >= 1000) return '${(n / 1000).toStringAsFixed(1)}K';
return '$n';
}
}
class _Row {
final String kind;
final String msgId;
final int part;
_Row(this.kind, this.msgId, this.part);
}
/// Height animation for a fold: the body grows from its top edge and fades in,
/// reporting each bit of height it adds so the list can hold its header still.
/// Same behaviour as dsh-Go's ExpandReveal (MIT).
class _Reveal extends StatefulWidget {
final bool open;
final Widget child;
final ValueChanged<double>? onGrow;
const _Reveal({
required this.open,
required this.child,
this.onGrow,
});
@override
State<_Reveal> createState() => _RevealState();
}
class _RevealState extends State<_Reveal>
with SingleTickerProviderStateMixin {
late final AnimationController _c = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 280),
value: widget.open ? 1 : 0,
)..addListener(_tick);
late final Animation<double> _size = CurvedAnimation(
parent: _c,
curve: Curves.easeInOutCubic,
reverseCurve: Curves.easeInOutCubic.flipped);
late final Animation<double> _fade = CurvedAnimation(
parent: _c, curve: const Interval(0.3, 1, curve: Curves.easeOut));
final GlobalKey _body = GlobalKey();
double? _shown;
@override
void didUpdateWidget(_Reveal old) {
super.didUpdateWidget(old);
if (widget.open == old.open) return;
// A fold nobody can see (a finished run far up the history) must not
// animate or drag the view: it just takes its new size.
if (!_headerOnScreen()) {
_c.value = widget.open ? 1 : 0;
return;
}
// Every pixel the fold adds or removes is reported from here on, so the
// list can hold the header still for the whole animation. Expanding starts
// from zero; collapsing starts from the height already on screen.
final box = _body.currentContext?.findRenderObject() as RenderBox?;
_shown = widget.open || box == null || !box.hasSize ? 0 : box.size.height;
widget.open ? _c.forward() : _c.reverse();
}
/// Whether this fold's header (the row right above it) is in view.
bool _headerOnScreen() {
final self = context.findRenderObject();
final scroll = Scrollable.maybeOf(context);
if (self is! RenderBox || !self.attached || scroll == null) return true;
final viewport = scroll.context.findRenderObject();
if (viewport is! RenderBox || !viewport.attached) return true;
final top = self.localToGlobal(Offset.zero).dy;
final vTop = viewport.localToGlobal(Offset.zero).dy;
return top > vTop + 24 && top < vTop + viewport.size.height;
}
@override
void dispose() {
_c.dispose();
super.dispose();
}
void _tick() {
final box = _body.currentContext?.findRenderObject() as RenderBox?;
if (box == null || !box.hasSize) {
if (_size.value > 0) {
WidgetsBinding.instance.addPostFrameCallback((_) => _tick());
}
return;
}
final shown = _size.value * box.size.height;
final before = _shown;
_shown = shown;
if (before == null) return;
final delta = shown - before;
if (delta.abs() > 0.01) widget.onGrow?.call(delta);
}
@override
Widget build(BuildContext context) {
if (!widget.open && _c.isDismissed) return const SizedBox.shrink();
return SizeTransition(
sizeFactor: _size,
axisAlignment: -1,
child: FadeTransition(
opacity: _fade,
child: KeyedSubtree(key: _body, child: widget.child),
),
);
}
}
/// One reasoning or tool part, addressed across the assistant messages of a
/// turn.
class _Step {
final String msgId;
final int index;
final ContentPart part;
const _Step(this.msgId, this.index, this.part);
}
2026-11-18 19:08:06 +08:00
class _ImageRef {
final String source;
final String label;
_ImageRef(this.source, this.label);
}
List<_ImageRef> toolImages(ContentPart p, String dir) {
const exts = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.avif'};
final out = <_ImageRef>[];
final seen = <String>{};
final labels = <String>{};
void add(String source, String label) {
source = source.trim();
if (source.startsWith('file://')) source = source.substring(7);
if (source.isEmpty || seen.contains(source)) return;
if (!source.startsWith('data:')) {
if (source.contains('://')) return;
if (!source.startsWith('/')) {
if (dir.isEmpty) return;
source = '$dir/$source';
}
final ext = source.contains('.') ? '.${source.split('.').last.toLowerCase()}' : '';
if (!exts.contains(ext)) return;
if (label.isEmpty) {
label = source.split('/').last;
}
if (labels.contains(label)) return;
}
if (label.isEmpty) label = 'Image';
2026-11-18 19:08:06 +08:00
seen.add(source);
labels.add(label);
out.add(_ImageRef(source, label));
}
final st = p.state;
if (st != null) {
var attachments = 0;
for (final c in [...st.attachments, ...st.content]) {
if (c.type == 'file' && (c.mime ?? '').startsWith('image/')) {
final src = (c.url?.isNotEmpty ?? false) ? c.url! : c.uri;
if (src != null && src.isNotEmpty) {
attachments++;
add(src, c.filename ?? '');
}
} else if (c.type == 'text') {
final re = RegExp(r'(/[^\s"' + r'`' + r'()\[\]{}<>]+\.(?:png|jpg|jpeg|gif|webp|bmp|avif))');
for (final m in re.allMatches(c.text)) {
add(m.group(1)!, '');
}
}
}
if (attachments == 0) {
for (final k in ['filePath', 'path', 'file', 'file_path', 'sourcePath']) {
final v = st.input[k];
if (v is String) add(v, '');
}
}
}
return out;
}
String toolOutput(ContentPart p) {
final st = p.state;
if (st == null) return '';
final out = st.content.where((c) => c.type == 'text').map((c) => c.text).join('\n');
if (out.isNotEmpty) return out;
for (final key in const ['output', 'result', 'stdout', 'text', 'content']) {
final v = st.metadata?[key];
if (v is String && v.isNotEmpty) return v;
}
return st.error ?? '';
2026-11-18 19:08:06 +08:00
}
/// Already-fetched pictures, kept for the card and the full-screen view so a
/// rebuild does not ask the server again. Generated images are large, so only
/// a handful stay.
final Map<String, Uint8List> _imageBytes = {};
Future<Uint8List> _imageBytesFor(
Client client, String source, String directory) async {
if (source.startsWith('data:')) {
final comma = source.indexOf(',');
if (comma < 0) throw Exception(tr('Invalid data URL'));
final meta = source.substring(5, comma);
if (!meta.contains('base64')) throw Exception(tr('Unsupported data URL'));
return base64Decode(source.substring(comma + 1));
}
final cached = _imageBytes[source];
if (cached != null) return cached;
final bytes =
Uint8List.fromList(await client.rawFile(source, directory: directory));
if (_imageBytes.length >= 8) _imageBytes.remove(_imageBytes.keys.first);
_imageBytes[source] = bytes;
return bytes;
}
/// One generated picture, in the conversation where the call ran. Loading is
/// its own state, as the image dialog does it: the row is created before the
/// bytes arrive.
class _GeneratedImage extends StatefulWidget {
final String source;
final String directory;
final Client client;
final VoidCallback onTap;
const _GeneratedImage({
required this.source,
required this.directory,
required this.client,
required this.onTap,
});
@override
State<_GeneratedImage> createState() => _GeneratedImageState();
}
class _GeneratedImageState extends State<_GeneratedImage> {
Uint8List? _bytes;
Object? _error;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
try {
final bytes =
await _imageBytesFor(widget.client, widget.source, widget.directory);
if (mounted) setState(() => _bytes = bytes);
} catch (e) {
if (mounted) setState(() => _error = e);
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
if (_error != null) {
return Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(10),
),
child: Row(
children: [
Icon(Icons.broken_image_outlined,
size: 16, color: theme.hintColor),
const SizedBox(width: 8),
Expanded(
child: AppText(
trArgs('Could not load image: {0}', [pathLeaf(widget.source)]),
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: theme.hintColor),
),
),
],
),
);
}
if (_bytes == null) {
return Container(
height: 150,
alignment: Alignment.center,
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(10),
),
child: const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
);
}
return Align(
alignment: Alignment.centerLeft,
child: InkWell(
onTap: widget.onTap,
borderRadius: BorderRadius.circular(10),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 380),
child: Image.memory(
_bytes!,
fit: BoxFit.contain,
alignment: Alignment.centerLeft,
gaplessPlayback: true,
),
),
),
),
);
}
}
/// A full-screen-ish image preview that loads itself: the dialog is created
/// first, so the image and its spinner must live in a StatefulWidget.
/// The native form/question card: every visible field at once, one answer.
/// Field visibility follows the form's `when` clauses, and required fields
/// must be filled before it can be sent.
class _FormDock extends StatefulWidget {
final ChatState chat;
final FormInfo form;
const _FormDock({super.key, required this.chat, required this.form});
@override
State<_FormDock> createState() => _FormDockState();
}
class _FormDockState extends State<_FormDock> {
final Map<String, Object?> _values = {};
final Map<String, TextEditingController> _controllers = {};
String? _error;
bool _sending = false;
@override
void initState() {
super.initState();
for (final f in widget.form.fields) {
switch (f.type) {
case 'boolean':
_values[f.key] = f.defaultValue is bool ? f.defaultValue : false;
break;
case 'multiselect':
_values[f.key] = f.defaultValue is List
? List<String>.from((f.defaultValue as List).whereType<String>())
: <String>[];
break;
case 'external':
_values[f.key] = true;
break;
default:
if (f.defaultValue != null) {
_values[f.key] = f.defaultValue;
_controllers[f.key] =
TextEditingController(text: '${f.defaultValue}');
}
}
}
}
@override
void dispose() {
for (final c in _controllers.values) {
c.dispose();
}
super.dispose();
}
bool _visible(AgentFormField f) {
if (f.hidden) return false;
for (final w in f.when) {
final v = _values[w.key];
final eq = v == w.value ||
(v is num && w.value is num && v == w.value) ||
(v is bool && w.value is bool && v == w.value);
if (w.op == 'neq' ? eq : !eq) return false;
}
return true;
}
TextEditingController _controller(AgentFormField f) =>
_controllers.putIfAbsent(f.key, () => TextEditingController());
void _set(AgentFormField f, Object? value) {
setState(() {
_values[f.key] = value;
_error = null;
});
}
Future<void> _submit() async {
final visible = widget.form.fields.where(_visible).toList();
final missing = <String>[];
for (final f in visible) {
if (!f.required || f.type == 'external') continue;
final v = _values[f.key];
// A required switch or acknowledgement has to be on, not merely set.
final empty = v == null ||
v == false ||
(v is String && v.trim().isEmpty) ||
(v is List && v.isEmpty);
if (empty) missing.add(f.label);
}
if (missing.isNotEmpty) {
setState(() => _error = trArgs('Required: {0}', [missing.join(tr(', '))]));
return;
}
final answer = <String, Object?>{};
for (final f in visible) {
if (f.type == 'external') {
answer[f.key] = true;
continue;
}
final v = _values[f.key];
if (v == null) continue;
if (v is String && v.trim().isEmpty) continue;
if (v is List && v.isEmpty) continue;
answer[f.key] = v;
}
setState(() {
_sending = true;
_error = null;
});
await widget.chat.replyForm(widget.form, answer);
if (mounted) setState(() => _sending = false);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final fields = widget.form.fields.where(_visible).toList();
return Card(
margin: const EdgeInsets.fromLTRB(12, 4, 12, 4),
color: scheme.surfaceContainerHigh,
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 10, 12, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Icon(Icons.help_outline, size: 18, color: scheme.primary),
const SizedBox(width: 8),
Expanded(
child: AppText(
widget.form.title.isEmpty ? 'Choose one' : widget.form.title,
style: const TextStyle(
fontSize: 14, fontWeight: FontWeight.w600),
),
),
TextButton(
style: TextButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 8),
minimumSize: const Size(0, 32),
),
onPressed: _sending
? null
: () => widget.chat.cancelForm(widget.form),
child: const AppText('Cancel', style: TextStyle(fontSize: 12.5)),
),
],
),
if (fields.isNotEmpty)
ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 360),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (final f in fields) _field(f, theme),
],
),
),
),
if (_error != null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: AppText(_error!,
style: TextStyle(fontSize: 12, color: scheme.error)),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FilledButton(
onPressed: _sending ? null : _submit,
child: _sending
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2))
: const AppText('Send'),
),
],
),
],
),
),
);
}
Widget _field(AgentFormField f, ThemeData theme) {
final scheme = theme.colorScheme;
final title = Row(
children: [
Flexible(
child: Text(f.label,
style:
const TextStyle(fontSize: 13, fontWeight: FontWeight.w600)),
),
if (f.required)
AppText(' *', style: TextStyle(color: scheme.error, fontSize: 13)),
],
);
Widget hint() => f.description == null || f.description!.isEmpty
? const SizedBox.shrink()
: Padding(
padding: const EdgeInsets.only(top: 2, bottom: 2),
child: Text(f.description!,
style: TextStyle(fontSize: 12, color: theme.hintColor)),
);
switch (f.type) {
case 'external':
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
title,
hint(),
if (f.url != null && f.url!.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 2),
child: Text(f.url!,
style: TextStyle(
fontSize: 12, color: scheme.primary),
maxLines: 2,
overflow: TextOverflow.ellipsis),
),
],
),
);
case 'boolean':
return SwitchListTile(
contentPadding: EdgeInsets.zero,
dense: true,
title: title,
subtitle: hint(),
value: _values[f.key] == true,
onChanged: (v) => _set(f, v),
);
case 'multiselect':
final selected = List<String>.from(
(_values[f.key] as List?)?.whereType<String>() ?? const []);
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
title,
hint(),
Wrap(
spacing: 6,
runSpacing: -6,
children: [
for (final o in f.options)
FilterChip(
label: AppText(o.label, style: const TextStyle(fontSize: 12.5)),
selected: selected.contains(o.value),
onSelected: (on) {
final next = [...selected];
if (on) {
next.add(o.value);
} else {
next.remove(o.value);
}
_set(f, next);
},
),
],
),
],
),
);
case 'string':
if (f.options.isNotEmpty) {
final current = _values[f.key]?.toString();
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
title,
hint(),
Wrap(
spacing: 6,
runSpacing: -6,
children: [
for (final o in f.options)
ChoiceChip(
label: AppText(o.label,
style: const TextStyle(fontSize: 12.5)),
selected: current == o.value,
onSelected: (_) => _set(f, o.value),
),
],
),
if (f.custom)
Padding(
padding: const EdgeInsets.only(top: 6),
child: TextField(
controller: _controller(f),
onChanged: (v) => _set(f, v),
style: const TextStyle(fontSize: 13),
decoration: InputDecoration(
isDense: true,
hintText: tr('Other…'),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8)),
),
),
),
],
),
);
}
final numeric = f.format == 'number';
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
title,
hint(),
const SizedBox(height: 4),
TextField(
controller: _controller(f),
onChanged: (v) => _set(f, v),
keyboardType: f.format == 'email'
? TextInputType.emailAddress
: f.format == 'uri'
? TextInputType.url
: numeric
? TextInputType.number
: TextInputType.text,
style: const TextStyle(fontSize: 13),
decoration: InputDecoration(
isDense: true,
hintText: f.placeholder ??
(f.format == 'date' ? 'YYYY-MM-DD' : null),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8)),
),
),
],
),
);
case 'number':
case 'integer':
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
title,
hint(),
const SizedBox(height: 4),
TextField(
controller: _controller(f),
keyboardType:
TextInputType.numberWithOptions(decimal: f.type == 'number'),
onChanged: (v) {
final n = f.type == 'integer'
? int.tryParse(v)
: num.tryParse(v);
_set(f, n ?? (v.isEmpty ? null : v));
},
style: const TextStyle(fontSize: 13),
decoration: InputDecoration(
isDense: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8)),
),
),
],
),
);
default:
return Padding(
padding: const EdgeInsets.only(top: 8),
child: AppText(trArgs('{0} ({1})', [f.label, f.type]),
style: const TextStyle(fontSize: 13)),
);
}
}
}