Files
lingjhf 06f1c26681
Gitea CI / Assemble and validate CI artifacts (push) Successful in 1m47s
Gitea CI / Check code and tests (push) Successful in 7m15s
Gitea CI / Build Android APK (push) Successful in 4m6s
Gitea CI / Build Windows x64 app (push) Successful in 3m34s
Gitea CI / Audit and package Windows x64 (push) Successful in 1m29s
Gitea CI / Gitea CI passed (push) Successful in 1s
Gitea Release / Prepare draft Release (push) Failing after 8s
Gitea Release / Upload Android to draft Release (push) Skipped
Gitea Release / Upload Windows to draft Release (push) Skipped
Gitea Release / Verify and publish Release (push) Skipped
Move editor UI into the app and release verified Core dependencies (#14)
2026-10-11 19:59:40 +00:00

1048 lines
54 KiB
Dart

import 'agent_reply_region.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import '../../shared/layout/composer_layout.dart';
import '../../shared/theme/composer_style.dart';
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_core/project.dart';
import '../../integrations/platform/platform_capabilities.dart';
import 'agent_composer_controller.dart';
import 'agent_attachment_drop_region.dart';
import 'agent_chat_actions.dart';
import 'agent_composer_store.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/agent/agent_provider.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../settings/settings_page.dart';
import 'chat_controller.dart';
import 'chat_state.dart';
import '../../integrations/agent/conversation_repository.dart';
import '../../workspace/external_media_import.dart';
import '../../settings/settings_operation.dart';
import '../../workspace/projects.dart';
import '../media/media_browser_feedback.dart';
import 'agent_attachment_card.dart';
import 'agent_media_attachments.dart';
import 'agent_message_codec.dart';
import 'breakable_selectable_text.dart';
import 'composer_document.dart';
import 'composer_reference_validator.dart';
import 'composer_suggestion_surface.dart';
const _userTurnGap = 56.0;
const _replyTurnGap = 48.0;
String _elapsedLabel(BuildContext context, int elapsedMs) {
final totalSeconds = ((elapsedMs + 999) ~/ 1000).clamp(1, 86400000);
final minutes = totalSeconds ~/ 60;
final seconds = totalSeconds % 60;
final duration = minutes == 0
? context.l10n.durationSeconds(totalSeconds)
: context.l10n.durationMinutesSeconds(minutes, seconds);
return context.l10n.agentElapsedTime(duration);
}
class AgentChatPanel extends ConsumerStatefulWidget {
const AgentChatPanel({
super.key,
this.projectId,
this.timelineId,
this.projectSelector,
this.inputController,
this.composer,
this.conversationId,
this.draftKey,
this.onConversationCreated,
this.onConversationUpdated,
this.composerColor,
});
final String? projectId;
final String? timelineId;
final Widget? projectSelector;
final ComposerDocumentController? inputController;
final AgentComposerController? composer;
final String? conversationId;
final String? draftKey;
final Color? composerColor;
final ValueChanged<ConversationMetadata>? onConversationCreated;
final ValueChanged<ConversationMetadata>? onConversationUpdated;
@override
ConsumerState<AgentChatPanel> createState() => _AgentChatPanelState();
}
class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
late final ComposerDocumentController _input =
widget.inputController ?? ComposerDocumentController();
final _scroll = ScrollController();
final _inputScroll = ScrollController();
final _footerKey = GlobalKey();
double _footerHeight = 0;
bool _footerMeasureScheduled = false;
bool _inputOverflows = false;
bool _follow = true;
String get _modelOperation =>
'agent-model-${widget.projectId}-${widget.conversationId ?? widget.draftKey ?? 'new'}';
bool get _choosingModel =>
ref.read(settingsOperationProvider(_modelOperation)).isLoading;
bool get _usingDraftModel => _composer.usingDraftModel;
bool get _importingAttachments =>
_composer.busy ||
widget.projectId != null &&
ref.read(externalMediaImportProvider(widget.projectId!)).isLoading;
late AgentComposerController _composer;
List<AgentMediaAttachment> get _attachments => _composer.attachments;
AgentComposerController _resolveComposer() =>
widget.composer ??
ref
.read(agentComposerStoreProvider)
.composer(
widget.projectId,
widget.conversationId ?? widget.draftKey ?? 'new',
);
void _composerChanged() {
if (mounted) setState(() {});
}
void _scheduleFooterMeasure() {
if (_footerMeasureScheduled) return;
_footerMeasureScheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_footerMeasureScheduled = false;
if (!mounted) return;
final height = _footerKey.currentContext?.size?.height ?? 0;
if ((_footerHeight - height).abs() > 0.5) {
setState(() => _footerHeight = height);
if (_follow) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _scroll.hasClients) {
_scroll.jumpTo(_scroll.position.maxScrollExtent);
}
});
}
}
});
}
@override
void didUpdateWidget(covariant AgentChatPanel oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.conversationId != widget.conversationId ||
oldWidget.projectId != widget.projectId ||
oldWidget.draftKey != widget.draftKey) {
_composer.removeListener(_composerChanged);
_composer = _resolveComposer();
_composer.addListener(_composerChanged);
}
}
@override
void initState() {
super.initState();
_composer = _resolveComposer();
_composer.addListener(_composerChanged);
_scroll.addListener(() {
_follow = _scroll.position.extentAfter < 80;
});
}
@override
void dispose() {
_composer.removeListener(_composerChanged);
if (widget.inputController == null) _input.dispose();
_scroll.dispose();
_inputScroll.dispose();
super.dispose();
}
Future<void> _pickAttachments() async {
try {
await _composer.pickAttachments();
} catch (_) {
// Feedback belongs to the composer even if this panel is hidden.
}
}
@override
Widget build(BuildContext context) {
ref.watch(
settingsOperationProvider(_modelOperation)
.select((value) => value.isLoading),
);
if (widget.projectId != null) {
ref.watch(
externalMediaImportProvider(widget.projectId!)
.select((value) => value.isLoading),
);
}
final workspace = ref.watch(
projectsProvider.select(
(value) => value.asData?.value.copyWith(
recent: const [],
error: null,
creatingTimeline: false,
),
),
);
final referenceValidator = ComposerReferenceValidator(
workspace: workspace,
projectId: widget.projectId,
);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
referenceValidator.validate(_input);
});
final provider = widget.projectId != null
? chatControllerProvider(
widget.projectId!,
conversationId: widget.conversationId,
draftKey: widget.draftKey,
)
: null;
final state = provider == null
? const ChatState()
: ref.watch(provider.select(chatChrome));
final settings = ref.watch(agentSettingsProvider).asData?.value;
final available =
settings?.providers
.where(
(item) =>
item.enabled &&
AgentApiType.values.any(
(type) => type.name == item.apiType,
) &&
item.models.isNotEmpty,
)
.toList() ??
const <AgentProviderSettings>[];
final conversation = state.conversation;
final showProjectSelector =
widget.projectSelector != null &&
widget.conversationId == null &&
conversation == null &&
state.messages.isEmpty &&
!state.busy;
final providerId = conversation?.providerId ?? settings?.selectedProviderId;
final modelId = conversation?.modelId ?? settings?.selectedModelId;
final selectedProvider = available
.where((item) => item.id == providerId)
.firstOrNull;
final selectedModel = selectedProvider?.models
.where((item) => item.id == modelId)
.firstOrNull;
final usingExisting =
conversation != null ||
(widget.conversationId != null && !_usingDraftModel);
final configured = usingExisting
? conversation != null &&
settings?.enabled == true &&
selectedModel != null
: ref.watch(agentRuntimeProvider).asData?.value != null;
Future<void> chooseModel(String providerId, String modelId) async {
if (_choosingModel || state.busy) return;
final saved = await ref
.read(settingsOperationProvider(_modelOperation).notifier)
.run(() async {
if (provider == null) {
await ref
.read(agentSettingsProvider.notifier)
.selectModel(providerId, modelId);
} else {
await ref
.read(provider.notifier)
.selectModel(providerId, modelId);
}
});
if (!mounted || !context.mounted) return;
if (saved) {
_composer.useDraftModel();
} else {
ErrorNotificationHost.of(context).show(
ErrorNotification(
content: Text(context.l10n.agentSaveSettingsFailed),
),
);
}
}
final compactButtonStyle = AppComposerStyle.controlButton(context);
final compactIconStyle = AppComposerStyle.controlIcon(context);
Widget modelPicker() {
if (available.isEmpty) {
return TextButton.icon(
key: const Key('agent-configure-model'),
style: compactButtonStyle,
onPressed: () => showSettingsPage(context, initialTab: 1),
icon: const Icon(AppIcons.tune, size: 16),
label: Text(context.l10n.agentConfigureModel),
);
}
return AppDropdownMenu(
minWidth: 220,
maxHeight: 320,
items: [
if (usingExisting) AppMenuLabel(context.l10n.agentModelChangeSession),
for (final item in available) ...[
AppMenuLabel(item.name),
for (final model in item.models)
AppMenuItem(
label: model.id,
selectOption: true,
selected: item.id == providerId && model.id == modelId,
onPressed: () => chooseModel(item.id, model.id),
),
],
const Divider(height: 1),
AppMenuItem(
label: context.l10n.agentConfigureModel,
selectOption: true,
onPressed: () => showSettingsPage(context, initialTab: 1),
),
],
builder: (context, toggle, focus) => AppToolbarDropdownButton(
buttonKey: const Key('agent-model-picker'),
focusNode: focus,
onPressed: () {
if (!state.busy && !_choosingModel) toggle?.call();
},
style: compactButtonStyle,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Text(
selectedModel?.id ?? context.l10n.agentSelectModel,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 4),
const Icon(AppIcons.expandMore, size: 14),
],
),
),
);
}
if (provider != null && TickerMode.valuesOf(context).enabled) {
ref.listen(provider, (previous, next) {
if (_follow) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _scroll.hasClients) {
_scroll.jumpTo(_scroll.position.maxScrollExtent);
}
});
}
});
}
void send() {
referenceValidator.validate(_input);
if (provider == null ||
widget.timelineId == null ||
!configured ||
_choosingModel ||
state.busy ||
_importingAttachments ||
_input.hasInvalidReferences ||
(_input.text.trim().isEmpty && _attachments.isEmpty)) {
return;
}
final text = takeAgentDraft(_input, _composer);
_follow = true;
ref
.read(provider.notifier)
.send(
text,
timelineId: widget.timelineId!,
onCreated: widget.onConversationCreated,
onUpdated: widget.onConversationUpdated,
);
}
final theme = Theme.of(context);
final content = AgentAttachmentDropRegion(
projectId: widget.projectId,
composer: _composer,
child: LayoutBuilder(
builder: (context, constraints) {
final panelWidth =
(constraints.maxWidth - ComposerLayout.horizontalInset * 2)
.clamp(0.0, ComposerLayout.maxWidth)
.toDouble();
_scheduleFooterMeasure();
final footerInset =
_footerHeight + ComposerLayout.bottomInset + AppSpacing.small;
return Stack(
children: [
Positioned.fill(
child: Scrollbar(
key: const Key('agent-conversation-scrollbar'),
controller: _scroll,
notificationPredicate: (notification) =>
notification.depth == 0 &&
notification.context
?.findAncestorWidgetOfExactType<
ScrollEdgeFade
>() !=
null,
child: SizedBox(
key: const Key('agent-conversation'),
child: state.messages.isEmpty
? const SizedBox.expand()
: ScrollEdgeFade(
controller: _scroll,
bottomInset: footerInset,
child: ScrollConfiguration(
behavior: const _NoAutomaticScrollbarBehavior(),
child: ListView(
controller: _scroll,
padding: EdgeInsets.only(bottom: footerInset),
children: [
Center(
child: SizedBox(
key: const Key(
'agent-conversation-content',
),
width: panelWidth,
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: AppSpacing.compact,
),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.stretch,
children: [
for (final message
in state.messages)
Padding(
padding: EdgeInsets.only(
bottom: message.isUser
? _userTurnGap
: _replyTurnGap,
),
child: Column(
crossAxisAlignment:
message.isUser
? CrossAxisAlignment.end
: CrossAxisAlignment
.start,
children: [
if (!message.isUser) ...[
if (message.elapsedMs
case final elapsed?)
Padding(
padding:
const EdgeInsets.only(
bottom:
AppSpacing
.tiny,
),
child: Row(
mainAxisSize:
MainAxisSize
.min,
children: [
Text(
_elapsedLabel(
context,
elapsed,
),
style:
AppTheme.chatMetaTextStyle(
context,
),
),
Icon(
AppIcons
.chevronRight,
size: 14,
color:
AppTheme.chatMetaTextStyle(
context,
).color,
),
],
),
),
Divider(
height: 1,
color:
theme.dividerColor,
),
const SizedBox(
height:
AppSpacing.medium,
),
],
if (AgentComposerMessage.decode(
message.text,
).text.isNotEmpty)
if (message.isUser)
Container(
decoration:
AppTheme.userMessageDecoration(
context,
),
padding: const EdgeInsets.symmetric(
horizontal:
AppSpacing
.medium,
vertical: AppSpacing
.itemVertical,
),
child: BreakableSelectableText(
text:
AgentComposerMessage.decode(
message.text,
).text,
style:
AppTheme.chatMessageTextStyle(
context,
),
),
)
else
SelectableText(
message.text,
style:
AppTheme.chatMessageTextStyle(
context,
),
),
if (message.isUser &&
AgentComposerMessage.decode(
message.text,
)
.attachments
.isNotEmpty)
Padding(
padding:
const EdgeInsets.only(
top: 8,
),
child: Wrap(
spacing: 8,
runSpacing: 8,
alignment:
WrapAlignment.end,
children: [
for (final attachment
in AgentComposerMessage.decode(
message.text,
).attachments)
Consumer(
builder: (context, ref, _) {
final asset = ref.watch(
projectsProvider.select(
(
value,
) => value
.asData
?.value
.assets
.where(
(
asset,
) =>
asset.id ==
attachment.id,
)
.firstOrNull,
),
);
return asset ==
null
? Chip(
label: Text(
attachment.name,
),
)
: AgentAttachmentCard(
asset:
asset,
);
},
),
],
),
),
if (message.interrupted)
Text(
context
.l10n
.replyInterrupted,
style: theme
.textTheme
.bodySmall,
),
],
),
),
AgentReplyRegion(
projectId: widget.projectId,
conversationId:
widget.conversationId,
draftKey: widget.draftKey,
),
],
),
),
),
),
],
),
),
),
),
),
),
Positioned(
left: ComposerLayout.horizontalInset,
right: ComposerLayout.horizontalInset,
bottom: ComposerLayout.bottomInset,
child: NotificationListener<SizeChangedLayoutNotification>(
onNotification: (_) {
_scheduleFooterMeasure();
return false;
},
child: SizeChangedLayoutNotifier(
key: _footerKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (state.error case final error?)
Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.compact,
),
child: Text(
agentChatErrorMessage(context, error),
style: theme.textTheme.bodySmall,
),
),
if ({
AgentChatError.recoveryRequired,
AgentChatError.interrupted,
AgentChatError.turnLimit,
}.contains(state.error))
TextButton(
onPressed: state.busy || widget.timelineId == null
? null
: () => ref
.read(provider!.notifier)
.send(
context.l10n.agentResumeTask,
timelineId: widget.timelineId!,
resumeOnly: true,
onUpdated: widget.onConversationUpdated,
),
child: Text(context.l10n.agentResumeTask),
),
if (state.error == AgentChatError.exportReplyFailed)
TextButton(
onPressed: state.busy || widget.timelineId == null
? null
: () => ref
.read(provider!.notifier)
.send(
context.l10n.agentRetrySummary,
timelineId: widget.timelineId!,
summaryOnly: true,
onUpdated: widget.onConversationUpdated,
),
child: Text(context.l10n.agentRetrySummary),
),
if (usingExisting &&
!configured &&
conversation != null)
Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.compact,
),
child: Text(
context.l10n.agentModelUnavailable,
style: theme.textTheme.bodySmall,
),
),
Align(
alignment: Alignment.bottomCenter,
child: SizedBox(
width: panelWidth,
child: Stack(
children: [
if (showProjectSelector)
Positioned(
top: ComposerLayout.utilityTopGap,
left: ComposerLayout.utilityInset,
right: ComposerLayout.utilityInset,
child: widget.projectSelector!,
),
Padding(
padding: EdgeInsets.only(
top: !showProjectSelector
? AppSpacing.small
: ComposerLayout.composerTopWithUtility,
),
child: Align(
alignment: Alignment.bottomCenter,
child: SizedBox(
width: panelWidth,
child: ComposerSuggestionSurface(
controller: _input,
width: panelWidth,
projectId: workspace?.activeProject?.id,
assets:
workspace?.assets ??
const <AssetDocument>[],
timelines:
workspace?.timelines ??
const <TimelineSummary>[],
onSend: send,
builder: (context, inputFocus) => Card(
key: const Key('agent-composer'),
color:
widget.composerColor ??
AppSurfaces.of(context)
.composerBackground,
margin: EdgeInsets.zero,
elevation: 0,
surfaceTintColor: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
ComposerLayout.radius,
),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_attachments.isNotEmpty)
SizedBox(
height: 138,
child: ListView.separated(
key: const Key(
'agent-composer-attachments',
),
scrollDirection:
Axis.horizontal,
padding:
const EdgeInsets.fromLTRB(
12,
12,
12,
4,
),
itemCount:
_attachments.length,
separatorBuilder: (_, _) =>
const SizedBox(
width: 8,
),
itemBuilder: (context, index) {
final attachment =
_attachments[index];
final asset = ref
.watch(
projectsProvider,
)
.asData
?.value
.assets
.where(
(item) =>
item.id ==
attachment.id,
)
.firstOrNull;
if (asset == null) {
return const SizedBox.shrink();
}
return AgentAttachmentCard(
key: Key(
'agent-attachment-${asset.id}',
),
asset: asset,
onRemove: () =>
_composer.remove(
asset.id,
),
);
},
),
),
ConstrainedBox(
// Leave room for messages and composer actions when this
// panel shares a short window with the timeline.
constraints: BoxConstraints(
maxHeight:
(constraints.maxHeight *
ComposerLayout
.inputMaxHeightFraction)
.clamp(
ComposerLayout
.inputMinHeight,
double.infinity,
),
),
child: NotificationListener<ScrollMetricsNotification>(
onNotification: (_) {
WidgetsBinding.instance
.addPostFrameCallback((
_,
) {
if (!mounted ||
!_inputScroll
.hasClients) {
return;
}
final overflows =
_inputScroll
.position
.maxScrollExtent >
0;
if (overflows !=
_inputOverflows) {
setState(
() =>
_inputOverflows =
overflows,
);
}
});
return false;
},
child: Scrollbar(
key: const Key(
'agent-input-scrollbar',
),
controller: _inputScroll,
thumbVisibility:
_inputOverflows,
child: ScrollConfiguration(
behavior:
const _NoAutomaticScrollbarBehavior(),
child: TextField(
controller: _input,
focusNode: inputFocus,
scrollController:
_inputScroll,
style:
AppTheme.composerTextStyle(
context,
),
cursorHeight:
AppTheme.composerCursorHeight(
context,
),
textAlignVertical:
TextAlignVertical
.top,
minLines: 1,
maxLines: 12,
keyboardType:
TextInputType
.multiline,
textInputAction:
TextInputAction
.newline,
decoration:
AppComposerStyle.inputDecoration(
context,
hintText: context
.l10n
.assistantHint,
),
),
),
),
),
),
ValueListenableBuilder<
TextEditingValue
>(
valueListenable: _input,
builder: (context, _, _) =>
_input.hasInvalidReferences
? Padding(
padding:
const EdgeInsets.symmetric(
horizontal: 14,
vertical: 4,
),
child: Align(
alignment: Alignment
.centerLeft,
child: Text(
context
.l10n
.composerReferenceInvalid,
style: theme
.textTheme
.bodySmall
?.copyWith(
color: theme
.colorScheme
.error,
),
),
),
)
: const SizedBox.shrink(),
),
Padding(
padding: AppComposerStyle
.controlsPadding,
child: Row(
children: [
IconButton(
style: compactIconStyle,
tooltip: context
.l10n
.addAttachment,
onPressed:
widget.projectId !=
null &&
!_importingAttachments &&
ref
.watch(
platformCapabilitiesProvider,
)
.localFileSelection
? _pickAttachments
: null,
icon: const Icon(
AppIcons.add,
),
),
const SizedBox(
width: ComposerLayout
.controlGap,
),
Expanded(
child: Align(
alignment:
AlignmentDirectional
.centerStart,
child: modelPicker(),
),
),
const SizedBox(
width: ComposerLayout
.controlGap,
),
if (state.busy)
IconButton.filled(
style:
AppTheme.primaryIconButtonStyle(
context,
).merge(
compactIconStyle,
),
tooltip: context
.l10n
.stopReply,
onPressed:
state.stopping
? null
: ref
.read(
provider!
.notifier,
)
.stop,
icon: const Icon(
AppIcons.stop,
),
)
else
ValueListenableBuilder<
TextEditingValue
>(
valueListenable: _input,
builder: (context, value, child) => IconButton.filled(
style:
AppComposerStyle.composerSendButtonStyle(
context,
).merge(
compactIconStyle,
),
tooltip: context
.l10n
.sendMessage,
onPressed:
provider !=
null &&
widget.timelineId !=
null &&
configured &&
!_importingAttachments &&
!_input
.hasInvalidReferences &&
(value.text
.trim()
.isNotEmpty ||
_attachments
.isNotEmpty)
? send
: null,
icon: const Icon(
AppIcons.arrowUp,
),
),
),
],
),
),
],
),
),
),
),
),
),
],
),
),
),
],
),
),
),
),
],
);
},
),
);
return MediaImportFeedbackListener(
feedback: _composer.feedback,
child: content,
);
}
}
/// Explicit scrollbars own their track instead of the desktop default wrapper.
class _NoAutomaticScrollbarBehavior extends MaterialScrollBehavior {
const _NoAutomaticScrollbarBehavior();
@override
Widget buildScrollbar(
BuildContext context,
Widget child,
ScrollableDetails details,
) => child;
}