From 6f581188d95fb69b79700bbf73cf9fc3c7f658bf Mon Sep 17 00:00:00 2001 From: leo Date: Tue, 24 Nov 2026 23:20:09 +0800 Subject: [PATCH] feat(chat): run a stopped or failed last turn again The last turn, stopped or ended on an error, has a button beside its copy and fork ones (Run this turn again): the conversation goes back to its message and sends it again as it was, as an unchanged edit would, without a "continue" message of the user's in between. The model can be changed first. As with an edit, the user is asked whether the files the turn changed go back. Fixes #1251 Co-Authored-By: BaoCode --- lib/chat/chat_history_view.dart | 53 ++++++++++++++ lib/chat/widgets/turn_footer.dart | 48 ++++++++++++- lib/l10n/app_en.arb | 1 + lib/l10n/app_localizations.dart | 6 ++ lib/l10n/app_localizations_en.dart | 3 + lib/l10n/app_localizations_zh.dart | 3 + lib/l10n/app_zh.arb | 1 + test/chat/retry_turn_test.dart | 108 +++++++++++++++++++++++++++++ 8 files changed, 220 insertions(+), 3 deletions(-) create mode 100644 test/chat/retry_turn_test.dart diff --git a/lib/chat/chat_history_view.dart b/lib/chat/chat_history_view.dart index 39393a702..aa79f0aad 100644 --- a/lib/chat/chat_history_view.dart +++ b/lib/chat/chat_history_view.dart @@ -368,6 +368,9 @@ class _ChatHistoryViewState extends State } return TurnFooter( answer: words.isEmpty ? null : words.join('\n\n'), + onRetry: _canRetry(prompt, index) + ? () => unawaited(_retryTurn(prompt)) + : null, onFork: widget.forkAfter?.call(index), worked: message.worked, usage: message.usage, @@ -375,6 +378,56 @@ class _ChatHistoryViewState extends State ); } + /// Whether the turn begun by the message at [prompt] and ending at + /// [index] can be run again ([_retryTurn]): the conversation's last, done + /// with, stopped or ended on an error (#1251). + bool _canRetry(int prompt, int index) { + final feed = _feed; + if (feed is! ChatSession || !feed.canEditMessages || feed.isStreaming) { + return false; + } + for (var i = index + 1; i < feed.itemCount; i++) { + if (feed.itemAt(i) is UserMessageItem) return false; + } + if (feed.lastTurnInterrupted) return true; + for (var i = prompt + 1; i <= index; i++) { + if (feed.itemAt(i) case NoticeItem(kind: NoticeKind.error)) return true; + } + return false; + } + + /// Runs the turn begun by the message at [prompt] again, the message as + /// sent: as if edited and sent unchanged, without a message to say go on. + Future _retryTurn(int prompt) async { + final feed = _feed; + if (feed is! ChatSession || _askingRewind) return; + final message = feed.itemAt(prompt); + if (message is! UserMessageItem) return; + _askingRewind = true; + final bool? revertFiles; + try { + revertFiles = await askRewindFiles( + context, + () => feed.rewindPlanAt(prompt), + ); + } finally { + _askingRewind = false; + } + if (revertFiles == null || !mounted || feed.isStreaming) return; + setState(() { + // Everything after the message is replaced; so are its steps. + _expanded.removeWhere((i, _) => i > prompt); + _foldOpen.removeWhere((key, _) => key.$2 > prompt); + _unfoldedTurns.clear(); + }); + feed.editMessage( + prompt, + ComposerMessage(text: message.text, images: message.images), + from: UserPlace.computer, + revertFiles: revertFiles, + ); + } + /// Under the status row of the turn under way, the last of all, whether /// the row shows or not: how fast the model writes, how long the turn /// has taken, and the tokens so far. diff --git a/lib/chat/widgets/turn_footer.dart b/lib/chat/widgets/turn_footer.dart index 79ff051ea..55e922f6a 100644 --- a/lib/chat/widgets/turn_footer.dart +++ b/lib/chat/widgets/turn_footer.dart @@ -7,6 +7,7 @@ import 'package:flutter_svg/flutter_svg.dart'; import '../../ide/ide_hover.dart'; import '../../l10n/l10n.dart'; import '../../theme/app_theme.dart'; +import '../../theme/codicons.dart'; import '../../usage/usage_prices.dart'; import '../chat_models.dart'; import 'agent_step.dart'; @@ -38,8 +39,9 @@ abstract final class LiveTurnStatsSetting { static Listenable? changes; } -/// Under a finished turn: a button to copy its answer and one to fork the -/// conversation from there, then, faint, how long the turn took, how fast +/// Under a finished turn: a button to copy its answer, one to run it again +/// (the last, stopped or failed) and one to fork the conversation from +/// there, then, faint, how long the turn took, how fast /// the model wrote, what it cost and the tokens it used, as far as known. /// Out of the history's selection. /// @@ -53,6 +55,7 @@ class TurnFooter extends StatelessWidget { const TurnFooter({ super.key, this.answer, + this.onRetry, this.onFork, this.worked, this.usage, @@ -64,6 +67,10 @@ class TurnFooter extends StatelessWidget { /// What the copy button copies; no button when null. final String? answer; + /// Runs the turn again from its message, as sent (#1251): the last turn, + /// stopped or failed, perhaps on another model now; no button when null. + final VoidCallback? onRetry; + /// Copies the conversation up to the end of this turn into a new one; /// no button when null. final VoidCallback? onFork; @@ -96,16 +103,18 @@ class TurnFooter extends StatelessWidget { final l10n = context.l10n; final live = this.live; if (live == null) { + final onRetry = this.onRetry; final onFork = this.onFork; return _padded( _line([ - if (answer != null || onFork != null) + if (answer != null || onRetry != null || onFork != null) Row( mainAxisSize: MainAxisSize.min, spacing: 2, children: [ if (answer case final answer?) CopyButton(text: answer, tooltip: l10n.turnCopy), + if (onRetry != null) _RetryButton(onTap: onRetry), if (onFork != null) _ForkButton(onTap: onFork), ], ), @@ -304,6 +313,39 @@ class _ForkButton extends StatelessWidget { } } +/// A faint icon beside the copy button, as the fork's: runs the turn again. +class _RetryButton extends StatelessWidget { + const _RetryButton({required this.onTap}); + + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + return IdeHover( + message: context.l10n.turnRetry, + child: HoverBuilder( + cursor: SystemMouseCursors.click, + builder: (context, hovered) => GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.all(3), + decoration: BoxDecoration( + color: hovered ? AppColors.hover : null, + borderRadius: BorderRadius.circular(4), + ), + child: Icon( + Codicons.refresh, + size: 13, + color: hovered ? AppColors.text : AppColors.textFaint, + ), + ), + ), + ), + ); + } +} + class _Stat extends StatelessWidget { const _Stat({ this.icon, diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 7b0e9f55e..4fd974d60 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1611,6 +1611,7 @@ "description": "Hint of the button at the end of a finished turn that copies its answer." }, "turnFork": "Fork from here", + "turnRetry": "Run this turn again", "@turnFork": { "description": "Hint of the button at the end of a finished turn that copies the conversation up to there into a new one." }, diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 1ab0e2f0f..799d7dbaa 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -4742,6 +4742,12 @@ abstract class AppLocalizations { /// **'Fork from here'** String get turnFork; + /// No description provided for @turnRetry. + /// + /// In en, this message translates to: + /// **'Run this turn again'** + String get turnRetry; + /// No description provided for @turnCopied. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 8ae0ba084..7a5d4927f 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -2739,6 +2739,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get turnFork => 'Fork from here'; + @override + String get turnRetry => 'Run this turn again'; + @override String get turnCopied => 'Copied'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 1a2b606db..5b20d0351 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -2644,6 +2644,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get turnFork => '从这里 Fork'; + @override + String get turnRetry => '重试本轮'; + @override String get turnCopied => '已复制'; diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index d8e7f5937..4e01db0d9 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -774,6 +774,7 @@ "stepsThought": "思考 {duration}", "turnCopy": "复制回复", "turnFork": "从这里 Fork", + "turnRetry": "重试本轮", "turnCopied": "已复制", "turnSpeed": "{speed} tok/s", "turnTokens": "{tokens} tokens", diff --git a/test/chat/retry_turn_test.dart b/test/chat/retry_turn_test.dart new file mode 100644 index 000000000..874eafda0 --- /dev/null +++ b/test/chat/retry_turn_test.dart @@ -0,0 +1,108 @@ +import 'package:baocode/chat/chat_models.dart'; +import 'package:baocode/chat/chat_screen.dart'; +import 'package:baocode/chat/chat_session.dart'; +import 'package:baocode/ide/ide_hover.dart'; +import 'package:baocode/kernel/agent_kernel.dart'; +import 'package:baocode/kernel/claude_code/claude_code_kernel.dart'; +import 'package:baocode/theme/app_theme.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../kernel_test.dart' show FakeCli; + +Finder _retry() => find.byWidgetPredicate( + (widget) => widget is IdeHover && widget.message == 'Run this turn again', +); + +List _said(ChatSession session) => [ + for (var i = 0; i < session.itemCount; i++) + if (session.itemAt(i) case UserMessageItem(:final text)) text, +]; + +void main() { + testWidgets('a stopped last turn runs again from its message, no message ' + 'to say go on (#1251)', (tester) async { + tester.view.physicalSize = const Size(1000, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final cli = FakeCli( + answers: { + 'rewind_conversation': {'rewound': true}, + }, + ); + late final KernelDescriptor descriptor; + descriptor = KernelDescriptor( + id: 'claude-code', + label: 'Claude Code', + icon: Icons.auto_awesome_rounded, + description: '', + create: (context) => + ClaudeCodeKernel(descriptor, context, start: (_) async => cli), + ); + final session = ChatSession( + kernel: descriptor, + kernels: [descriptor], + historyCount: 0, + ); + addTearDown(session.dispose); + await tester.pumpWidget( + MaterialApp( + theme: buildAppTheme(), + home: ChatScreen(session: session, embedded: true), + ), + ); + await tester.pump(); + + // A turn done: nothing to run again. + session.send(const ComposerMessage(text: 'first')); + await tester.pump(const Duration(milliseconds: 100)); + cli.push({ + 'type': 'assistant', + 'message': { + 'id': 'reply-1', + 'role': 'assistant', + 'content': [ + {'type': 'text', 'text': 'Done.'}, + ], + }, + }); + cli.push({ + 'type': 'result', + 'subtype': 'success', + 'is_error': false, + 'session_id': 's', + }); + await tester.pumpAndSettle(); + expect(_retry(), findsNothing); + + // The next stopped half way: it can run again. + session.send(const ComposerMessage(text: 'second')); + await tester.pump(const Duration(milliseconds: 100)); + cli.push({ + 'type': 'assistant', + 'message': { + 'id': 'reply-2', + 'role': 'assistant', + 'content': [ + {'type': 'text', 'text': 'Working on it'}, + ], + }, + }); + await tester.pump(); + session.stop(); + await tester.pumpAndSettle(); + expect(session.lastTurnInterrupted, isTrue); + expect(_retry(), findsOneWidget); + + final second = cli.users.last['uuid']; + await tester.tap(_retry()); + await tester.pumpAndSettle(); + final request = cli.requests('rewind_conversation').single; + expect(request['target_message_uuid'], second); + expect(_said(session), ['first', 'second']); + expect(cli.users, hasLength(3)); + final resent = (cli.users.last['message'] as Map)['content']; + expect('$resent', contains('second')); + await tester.pumpWidget(const SizedBox()); + }); +}