Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions lib/chat/chat_history_view.dart
Original file line number Diff line number Diff line change
Expand Up @@ -368,13 +368,66 @@ class _ChatHistoryViewState extends State<ChatHistoryView>
}
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,
cost: _turnCosts[prompt],
);
}

/// 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<void> _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.
Expand Down
48 changes: 45 additions & 3 deletions lib/chat/widgets/turn_footer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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.
///
Expand All @@ -53,6 +55,7 @@ class TurnFooter extends StatelessWidget {
const TurnFooter({
super.key,
this.answer,
this.onRetry,
this.onFork,
this.worked,
this.usage,
Expand All @@ -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;
Expand Down Expand Up @@ -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),
],
),
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions lib/l10n/app_en.arb
Original file line number Diff line number Diff line change
Expand Up @@ -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."
},
Expand Down
6 changes: 6 additions & 0 deletions lib/l10n/app_localizations.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 3 additions & 0 deletions lib/l10n/app_localizations_en.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down
3 changes: 3 additions & 0 deletions lib/l10n/app_localizations_zh.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2644,6 +2644,9 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get turnFork => '从这里 Fork';

@override
String get turnRetry => '重试本轮';

@override
String get turnCopied => '已复制';

Expand Down
1 change: 1 addition & 0 deletions lib/l10n/app_zh.arb
Original file line number Diff line number Diff line change
Expand Up @@ -774,6 +774,7 @@
"stepsThought": "思考 {duration}",
"turnCopy": "复制回复",
"turnFork": "从这里 Fork",
"turnRetry": "重试本轮",
"turnCopied": "已复制",
"turnSpeed": "{speed} tok/s",
"turnTokens": "{tokens} tokens",
Expand Down
108 changes: 108 additions & 0 deletions test/chat/retry_turn_test.dart
Original file line number Diff line number Diff line change
@@ -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<String> _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());
});
}