Merge branch 'worktree-agent-a26df8b0059ab1b12'

This commit is contained in:
2026-11-09 20:54:12 +00:00
43 changed files with 2689 additions and 274 deletions
@@ -5,14 +5,22 @@ import 'package:flutter/widgets.dart';
abstract final class ChatComposerPasteFocus {
static final Set<FocusNode> _composers = {};
static final Set<FocusNode> _inputs = {};
static void register(FocusNode focus) => _composers.add(focus);
static void unregister(FocusNode focus) => _composers.remove(focus);
/// An input that is not an [EditableText] (a shell command's terminal)
/// registers its focus here: a paste while it has focus is its own.
static void registerInput(FocusNode focus) => _inputs.add(focus);
static void unregisterInput(FocusNode focus) => _inputs.remove(focus);
static bool get anotherEditableHasFocus {
final primary = FocusManager.instance.primaryFocus;
if (primary == null || _composers.any((focus) => focus.hasFocus)) {
return false;
}
if (_inputs.any((focus) => focus.hasFocus)) return true;
final context = primary.context;
if (context == null) return false;
var editable = context.widget is EditableText;
@@ -4,7 +4,6 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'chat_shell_metrics.dart';
import 'chat_shell_run.dart';
import 'chat_shell_runs_controller.dart';
@@ -15,26 +14,23 @@ const String chatShellCopiedLabel = 'Copied';
const String chatShellShareLabel = 'Send to agent';
const String chatShellSharingLabel = 'Sending…';
const String chatShellSharedLabel = 'Sent to agent';
const String chatShellExpandLabel = 'Expand';
const String chatShellCollapseLabel = 'Collapse';
const String chatShellFullScreenLabel = 'Full screen';
/// The card's host buttons: Stop while running; Copy output, Send to agent
/// once finished; Expand/Collapse for the output area.
/// once finished; Full screen for the terminal.
class ChatShellCardActions extends StatefulWidget {
const ChatShellCardActions({
super.key,
required this.run,
required this.controller,
required this.cupertino,
required this.expanded,
required this.onToggleExpanded,
required this.onFullScreen,
});
final ChatShellRun run;
final ChatShellRunsController controller;
final bool cupertino;
final bool expanded;
final VoidCallback onToggleExpanded;
final VoidCallback onFullScreen;
@override
State<ChatShellCardActions> createState() => _ChatShellCardActionsState();
@@ -50,12 +46,12 @@ class _ChatShellCardActionsState extends State<ChatShellCardActions> {
super.dispose();
}
/// Copies everything the server kept, reading it first when this card
/// holds only the newest part.
/// Copies the plain text of everything the server kept (no terminal
/// escape sequences), read from the server.
Future<void> _copy() async {
final full = await widget.controller.loadAll(widget.run.id);
if (full == null) return;
await Clipboard.setData(ClipboardData(text: full.output));
final text = await widget.controller.plainText(widget.run.id);
if (text == null) return;
await Clipboard.setData(ClipboardData(text: text));
if (!mounted) return;
setState(() => _copied = true);
_reset?.cancel();
@@ -114,17 +110,13 @@ class _ChatShellCardActionsState extends State<ChatShellCardActions> {
? () => unawaited(controller.share(run.id))
: null,
),
if (widget.expanded || chatShellOutputMayOverflow(run.output))
if (run.running || run.output.isNotEmpty)
_button(
key: const Key('chat-shell-run-expand'),
label: widget.expanded
? chatShellCollapseLabel
: chatShellExpandLabel,
material: widget.expanded ? Icons.unfold_less : Icons.unfold_more,
cupertino: widget.expanded
? CupertinoIcons.chevron_up
: CupertinoIcons.chevron_down,
onPressed: widget.onToggleExpanded,
label: chatShellFullScreenLabel,
material: Icons.fullscreen,
cupertino: CupertinoIcons.fullscreen,
onPressed: widget.onFullScreen,
),
],
);
@@ -1,43 +1,5 @@
import 'package:flutter/widgets.dart';
/// The one layout bound of a shell command card: how tall its output area
/// may grow. Collapsed it shows about [kChatShellOutputCollapsedLines] lines
/// of the host's (scaled) monospace text; expanded it may take
/// [kChatShellOutputExpandedShare] of the window height. Everything else in
/// the card is content-sized.
/// The one layout bound of a shell command card: how many terminal rows its
/// output area shows. A running command's terminal has this many rows; a
/// finished one shrinks to the rows its output uses, up to this many, and
/// scrolls within them. Full screen takes the whole window instead.
const int kChatShellOutputCollapsedLines = 12;
const double kChatShellOutputExpandedShare = 0.6;
/// The monospace line height factor the output text is set at.
const double kChatShellOutputLineHeight = 1.35;
/// Characters of output drawn at once. A command can print far more than a
/// text layout should carry; the card says when it shows only the newest
/// part, and Copy output still copies everything the server kept.
const int kChatShellRenderedOutputLimit = 64 * 1024;
/// Whether [output] may be taller than the collapsed area, so Expand is worth
/// offering. Counted in lines, with long lines counted as wrapping.
bool chatShellOutputMayOverflow(String output) {
var lines = 0;
for (final line in output.split('\n')) {
lines += 1 + line.length ~/ 80;
if (lines > kChatShellOutputCollapsedLines) return true;
}
return false;
}
/// The output area's maximum height for this window, text scale and font.
double chatShellOutputMaxHeight(
BuildContext context, {
required double fontSize,
required bool expanded,
}) {
if (expanded) {
return MediaQuery.sizeOf(context).height * kChatShellOutputExpandedShare;
}
final line =
MediaQuery.textScalerOf(context).scale(fontSize) *
kChatShellOutputLineHeight;
return line * kChatShellOutputCollapsedLines;
}
@@ -1,119 +1,65 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/text/monospace.dart';
import '../conversation/chat_card_styles.dart';
import 'chat_shell_metrics.dart';
import 'chat_shell_run.dart';
import 'chat_shell_runs_controller.dart';
import 'chat_shell_terminal_keys.dart';
import 'chat_shell_terminal_view.dart';
/// The terminal-style output area of one command card: the host's monospace
/// body on a quiet inset surface, scrollable inside a bounded height and
/// anchored at the newest line while the command runs.
class ChatShellOutputView extends StatefulWidget {
/// The output area of one command card: the run's terminal emulator, which
/// takes typing while the command runs (with the key toolbar below it), or
/// its retained output read-only once it ended.
class ChatShellOutputView extends StatelessWidget {
const ChatShellOutputView({
super.key,
required this.run,
required this.controller,
required this.cupertino,
required this.expanded,
required this.viewKey,
required this.fullScreen,
});
final ChatShellRun run;
final ChatShellRunsController controller;
final bool cupertino;
final bool expanded;
@override
State<ChatShellOutputView> createState() => _ChatShellOutputViewState();
}
/// Replaced when the full-screen view closes, so the card's view sizes the
/// terminal to itself again.
final Key viewKey;
class _ChatShellOutputViewState extends State<ChatShellOutputView> {
final ScrollController _scroll = ScrollController();
@override
void dispose() {
_scroll.dispose();
super.dispose();
}
/// True while the full-screen view sizes the terminal.
final bool fullScreen;
@override
Widget build(BuildContext context) {
final run = widget.run;
final cupertino = widget.cupertino;
final body = chatCardBodyStyle(context, cupertino) ?? const TextStyle();
final fontSize = (body.fontSize ?? 14) * 0.95;
final style = body.copyWith(
fontFamily: appMonospaceFamily,
fontSize: fontSize,
height: kChatShellOutputLineHeight,
);
final secondary = chatCardSecondaryStyle(context, cupertino);
var text = run.output;
final clipped = text.length > kChatShellRenderedOutputLimit;
if (clipped) {
text = text.substring(text.length - kChatShellRenderedOutputLimit);
if (!run.running && run.output.isEmpty) {
return Text(
'No output.',
key: const Key('chat-shell-output-empty'),
style: chatCardSecondaryStyle(context, cupertino),
);
}
// The final newline ends the last line; it is not an empty line to draw.
if (text.endsWith('\n')) text = text.substring(0, text.length - 1);
final notes = [
if (run.truncated) 'Earlier output was dropped.',
if (clipped)
'Showing only the newest part; Copy output copies all of it.',
];
final session = controller.terminals.session(run);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
if (notes.isNotEmpty)
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Text(
notes.join(' '),
key: const Key('chat-shell-output-truncated'),
style: secondary,
),
),
DecoratedBox(
decoration: BoxDecoration(
color: chatCardFillColor(context, cupertino),
borderRadius: BorderRadius.circular(8),
),
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: chatShellOutputMaxHeight(
context,
fontSize: fontSize,
expanded: widget.expanded,
),
),
child: _scrollable(
Padding(
padding: const EdgeInsets.all(10),
child: text.isEmpty
? Text(
run.running ? 'No output yet.' : 'No output.',
style: secondary,
)
: Text(
text,
key: const Key('chat-shell-output-text'),
style: style,
),
),
),
),
ChatShellTerminalView(
key: viewKey,
session: session,
cupertino: cupertino,
autoResize: !fullScreen,
),
if (session.live && !fullScreen)
Padding(
padding: const EdgeInsets.only(top: 8),
child: ChatShellTerminalKeys(
session: session,
cupertino: cupertino,
field: chatShellTouchFirst(),
),
),
],
);
}
/// A short output sizes the box to itself; a long one scrolls inside it,
/// starting from (and following) the newest line.
Widget _scrollable(Widget child) {
final scroll = SingleChildScrollView(
controller: _scroll,
reverse: true,
child: SizedBox(width: double.infinity, child: child),
);
return widget.cupertino
? CupertinoScrollbar(controller: _scroll, child: scroll)
: Scrollbar(controller: _scroll, child: scroll);
}
}
@@ -27,6 +27,10 @@ class ChatShellRun {
this.outputEnd = 0,
this.outputBytes = 0,
this.gap = false,
this.terminal = false,
this.cols = 0,
this.rows = 0,
this.text = '',
});
final String id;
@@ -53,6 +57,17 @@ class ChatShellRun {
/// stretch of what the command wrote.
final bool gap;
/// True when the command runs in a pseudo-terminal of [cols] x [rows]:
/// [output] is then the raw terminal stream and it accepts typed input
/// while it runs. Older runs (and servers without terminals) are plain.
final bool terminal;
final int cols;
final int rows;
/// The server's plain-text rendering of its retained output (escape codes
/// removed); only a whole-output readback carries it.
final String text;
/// Whether earlier output is not shown here.
bool get truncated => outputStart > 0 || gap;
@@ -92,6 +107,10 @@ class ChatShellRun {
// A readback's text runs to the newest byte the server had.
outputEnd: output.isEmpty && start == 0 ? 0 : bytes,
outputBytes: bytes,
terminal: value['terminal'] == true,
cols: _int(value['cols']),
rows: _int(value['rows']),
text: '${value['text'] ?? ''}',
);
}
@@ -114,6 +133,10 @@ class ChatShellRun {
? next.outputBytes
: outputBytes,
gap: gap,
terminal: next.terminal || terminal,
cols: next.cols == 0 ? cols : next.cols,
rows: next.rows == 0 ? rows : next.rows,
text: text,
);
/// This run with one live output chunk covering bytes [offset, end). A
@@ -144,6 +167,9 @@ class ChatShellRun {
outputEnd: end,
outputBytes: end > outputBytes ? end : outputBytes,
gap: gap || dropped || (!contiguous && offset > 0),
terminal: terminal,
cols: cols,
rows: rows,
);
}
@@ -10,10 +10,12 @@ import 'chat_shell_output_view.dart';
import 'chat_shell_run.dart';
import 'chat_shell_runs_controller.dart';
import 'chat_shell_status.dart';
import 'chat_shell_terminal_page.dart';
/// One operator command in the transcript, as a terminal-style card in the
/// reading column: the command and folder, its live output, a spinner and
/// Stop while it runs, then its exit status, Copy output and Send to agent.
/// One operator command in the transcript, as a terminal card in the reading
/// column: the command and folder, its terminal (typed into while it runs),
/// a spinner and Stop while it runs, then its exit status, Copy output and
/// Send to agent. Full screen opens the same terminal over the whole window.
///
/// It listens to [controller] itself, so streamed output rebuilds only this
/// card, never the transcript.
@@ -32,7 +34,23 @@ class ChatShellRunCard extends StatefulWidget {
}
class _ChatShellRunCardState extends State<ChatShellRunCard> {
bool _expanded = false;
bool _fullScreen = false;
int _viewGeneration = 0;
Future<void> _openFullScreen(bool cupertino) async {
setState(() => _fullScreen = true);
await openChatShellTerminalPage(
context,
controller: widget.controller,
runId: widget.runId,
cupertino: cupertino,
);
if (!mounted) return;
setState(() {
_fullScreen = false;
_viewGeneration++;
});
}
@override
Widget build(BuildContext context) {
@@ -113,8 +131,10 @@ class _ChatShellRunCardState extends State<ChatShellRunCard> {
const SizedBox(height: 12),
ChatShellOutputView(
run: run,
controller: controller,
cupertino: cupertino,
expanded: _expanded,
viewKey: ValueKey<int>(_viewGeneration),
fullScreen: _fullScreen,
),
if (run.error.isNotEmpty && !run.running)
Padding(
@@ -129,8 +149,7 @@ class _ChatShellRunCardState extends State<ChatShellRunCard> {
run: run,
controller: controller,
cupertino: cupertino,
expanded: _expanded,
onToggleExpanded: () => setState(() => _expanded = !_expanded),
onFullScreen: () => _openFullScreen(cupertino),
),
if (error != null)
Semantics(
@@ -6,6 +6,7 @@ import '../../../core/api_gateway.dart';
import '../../../core/error_reason.dart';
import 'chat_shell_run.dart';
import 'chat_shell_runs_repository.dart';
import 'chat_shell_terminals.dart';
/// Where one run's "Send to agent" stands.
enum ChatShellShareState { idle, sending, sent }
@@ -19,10 +20,22 @@ enum ChatShellShareState { idle, sending, sent }
class ChatShellRunsController extends ChangeNotifier {
ChatShellRunsController(this.gateway, this.sessionId)
: _repository = ChatShellRunsRepository(gateway) {
terminals = ChatShellTerminals(
_repository,
sessionId,
onError: (id, error) {
if (_disposed) return;
_errors[id] = _reason(error);
_changed();
},
);
_frames = gateway.frames.listen(_onFrame, onError: (_) {});
unawaited(refresh());
}
/// The runs' terminal emulators and their input and size delivery.
late final ChatShellTerminals terminals;
final ApiGateway gateway;
final String sessionId;
final ChatShellRunsRepository _repository;
@@ -54,9 +67,20 @@ class ChatShellRunsController extends ChangeNotifier {
if (_disposed || token != _generation) return;
for (final run in listed) {
final held = _runs[run.id];
_runs[run.id] = held != null && held.outputEnd > run.outputEnd
? held.withLifecycle(run)
: run;
if (held != null &&
held.running &&
held.outputEnd > 0 &&
run.outputBytes > held.outputEnd) {
// A reconnect: fetch only what this copy missed.
unawaited(_resume(held));
continue;
}
final keep = held != null && held.outputEnd >= run.outputEnd;
_runs[run.id] = keep ? held.withLifecycle(run) : run;
if (!keep) terminals.replaced(run);
if (held != null && held.running && !run.running) {
terminals.finished(_runs[run.id]!);
}
}
_changed(membership: true);
} catch (_) {
@@ -67,7 +91,13 @@ class ChatShellRunsController extends ChangeNotifier {
/// Starts [command] in the chat's directory. Returns the refusal, or null.
Future<String?> start(String command) async {
try {
final run = await _repository.run(sessionId, command);
final size = terminals.lastSize;
final run = await _repository.run(
sessionId,
command,
cols: size?.$1,
rows: size?.$2,
);
if (_disposed) return null;
_runs.putIfAbsent(run.id, () => run);
_changed(membership: true);
@@ -107,28 +137,53 @@ class ChatShellRunsController extends ChangeNotifier {
_changed();
}
/// Every byte the server retained for [id]: what Copy output copies and
/// Show all draws. Null when it cannot be read (the error is recorded).
Future<ChatShellRun?> loadAll(String id) async {
final held = _runs[id];
if (held == null) return null;
if (!held.truncated && !held.running) return held;
/// The plain-text rendering of everything the server kept for [id]: what
/// Copy output copies. Null when it cannot be read (the error is recorded).
Future<String?> plainText(String id) async {
try {
final full = await _repository.output(sessionId, id);
if (_disposed) return null;
final latest = _runs[id] ?? held;
// A frame newer than the read keeps the card's own lifecycle facts.
final merged = full.withLifecycle(latest.running ? full : latest);
_runs[id] = merged;
_changed();
return merged;
// A server without terminals records plain output and no rendering.
return full.terminal || full.text.isNotEmpty ? full.text : full.output;
} catch (error) {
if (_disposed) return null;
_errors[id] = _reason(error);
_changed();
return null;
}
}
/// Reads what a running run printed while this copy was disconnected,
/// from the byte it holds up to; a gap redraws from what the server kept.
Future<void> _resume(ChatShellRun held) async {
try {
final tail = await _repository.output(
sessionId,
held.id,
after: held.outputEnd,
);
if (_disposed) return;
final latest = _runs[held.id] ?? held;
final next = latest
.withChunk(tail.output, tail.outputStart, tail.outputBytes)
.withLifecycle(latest.running ? tail : latest);
_runs[held.id] = next;
if (tail.outputStart == latest.outputEnd) {
terminals.appended(
next,
tail.output,
tail.outputStart,
tail.outputBytes,
);
} else {
terminals.replaced(next);
}
if (!next.running) terminals.finished(next);
_changed();
} catch (_) {
// The next frame or refresh repairs the copy.
}
}
void _onFrame(JsonMap envelope) {
if (_disposed || envelope['type'] != 'chat_shell_run_event') return;
final frame = envelope['chat_shell_run_event'];
@@ -137,8 +192,12 @@ class ChatShellRunsController extends ChangeNotifier {
final record = ChatShellRun.fromJson(frame['run']);
if (record != null) {
final held = _runs[record.id];
_runs[record.id] = held == null ? record : held.withLifecycle(record);
if (!record.running) _stopping.remove(record.id);
final next = held == null ? record : held.withLifecycle(record);
_runs[record.id] = next;
if (!record.running) {
_stopping.remove(record.id);
if (held != null && held.running) terminals.finished(next);
}
_changed(membership: held == null);
return;
}
@@ -148,11 +207,12 @@ class ChatShellRunsController extends ChangeNotifier {
unawaited(refresh());
return;
}
_runs[id] = held.withChunk(
'${frame['output'] ?? ''}',
(frame['offset'] as num?)?.toInt() ?? 0,
(frame['end'] as num?)?.toInt() ?? 0,
);
final text = '${frame['output'] ?? ''}';
final offset = (frame['offset'] as num?)?.toInt() ?? 0;
final end = (frame['end'] as num?)?.toInt() ?? 0;
final next = held.withChunk(text, offset, end);
_runs[id] = next;
terminals.appended(next, text, offset, end);
_changed();
}
@@ -169,6 +229,7 @@ class ChatShellRunsController extends ChangeNotifier {
void dispose() {
_disposed = true;
_generation++;
terminals.dispose();
unawaited(_frames?.cancel());
_membership.dispose();
super.dispose();
@@ -6,19 +6,52 @@ class ChatShellRunsRepository {
const ChatShellRunsRepository(this.gateway);
final ApiGateway gateway;
JsonMap _body(String sessionId, {String? command, String? runId}) => {
JsonMap _body(
String sessionId, {
String? command,
String? runId,
int? cols,
int? rows,
String? data,
int? after,
}) => {
'chat_shell_run_request': {
'session_id': sessionId,
'command': ?command,
'run_id': ?runId,
'cols': ?cols,
'rows': ?rows,
'data': ?data,
'after': ?after,
},
};
/// Starts [command]; the reply is its running record.
Future<ChatShellRun> run(String sessionId, String command) async => _record(
await gateway.call('chat_shell_run', _body(sessionId, command: command)),
/// Starts [command] in a terminal of [cols] x [rows] (the server's default
/// size when null); the reply is its running record.
Future<ChatShellRun> run(
String sessionId,
String command, {
int? cols,
int? rows,
}) async => _record(
await gateway.call(
'chat_shell_run',
_body(sessionId, command: command, cols: cols, rows: rows),
),
);
/// Writes typed text (control characters and escape sequences included)
/// to a running command's terminal.
Future<void> input(String sessionId, String runId, String data) => gateway
.call('chat_shell_input', _body(sessionId, runId: runId, data: data));
/// Sets a running command's terminal size.
Future<void> resize(String sessionId, String runId, int cols, int rows) =>
gateway.call(
'chat_shell_resize',
_body(sessionId, runId: runId, cols: cols, rows: rows),
);
Future<void> stop(String sessionId, String runId) =>
gateway.call('chat_shell_stop', _body(sessionId, runId: runId));
@@ -34,9 +67,17 @@ class ChatShellRunsRepository {
];
}
/// One run with the whole output the server retained.
Future<ChatShellRun> output(String sessionId, String runId) async => _record(
await gateway.call('chat_shell_run_output', _body(sessionId, runId: runId)),
/// One run with the whole output the server retained and its plain-text
/// rendering, or only the output from absolute byte [after] on.
Future<ChatShellRun> output(
String sessionId,
String runId, {
int? after,
}) async => _record(
await gateway.call(
'chat_shell_run_output',
_body(sessionId, runId: runId, after: after),
),
);
/// Queues an ordinary prompt carrying the run for the agent.
@@ -0,0 +1,235 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:xterm/core.dart';
import 'chat_shell_terminal_session.dart';
/// One key of the terminal toolbar: its label, icons and what it sends.
typedef _Key = ({
String id,
String label,
IconData? material,
IconData? cupertino,
void Function(Terminal terminal) send,
});
final List<_Key> _keys = [
(
id: 'enter',
label: 'Enter',
material: Icons.keyboard_return,
cupertino: CupertinoIcons.return_icon,
send: (t) => t.keyInput(TerminalKey.enter),
),
(
id: 'ctrl-c',
label: 'Ctrl-C',
material: null,
cupertino: null,
send: (t) => t.textInput('\x03'),
),
(
id: 'tab',
label: 'Tab',
material: Icons.keyboard_tab,
cupertino: CupertinoIcons.arrow_right_to_line,
send: (t) => t.keyInput(TerminalKey.tab),
),
(
id: 'esc',
label: 'Esc',
material: null,
cupertino: null,
send: (t) => t.keyInput(TerminalKey.escape),
),
(
id: 'left',
label: 'Left',
material: Icons.keyboard_arrow_left,
cupertino: CupertinoIcons.arrow_left,
send: (t) => t.keyInput(TerminalKey.arrowLeft),
),
(
id: 'up',
label: 'Up',
material: Icons.keyboard_arrow_up,
cupertino: CupertinoIcons.arrow_up,
send: (t) => t.keyInput(TerminalKey.arrowUp),
),
(
id: 'down',
label: 'Down',
material: Icons.keyboard_arrow_down,
cupertino: CupertinoIcons.arrow_down,
send: (t) => t.keyInput(TerminalKey.arrowDown),
),
(
id: 'right',
label: 'Right',
material: Icons.keyboard_arrow_right,
cupertino: CupertinoIcons.arrow_right,
send: (t) => t.keyInput(TerminalKey.arrowRight),
),
];
/// The keys a touch keyboard lacks, and Paste, for a running terminal; with
/// [field], also a text line whose text is typed into the process on Enter
/// (the soft keyboard's own way in). The field is emptied as soon as its
/// text is sent and can hide what is typed, for a token or password.
class ChatShellTerminalKeys extends StatefulWidget {
const ChatShellTerminalKeys({
super.key,
required this.session,
required this.cupertino,
required this.field,
});
final ChatShellTerminalSession session;
final bool cupertino;
final bool field;
@override
State<ChatShellTerminalKeys> createState() => _ChatShellTerminalKeysState();
}
class _ChatShellTerminalKeysState extends State<ChatShellTerminalKeys> {
final TextEditingController _text = TextEditingController();
bool _hidden = false;
@override
void dispose() {
_text.dispose();
super.dispose();
}
Terminal get _terminal => widget.session.terminal;
Future<void> _paste() async {
final data = await Clipboard.getData(Clipboard.kTextPlain);
final text = data?.text;
if (text != null && text.isNotEmpty && widget.session.live) {
_terminal.paste(text);
}
}
/// Types the field's text and Enter, then forgets it.
void _submit() {
final text = _text.text;
_text.clear();
if (text.isNotEmpty) _terminal.textInput(text);
_terminal.keyInput(TerminalKey.enter);
}
@override
Widget build(BuildContext context) {
final keys = Wrap(
spacing: 4,
runSpacing: 4,
children: [
_button(
'paste',
'Paste',
Icons.content_paste,
CupertinoIcons.doc_on_clipboard,
_paste,
),
for (final key in _keys)
_button(
key.id,
key.label,
key.material,
key.cupertino,
() => key.send(_terminal),
),
],
);
if (!widget.field) return keys;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Padding(padding: const EdgeInsets.only(bottom: 8), child: _field()),
keys,
],
);
}
Widget _field() {
final toggle = _hidden ? 'Show typing' : 'Hide typing';
if (widget.cupertino) {
return CupertinoTextField(
key: const Key('chat-shell-terminal-field'),
controller: _text,
placeholder: 'Type input, then Enter',
obscureText: _hidden,
autocorrect: false,
enableSuggestions: false,
textInputAction: TextInputAction.send,
onSubmitted: (_) => _submit(),
suffix: CupertinoButton(
key: const Key('chat-shell-terminal-hide'),
padding: const EdgeInsets.symmetric(horizontal: 8),
onPressed: () => setState(() => _hidden = !_hidden),
child: Icon(
_hidden ? CupertinoIcons.eye : CupertinoIcons.eye_slash,
semanticLabel: toggle,
),
),
);
}
return TextField(
key: const Key('chat-shell-terminal-field'),
controller: _text,
obscureText: _hidden,
autocorrect: false,
enableSuggestions: false,
textInputAction: TextInputAction.send,
onSubmitted: (_) => _submit(),
decoration: InputDecoration(
labelText: 'Type input, then Enter',
suffixIcon: IconButton(
key: const Key('chat-shell-terminal-hide'),
tooltip: toggle,
onPressed: () => setState(() => _hidden = !_hidden),
icon: Icon(_hidden ? Icons.visibility : Icons.visibility_off),
),
),
);
}
Widget _button(
String id,
String label,
IconData? material,
IconData? cupertino,
VoidCallback onPressed,
) {
final key = Key('chat-shell-key-$id');
if (widget.cupertino) {
return CupertinoButton(
key: key,
padding: const EdgeInsets.symmetric(horizontal: 8),
onPressed: onPressed,
child: cupertino == null
? Text(label)
: Icon(cupertino, semanticLabel: label),
);
}
if (material == null) {
return OutlinedButton(
key: key,
style: OutlinedButton.styleFrom(visualDensity: VisualDensity.compact),
onPressed: onPressed,
child: Text(label),
);
}
return IconButton.outlined(
key: key,
visualDensity: VisualDensity.compact,
tooltip: label,
onPressed: onPressed,
icon: Icon(material),
);
}
}
@@ -0,0 +1,38 @@
import 'package:xterm/core.dart';
final RegExp _link = RegExp(r'''https?://[^\s<>"'`]+''');
/// The web link drawn at [offset] in [buffer], if any: the operator taps the
/// login URL an auth command printed. A link the terminal wrapped across
/// rows is joined first. Only http and https links are offered.
Uri? chatShellLinkAt(Buffer buffer, CellOffset offset) {
if (offset.y < 0 || offset.y >= buffer.height) return null;
var first = offset.y;
while (first > 0 && buffer.lines[first].isWrapped) {
first--;
}
var last = offset.y;
while (last + 1 < buffer.height && buffer.lines[last + 1].isWrapped) {
last++;
}
final text = StringBuffer();
var tapped = 0;
for (var y = first; y <= last; y++) {
final line = buffer.lines[y];
if (y == offset.y) tapped = text.length + offset.x;
for (var x = 0; x < line.length; x++) {
final code = line.getCodePoint(x);
// One character per cell keeps cell and string positions aligned.
text.write(code == 0 || code > 0xFFFF ? ' ' : String.fromCharCode(code));
}
}
for (final match in _link.allMatches(text.toString())) {
if (tapped < match.start || tapped >= match.end) continue;
final trimmed = match[0]!.replaceFirst(RegExp(r'[.,;:!?)\]}]+$'), '');
if (tapped >= match.start + trimmed.length) return null;
final uri = Uri.tryParse(trimmed);
if (uri == null || uri.host.isEmpty) return null;
return uri;
}
return null;
}
@@ -0,0 +1,98 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/text/monospace.dart';
import 'chat_shell_runs_controller.dart';
import 'chat_shell_terminal_keys.dart';
import 'chat_shell_terminal_view.dart';
/// Opens [runId]'s terminal full screen: the same emulator the card draws,
/// sized to the window (a running process is resized to match), with the key
/// toolbar while it runs. Resolves when the page is closed.
Future<void> openChatShellTerminalPage(
BuildContext context, {
required ChatShellRunsController controller,
required String runId,
required bool cupertino,
}) {
Widget page(BuildContext _) => ChatShellTerminalPage(
controller: controller,
runId: runId,
cupertino: cupertino,
);
return Navigator.of(context).push<void>(
cupertino
? CupertinoPageRoute<void>(builder: page)
: MaterialPageRoute<void>(builder: page),
);
}
class ChatShellTerminalPage extends StatelessWidget {
const ChatShellTerminalPage({
super.key,
required this.controller,
required this.runId,
required this.cupertino,
});
final ChatShellRunsController controller;
final String runId;
final bool cupertino;
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: controller,
builder: (context, _) {
final run = controller.run(runId);
final title = Text(
run == null ? 'Command' : '\$ ${run.command}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontFamily: appMonospaceFamily),
);
Widget body = const SizedBox.shrink();
if (run != null) {
final session = controller.terminals.session(run);
body = SafeArea(
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: ChatShellTerminalView(
session: session,
cupertino: cupertino,
fill: true,
autofocus: true,
),
),
if (session.live)
Padding(
padding: const EdgeInsets.only(top: 8),
child: ChatShellTerminalKeys(
session: session,
cupertino: cupertino,
field: chatShellTouchFirst(),
),
),
],
),
),
);
}
if (cupertino) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(middle: title),
child: body,
);
}
return Scaffold(
appBar: AppBar(title: title),
body: body,
);
},
);
}
}
@@ -0,0 +1,151 @@
import 'package:xterm/core.dart';
import 'chat_shell_run.dart';
/// Lines of scrollback one card's terminal keeps.
const int chatShellTerminalScrollback = 5000;
/// The terminal emulator state of one run: the xterm [terminal] fed with the
/// run's output in order, and the bridge from what the operator types (or
/// the emulator answers) to the running process.
///
/// It keeps no copy of typed input: [Terminal.onOutput] hands each key or
/// paste straight to [onInput], which sends it.
class ChatShellTerminalSession {
ChatShellTerminalSession(
ChatShellRun run, {
required this.onInput,
required this.onResize,
}) : terminal = _ChatShellTerminal() {
// Drawn at the process's own size until a view lays it out at its own.
if (run.cols > 0 && run.rows > 0) terminal.resize(run.cols, run.rows);
terminal.onOutput = _output;
terminal.onResize = (cols, rows, _, _) => onResize(cols, rows);
replay(run);
}
final Terminal terminal;
/// Receives input for the process; only called while the run is live.
final void Function(String data) onInput;
/// Receives the size the view laid the terminal out at.
final void Function(int cols, int rows) onResize;
int _end = 0;
bool _live = false;
bool _replaying = false;
/// The absolute output byte this terminal has drawn up to.
int get end => _end;
/// Whether typing reaches a running process.
bool get live => _live;
/// Draws [run]'s held output from scratch: on open, after a gap and after
/// a readback replaced the card's copy. Answers the emulator gives to old
/// queries in that output are not sent: the process asked them long ago.
void replay(ChatShellRun run) {
_live = run.running && run.terminal;
_replaying = true;
try {
terminal.useMainBuffer();
terminal.buffer.clear();
terminal.buffer.setCursor(0, 0);
terminal.setCursorVisibleMode(true);
terminal.write('\x1b[0m');
if (run.truncated) {
terminal.write('\x1b[2m[earlier output was dropped]\x1b[0m\r\n');
}
var output = _drawable(run, run.output);
// A finished run's final newline would leave an empty line below it.
if (!run.running && output.endsWith('\r\n')) {
output = output.substring(0, output.length - 2);
}
terminal.write(output);
if (!run.running) terminal.setCursorVisibleMode(false);
} finally {
_replaying = false;
}
_end = run.outputEnd;
}
/// Draws one live chunk covering bytes [offset, end) of [run], which
/// already holds it. A chunk after a hole redraws the whole held copy.
void append(ChatShellRun run, String text, int offset, int end) {
if (end <= _end) return;
if (offset != _end) {
replay(run);
return;
}
terminal.write(_drawable(run, text));
_end = end;
}
/// The run ended: nothing typed reaches it any more.
void finish(ChatShellRun run) {
if (!_live) return;
_live = false;
terminal.setCursorVisibleMode(false);
}
/// The rows the drawn output takes, through the cursor's line, when the
/// terminal is [cols] wide: a finished run's box is sized by it before the
/// view lays the terminal out, so a card never changes height after it.
int rowsAt(int cols) {
final buffer = terminal.buffer;
final last = buffer.absoluteCursorY.clamp(0, buffer.height - 1);
var rows = 0;
var length = 0;
void close() => rows += length <= 0 ? 1 : (length + cols - 1) ~/ cols;
for (var y = 0; y <= last; y++) {
final line = buffer.lines[y];
if (y > 0 && !line.isWrapped) {
close();
length = 0;
}
// A row the next one continues is full to the terminal's width.
final continued = y + 1 < buffer.height && buffer.lines[y + 1].isWrapped;
length += continued ? line.length : line.getTrimmedLength();
}
close();
return rows;
}
void _output(String data) {
if (_live && !_replaying) onInput(data);
}
/// Plain-pipe output has bare newlines, which a terminal draws as a line
/// feed without a carriage return.
static String _drawable(ChatShellRun run, String text) =>
run.terminal ? text : text.replaceAll('\n', '\r\n');
}
/// The emulator with the scrollback the cards keep. It answers a cursor
/// position query (DSR 6) with the one-based row and column the protocol
/// specifies; xterm.dart 4.0.0 itself answers zero-based.
class _ChatShellTerminal extends Terminal {
_ChatShellTerminal() : super(maxLines: chatShellTerminalScrollback);
@override
void sendCursorPosition() {
onOutput?.call('\x1b[${buffer.cursorY + 1};${buffer.cursorX + 1}R');
}
/// Narrowing rewraps long lines, and xterm.dart 4.0.0 keeps every blank
/// row below the cursor while doing so: the extra rows push the top of
/// the output into scrollback. Blank rows below the cursor are dropped
/// instead, keeping the cursor on its line.
@override
void resize(int width, int height, [int? pixelWidth, int? pixelHeight]) {
super.resize(width, height, pixelWidth, pixelHeight);
final lines = buffer.lines;
while (buffer.height > viewHeight &&
buffer.height - 1 > buffer.absoluteCursorY &&
lines[buffer.height - 1].getText().trim().isEmpty) {
lines.pop();
buffer.setCursor(buffer.cursorX, buffer.cursorY + 1);
}
}
}
@@ -0,0 +1,88 @@
import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:xterm/xterm.dart';
import '../../../ui/text/monospace.dart';
import '../conversation/chat_card_styles.dart';
/// The terminal's colours from the host theme: the card's inset surface as
/// background, the body text colour as foreground, the accent as cursor and
/// selection. The sixteen ANSI colours are the emulator's standard palette,
/// darkened on a light surface so coloured output stays readable.
TerminalTheme chatShellTerminalTheme(BuildContext context, bool cupertino) {
final brightness = cupertino
? CupertinoTheme.brightnessOf(context)
: Theme.of(context).brightness;
final dark = brightness == Brightness.dark;
final background = chatCardFillColor(context, cupertino);
final foreground = cupertino
? CupertinoColors.label.resolveFrom(context)
: Theme.of(context).colorScheme.onSurface;
final accent = cupertino
? CupertinoTheme.of(context).primaryColor
: Theme.of(context).colorScheme.primary;
final base = TerminalThemes.defaultTheme;
Color ansi(Color color) {
if (dark) return color;
final hsl = HSLColor.fromColor(color);
return hsl.lightness > 0.4 ? hsl.withLightness(0.36).toColor() : color;
}
return TerminalTheme(
cursor: accent,
selection: accent.withValues(alpha: 0.35),
foreground: foreground,
// Opaque: the emulator paints cells over its own background.
background: Color.alphaBlend(
background,
cupertino
? CupertinoColors.systemBackground.resolveFrom(context)
: Theme.of(context).colorScheme.surface,
),
black: dark ? base.black : foreground,
red: ansi(base.red),
green: ansi(base.green),
yellow: ansi(base.yellow),
blue: ansi(base.blue),
magenta: ansi(base.magenta),
cyan: ansi(base.cyan),
white: dark ? base.white : ansi(base.brightBlack),
brightBlack: ansi(base.brightBlack),
brightRed: ansi(base.brightRed),
brightGreen: ansi(base.brightGreen),
brightYellow: ansi(base.brightYellow),
brightBlue: ansi(base.brightBlue),
brightMagenta: ansi(base.brightMagenta),
brightCyan: ansi(base.brightCyan),
brightWhite: dark ? base.brightWhite : foreground,
searchHitBackground: base.searchHitBackground,
searchHitBackgroundCurrent: base.searchHitBackgroundCurrent,
searchHitForeground: base.searchHitForeground,
);
}
/// The terminal's text: the host's monospace family at the card body size.
TerminalStyle chatShellTerminalStyle(BuildContext context, bool cupertino) {
final body = chatCardBodyStyle(context, cupertino) ?? const TextStyle();
return TerminalStyle(
fontFamily: appMonospaceFamily,
fontSize: (body.fontSize ?? 14) * 0.95,
height: 1.3,
);
}
/// The size of one terminal cell in [style] at the context's text scale,
/// measured exactly as the emulator measures it.
Size chatShellTerminalCellSize(BuildContext context, TerminalStyle style) {
final text = style.toTextStyle();
final builder = ui.ParagraphBuilder(text.getParagraphStyle())
..pushStyle(text.getTextStyle(textScaler: MediaQuery.textScalerOf(context)))
..addText('mmmmmmmmmm');
final paragraph = builder.build()
..layout(const ui.ParagraphConstraints(width: double.infinity));
final size = Size(paragraph.maxIntrinsicWidth / 10, paragraph.height);
paragraph.dispose();
return size;
}
@@ -0,0 +1,155 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:xterm/xterm.dart';
import '../conversation/chat_composer_paste_focus.dart';
import '../ui/transcript/chat_link_launcher.dart';
import 'chat_shell_metrics.dart';
import 'chat_shell_terminal_links.dart';
import 'chat_shell_terminal_session.dart';
import 'chat_shell_terminal_theme.dart';
/// Whether the soft keyboard is the main way to type here, so the key
/// toolbar offers a text field: the terminal itself takes hardware keys only.
bool chatShellTouchFirst() =>
defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS;
/// The terminal's own key shortcuts. Cmd-C, Cmd-V and Cmd-A on Apple
/// platforms; elsewhere Ctrl-V (and the terminal convention Ctrl-Shift-V)
/// paste and Ctrl-Shift-C copies, so every other Ctrl key, Ctrl-A and Ctrl-C
/// included, reaches the process.
Map<ShortcutActivator, Intent> chatShellTerminalShortcuts() {
const paste = PasteTextIntent(SelectionChangedCause.keyboard);
final apple =
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS;
if (apple) {
return const {
SingleActivator(LogicalKeyboardKey.keyC, meta: true):
CopySelectionTextIntent.copy,
SingleActivator(LogicalKeyboardKey.keyV, meta: true): paste,
SingleActivator(LogicalKeyboardKey.keyA, meta: true): SelectAllTextIntent(
SelectionChangedCause.keyboard,
),
};
}
return const {
SingleActivator(LogicalKeyboardKey.keyC, control: true, shift: true):
CopySelectionTextIntent.copy,
SingleActivator(LogicalKeyboardKey.keyV, control: true): paste,
SingleActivator(LogicalKeyboardKey.keyV, control: true, shift: true): paste,
};
}
/// One run's terminal emulator view. In a card it is bounded to
/// [kChatShellOutputCollapsedLines] rows (a finished run shrinks to its
/// output); with [fill] it takes the space its parent gives (full screen).
/// It sizes the terminal to its own layout; a running process is resized to
/// match. Tapping a printed web link opens it in the browser.
class ChatShellTerminalView extends StatefulWidget {
const ChatShellTerminalView({
super.key,
required this.session,
required this.cupertino,
this.fill = false,
this.autofocus = false,
this.autoResize = true,
});
final ChatShellTerminalSession session;
final bool cupertino;
final bool fill;
final bool autofocus;
/// False while another view of the same terminal (full screen) sizes it.
final bool autoResize;
@override
State<ChatShellTerminalView> createState() => _ChatShellTerminalViewState();
}
class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
final TerminalController _controller = TerminalController();
final FocusNode _focus = FocusNode(debugLabel: 'chat-shell-terminal');
@override
void initState() {
super.initState();
// A paste while the terminal has focus goes to the process, not to the
// chat composer.
ChatComposerPasteFocus.registerInput(_focus);
}
@override
void dispose() {
ChatComposerPasteFocus.unregisterInput(_focus);
_controller.dispose();
_focus.dispose();
super.dispose();
}
void _tapped(TapUpDetails details, CellOffset offset) {
final uri = chatShellLinkAt(widget.session.terminal.buffer, offset);
if (uri != null) openChatLink(context, uri);
}
@override
Widget build(BuildContext context) {
final session = widget.session;
final live = session.live;
final style = chatShellTerminalStyle(context, widget.cupertino);
const padding = EdgeInsets.all(8);
Widget view = Semantics(
identifier: 'chat-shell-terminal',
label: live ? 'Terminal, type to send input' : 'Terminal output',
child: TerminalView(
session.terminal,
controller: _controller,
focusNode: _focus,
autofocus: widget.autofocus && live,
autoResize: widget.autoResize,
theme: chatShellTerminalTheme(context, widget.cupertino),
textStyle: style,
padding: padding,
readOnly: !live,
// Keys go straight to the process as key events (a focused text
// input would stay closed on the web); touch typing goes through the
// key toolbar's field instead.
hardwareKeyboardOnly: true,
shortcuts: chatShellTerminalShortcuts(),
cursorType: TerminalCursorType.block,
onTapUp: _tapped,
),
);
// The emulator would otherwise inset itself by the window's safe area.
view = MediaQuery.removePadding(
context: context,
removeTop: true,
removeBottom: true,
removeLeft: true,
removeRight: true,
child: view,
);
view = ClipRRect(borderRadius: BorderRadius.circular(8), child: view);
if (widget.fill) return view;
final cell = chatShellTerminalCellSize(context, style);
return LayoutBuilder(
builder: (context, constraints) {
// A finished run's box fits the rows its output takes at this width.
final cols = ((constraints.maxWidth - padding.horizontal) / cell.width)
.floor()
.clamp(1, 1000);
final rows = live
? kChatShellOutputCollapsedLines
: session.rowsAt(cols).clamp(1, kChatShellOutputCollapsedLines);
// A pixel of slack keeps rounding from losing the last row.
return SizedBox(
height: rows * cell.height + padding.vertical + 1,
child: view,
);
},
);
}
}
@@ -0,0 +1,142 @@
import 'dart:async';
import 'chat_shell_run.dart';
import 'chat_shell_runs_repository.dart';
import 'chat_shell_terminal_session.dart';
/// UTF-16 units of typed or pasted text one `chat_shell_input` carries: at
/// most 12 KiB of UTF-8, inside the server's 16 KiB bound.
const int chatShellInputChunk = 4096;
/// How long a view's size settles before the process is resized.
const Duration chatShellResizeDelay = Duration(milliseconds: 150);
/// The terminal emulators of one chat's runs, kept outside the cards so a
/// card scrolled out of the transcript (or opened full screen) draws the same
/// state, and the delivery of typed input and sizes to the server.
class ChatShellTerminals {
ChatShellTerminals(
this._repository,
this._sessionId, {
required this.onError,
});
final ChatShellRunsRepository _repository;
final String _sessionId;
/// Reports a refused input or resize of a run, in the server's words.
final void Function(String runId, Object error) onError;
final Map<String, ChatShellTerminalSession> _sessions = {};
final Map<String, _InputPipe> _inputs = {};
final Map<String, Timer> _resizes = {};
final Map<String, (int, int)> _sentSizes = {};
bool _disposed = false;
/// The size a view last laid a terminal out at: new runs start at it, so
/// their first output already fits the reading column.
(int, int)? lastSize;
/// The emulator of [run], created (and fed its held output) on first use.
ChatShellTerminalSession session(ChatShellRun run) => _sessions.putIfAbsent(
run.id,
() => ChatShellTerminalSession(
run,
onInput: (data) => _input(run.id, data),
onResize: (cols, rows) => _resized(run.id, cols, rows),
),
);
/// The card's copy of [run] was replaced (readback, gap): redraw it.
void replaced(ChatShellRun run) => _sessions[run.id]?.replay(run);
/// [run] now holds one more live chunk.
void appended(ChatShellRun run, String text, int offset, int end) =>
_sessions[run.id]?.append(run, text, offset, end);
/// [run] ended: draw its final output read-only.
void finished(ChatShellRun run) {
_resizes.remove(run.id)?.cancel();
_inputs.remove(run.id);
_sessions[run.id]?.replay(run);
}
void _input(String runId, String data) {
if (_disposed) return;
_inputs
.putIfAbsent(
runId,
() => _InputPipe(
(data) => _repository.input(_sessionId, runId, data),
(error) => onError(runId, error),
),
)
.add(data);
}
void _resized(String runId, int cols, int rows) {
lastSize = (cols, rows);
if (_disposed || !(_sessions[runId]?.live ?? false)) return;
_resizes.remove(runId)?.cancel();
_resizes[runId] = Timer(chatShellResizeDelay, () {
_resizes.remove(runId);
if (_sentSizes[runId] == (cols, rows)) return;
_sentSizes[runId] = (cols, rows);
_repository
.resize(_sessionId, runId, cols, rows)
.catchError((Object error) => onError(runId, error));
});
}
void dispose() {
_disposed = true;
for (final timer in _resizes.values) {
timer.cancel();
}
_resizes.clear();
_inputs.clear();
}
}
/// One run's typed input on its way to the server, in order: what arrives
/// while a request is in flight goes in the next one. Nothing is kept once
/// sent, and a refusal discards what was waiting rather than retyping it.
class _InputPipe {
_InputPipe(this._send, this._failed);
final Future<void> Function(String data) _send;
final void Function(Object error) _failed;
final StringBuffer _pending = StringBuffer();
bool _busy = false;
void add(String data) {
_pending.write(data);
if (!_busy) unawaited(_pump());
}
Future<void> _pump() async {
_busy = true;
try {
while (_pending.isNotEmpty) {
var waiting = _pending.toString();
_pending.clear();
var cut = waiting.length;
if (cut > chatShellInputChunk) {
cut = chatShellInputChunk;
// Never split a surrogate pair across two requests.
final unit = waiting.codeUnitAt(cut - 1);
if (unit >= 0xD800 && unit <= 0xDBFF) cut--;
_pending.write(waiting.substring(cut));
}
final chunk = waiting.substring(0, cut);
waiting = '';
await _send(chunk);
}
} catch (error) {
_pending.clear();
_failed(error);
} finally {
_busy = false;
}
}
}