feat: initial Cutdex application
Add the Flutter video editing application with project management, media import, timeline editing, preview, AI assistance, diagnostics and settings. Include shared UI and native host packages, platform runners, application tests and release tooling. Provide usage and contribution guides, the MIT license and third-party notices. Exclude local credentials, build outputs and validation data.
This commit is contained in:
commit
27e77fff39
718 files changed
+183958
No files matched your search
@@ -0,0 +1,103 @@
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../media/media_asset_cover.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../media/audio_asset_tile.dart';
|
||||
|
||||
/// Compact project-media preview shared by the composer and sent messages.
|
||||
class AgentAttachmentCard extends StatelessWidget {
|
||||
const AgentAttachmentCard({super.key, required this.asset, this.onRemove});
|
||||
|
||||
final AssetDocument asset;
|
||||
final VoidCallback? onRemove;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final kind = asset.metadata['kind'];
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
final preview = switch (kind) {
|
||||
'image' || 'video' => SizedBox.expand(
|
||||
child: MediaAssetCover(
|
||||
asset: asset,
|
||||
fit: BoxFit.cover,
|
||||
fallback: Center(
|
||||
child: Icon(
|
||||
kind == 'image' ? Icons.image_outlined : Icons.movie_outlined,
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
errorFallback: Center(
|
||||
child: Icon(
|
||||
Icons.broken_image_outlined,
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
'audio' => AudioAssetTile(
|
||||
asset: asset,
|
||||
showName: false,
|
||||
aspectRatio: 132 / 96,
|
||||
),
|
||||
_ => Center(
|
||||
child: Icon(
|
||||
Icons.insert_drive_file_outlined,
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
};
|
||||
return SizedBox(
|
||||
width: 132,
|
||||
height: 122,
|
||||
child: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: ColoredBox(
|
||||
color: AppSurfaces.of(context).previewBackground,
|
||||
child: Column(
|
||||
children: [
|
||||
Expanded(child: SizedBox.expand(child: preview)),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 5,
|
||||
),
|
||||
child: Text(
|
||||
asset.name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (onRemove != null)
|
||||
Positioned(
|
||||
top: -4,
|
||||
right: -4,
|
||||
child: IconButton.filled(
|
||||
key: Key('agent-attachment-remove-${asset.id}'),
|
||||
tooltip: MaterialLocalizations.of(context).deleteButtonTooltip,
|
||||
onPressed: onRemove,
|
||||
style: IconButton.styleFrom(
|
||||
minimumSize: const Size(20, 20),
|
||||
maximumSize: const Size(20, 20),
|
||||
padding: EdgeInsets.zero,
|
||||
backgroundColor: colors.surface,
|
||||
foregroundColor: colors.onSurface,
|
||||
),
|
||||
icon: const Icon(Icons.close, size: 13),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,84 @@
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../workspace/external_media_import.dart';
|
||||
import '../../workspace/media_import.dart';
|
||||
import '../../workspace/media_import_feedback.dart';
|
||||
import 'agent_media_attachments.dart';
|
||||
|
||||
/// Owns attachment operations for one conversation or draft, even while hidden.
|
||||
class AgentComposerController extends ChangeNotifier {
|
||||
AgentComposerController({
|
||||
required this.canImport,
|
||||
required this.pickFiles,
|
||||
required this.importMedia,
|
||||
List<AgentMediaAttachment>? attachments,
|
||||
}) : attachments = attachments ?? [];
|
||||
|
||||
final bool Function() canImport;
|
||||
final Future<List<ExternalMediaFile>> Function() pickFiles;
|
||||
final Future<ExternalMediaSelection?> Function(List<ExternalMediaFile>)
|
||||
importMedia;
|
||||
final List<AgentMediaAttachment> attachments;
|
||||
final feedback = MediaImportFeedbackController();
|
||||
bool _busy = false;
|
||||
bool _disposed = false;
|
||||
bool get busy => _busy;
|
||||
|
||||
void attach(AssetDocument asset) {
|
||||
if (_disposed || attachments.any((item) => item.id == asset.id)) return;
|
||||
attachments.add(AgentMediaAttachment.fromAsset(asset));
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void remove(String id) {
|
||||
attachments.removeWhere((item) => item.id == id);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void clear() {
|
||||
attachments.clear();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<ExternalMediaSelection?> pickAttachments() => _run(pickFiles);
|
||||
|
||||
Future<ExternalMediaSelection?> importAttachments(
|
||||
List<ExternalMediaFile> files,
|
||||
) => _run(() async => files);
|
||||
|
||||
Future<ExternalMediaSelection?> _run(
|
||||
Future<List<ExternalMediaFile>> Function() select,
|
||||
) async {
|
||||
if (_disposed || _busy || !canImport()) return null;
|
||||
_busy = true;
|
||||
notifyListeners();
|
||||
try {
|
||||
final files = await select();
|
||||
if (_disposed || files.isEmpty || !canImport()) return null;
|
||||
final result = await importMedia(files);
|
||||
// Deleting the conversation invalidates this destination. Hiding its
|
||||
// presentation does not, so completed imports still populate the draft.
|
||||
if (!_disposed) {
|
||||
for (final asset in result?.selected ?? <AssetDocument>[]) {
|
||||
attach(asset);
|
||||
}
|
||||
feedback.recordResult(result);
|
||||
}
|
||||
return result;
|
||||
} catch (_) {
|
||||
if (!_disposed) feedback.recordFailure();
|
||||
rethrow;
|
||||
} finally {
|
||||
_busy = false;
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
feedback.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../integrations/platform/file_picker.dart';
|
||||
import '../../integrations/platform/platform_capabilities.dart';
|
||||
import '../../workspace/media_file_extensions.dart';
|
||||
import '../../workspace/external_media_import.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
import 'agent_composer_controller.dart';
|
||||
import 'agent_media_attachments.dart';
|
||||
import 'composer_document.dart';
|
||||
|
||||
/// Composition survives presentation changes, including temporarily hidden chat.
|
||||
final agentComposerStoreProvider = Provider<AgentComposerStore>((ref) {
|
||||
final store = AgentComposerStore(
|
||||
createComposer: (projectId) => AgentComposerController(
|
||||
canImport: () =>
|
||||
ref.mounted &&
|
||||
projectId != null &&
|
||||
ref.read(platformCapabilitiesProvider).localFileSelection &&
|
||||
ref.read(projectsProvider).value?.activeProject?.id == projectId &&
|
||||
ref.read(projectsProvider).value?.projectBusy == false &&
|
||||
!ref.read(externalMediaImportProvider(projectId)).isLoading,
|
||||
pickFiles: () => ref
|
||||
.read(filePickerProvider)
|
||||
.pickFiles(allowedExtensions: selectableMediaFileExtensions),
|
||||
importMedia: (files) => ref
|
||||
.read(externalMediaImportProvider(projectId!).notifier)
|
||||
.importFiles(files),
|
||||
),
|
||||
);
|
||||
ref.onDispose(store.dispose);
|
||||
return store;
|
||||
});
|
||||
|
||||
final class AgentComposerStore {
|
||||
AgentComposerStore({required this.createComposer});
|
||||
final AgentComposerController Function(String?) createComposer;
|
||||
ComposerDocumentController _draft = ComposerDocumentController();
|
||||
ComposerDocumentController get draft => _draft;
|
||||
final _inputs = <(String?, String), ComposerDocumentController>{};
|
||||
final _composers = <(String?, String), AgentComposerController>{};
|
||||
|
||||
ComposerDocumentController input(String? projectId, String? conversationId) =>
|
||||
conversationId == null
|
||||
? draft
|
||||
: _inputs.putIfAbsent((
|
||||
projectId,
|
||||
conversationId,
|
||||
), ComposerDocumentController.new);
|
||||
|
||||
List<AgentMediaAttachment> attachments(String? projectId, String key) =>
|
||||
composer(projectId, key).attachments;
|
||||
|
||||
AgentComposerController composer(String? projectId, String key) =>
|
||||
_composers.putIfAbsent((projectId, key), () => createComposer(projectId));
|
||||
|
||||
void promoteDraft(String projectId, String draftKey, String conversationId) {
|
||||
final destination = (projectId, conversationId);
|
||||
_inputs.remove(destination)?.dispose();
|
||||
_inputs[destination] = _draft;
|
||||
_draft = ComposerDocumentController();
|
||||
final composer = _composers.remove((projectId, draftKey));
|
||||
if (composer != null) {
|
||||
_composers.remove(destination)?.dispose();
|
||||
_composers[destination] = composer;
|
||||
}
|
||||
}
|
||||
|
||||
void removeConversation(String projectId, String conversationId) {
|
||||
_inputs.remove((projectId, conversationId))?.dispose();
|
||||
_composers.remove((projectId, conversationId))?.dispose();
|
||||
}
|
||||
|
||||
void removeDraft(String? projectId, String draftKey) {
|
||||
_composers.remove((projectId, draftKey))?.dispose();
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
draft.dispose();
|
||||
for (final input in _inputs.values) {
|
||||
input.dispose();
|
||||
}
|
||||
_inputs.clear();
|
||||
for (final composer in _composers.values) {
|
||||
composer.dispose();
|
||||
}
|
||||
_composers.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,718 @@
|
||||
import 'package:cutdex/errors/app_failure.dart';
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../../diagnostics/agent_request_diagnostics.dart';
|
||||
import '../../diagnostics/app_diagnostics.dart';
|
||||
import '../../integrations/agent/agent_prompt_policy.dart';
|
||||
import '../../integrations/agent/agent_provider.dart';
|
||||
import '../../integrations/agent/agent_runtime_factory.dart';
|
||||
import '../../integrations/agent/conversation_repository.dart';
|
||||
import '../../integrations/editor_tools.dart';
|
||||
import 'agent_message_codec.dart';
|
||||
import 'chat_state.dart';
|
||||
import 'composer_document.dart';
|
||||
|
||||
part 'agent_conversation_service.g.dart';
|
||||
part 'agent_conversation_service.freezed.dart';
|
||||
|
||||
enum AgentConversationFailure {
|
||||
configurationRead,
|
||||
notConfigured,
|
||||
contextBudget,
|
||||
authentication,
|
||||
connection,
|
||||
protocol,
|
||||
request,
|
||||
}
|
||||
|
||||
class AgentConversationException implements Exception {
|
||||
const AgentConversationException(this.failure);
|
||||
final AgentConversationFailure failure;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class AgentConversationMessage with _$AgentConversationMessage {
|
||||
const AgentConversationMessage._();
|
||||
|
||||
const factory AgentConversationMessage({
|
||||
required String text,
|
||||
required bool isUser,
|
||||
int? elapsedMs,
|
||||
}) = _AgentConversationMessage;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class AgentConversationHistory with _$AgentConversationHistory {
|
||||
const factory AgentConversationHistory(
|
||||
List<AgentConversationMessage> messages, {
|
||||
@Default(false) bool exportReplyFailed,
|
||||
@Default(false) bool recoveryRequired,
|
||||
@Default(false) bool resumeAvailable,
|
||||
}) = _AgentConversationHistory;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class AgentConversationPreparation
|
||||
with _$AgentConversationPreparation {
|
||||
const factory AgentConversationPreparation(
|
||||
List<AgentConversationMessage> messages, {
|
||||
required bool sessionChanged,
|
||||
}) = _AgentConversationPreparation;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class AgentConversationOutcome with _$AgentConversationOutcome {
|
||||
const AgentConversationOutcome._();
|
||||
|
||||
const factory AgentConversationOutcome({
|
||||
required String response,
|
||||
required bool completed,
|
||||
required bool failed,
|
||||
ConversationMetadata? conversation,
|
||||
RunFailure? failure,
|
||||
@Default(false) bool paused,
|
||||
@Default(false) bool recoveryRequired,
|
||||
@Default(false) bool exportReplyFailed,
|
||||
int? elapsedMs,
|
||||
}) = _AgentConversationOutcome;
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
AgentConversationRegistry agentConversationRegistry(Ref ref) {
|
||||
final registry = AgentConversationRegistry();
|
||||
ref.onDispose(registry.dispose);
|
||||
return registry;
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
Future<AgentRuntime?> Function(ConversationMetadata?)
|
||||
agentConversationRuntimeResolver(Ref ref) {
|
||||
return (item) async {
|
||||
if (item == null) return ref.read(agentRuntimeProvider.future);
|
||||
final settings = await ref.read(agentSettingsProvider.future);
|
||||
return ref
|
||||
.read(agentRuntimeFactoryProvider)
|
||||
.createFor(
|
||||
settings,
|
||||
providerId: item.providerId,
|
||||
modelId: item.modelId,
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
Future<EditorAgentBinding> Function(String, String)
|
||||
agentConversationToolsResolver(Ref ref) {
|
||||
return (projectId, timelineId) =>
|
||||
createEditorAgentBinding(ref, projectId, timelineId);
|
||||
}
|
||||
|
||||
class AgentConversationRegistry {
|
||||
final _services = <String, AgentConversationService>{};
|
||||
bool _paused = false;
|
||||
bool get hasRunning => _services.values.any((service) => service.busy);
|
||||
bool get canStart => !_paused;
|
||||
|
||||
Future<T> whilePaused<T>(Future<T> Function() action) async {
|
||||
if (_paused || hasRunning) {
|
||||
throw AppException(AppErrorCode.agentLocationBusy);
|
||||
}
|
||||
_paused = true;
|
||||
try {
|
||||
return await action();
|
||||
} finally {
|
||||
_paused = false;
|
||||
}
|
||||
}
|
||||
|
||||
String _key(String projectId, String id) => '$projectId\u0000$id';
|
||||
|
||||
AgentConversationService obtain(
|
||||
String projectId,
|
||||
String key,
|
||||
String? conversationId,
|
||||
AgentConversationService Function(void Function(String) published) create,
|
||||
) {
|
||||
final lookup = _key(projectId, conversationId ?? 'draft:$key');
|
||||
return _services.putIfAbsent(lookup, () {
|
||||
late final AgentConversationService service;
|
||||
service = create((id) => _services[_key(projectId, id)] = service);
|
||||
return service;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> cancel(String projectId, String id) async =>
|
||||
_services[_key(projectId, id)]?.cancelAndWait();
|
||||
|
||||
Future<void> cancelAll() async {
|
||||
await Future.wait([
|
||||
for (final service in _services.values.toSet()) service.cancelAndWait(),
|
||||
]);
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
for (final service in _services.values.toSet()) {
|
||||
service.dispose();
|
||||
}
|
||||
_services.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Not auto-disposed: switching the visible conversation must not stop a run.
|
||||
@Riverpod(keepAlive: true)
|
||||
AgentConversationService agentConversationService(
|
||||
Ref ref,
|
||||
String projectId,
|
||||
String key,
|
||||
String? conversationId,
|
||||
) {
|
||||
return ref
|
||||
.read(agentConversationRegistryProvider)
|
||||
.obtain(
|
||||
projectId,
|
||||
key,
|
||||
conversationId,
|
||||
(published) => AgentConversationService(
|
||||
projectId: projectId,
|
||||
conversationId: conversationId,
|
||||
canStart: () => ref.read(agentConversationRegistryProvider).canStart,
|
||||
onPublished: published,
|
||||
loadRepository: () => ref.read(conversationRepositoryProvider.future),
|
||||
loadRuntime: ref.read(agentConversationRuntimeResolverProvider),
|
||||
loadTools: (timelineId) => ref.read(
|
||||
agentConversationToolsResolverProvider,
|
||||
)(projectId, timelineId),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Owns one explicit conversation identity, checkpoint recovery and Agent run.
|
||||
class AgentConversationService {
|
||||
AgentConversationService({
|
||||
required this.projectId,
|
||||
required this.conversationId,
|
||||
required this.loadRepository,
|
||||
required this.loadRuntime,
|
||||
required this.loadTools,
|
||||
this.onPublished,
|
||||
this.canStart,
|
||||
});
|
||||
|
||||
final String projectId;
|
||||
final String? conversationId;
|
||||
final Future<ConversationRepository> Function() loadRepository;
|
||||
final Future<AgentRuntime?> Function(ConversationMetadata?) loadRuntime;
|
||||
final Future<EditorAgentBinding> Function(String timelineId) loadTools;
|
||||
final void Function(String id)? onPublished;
|
||||
final bool Function()? canStart;
|
||||
final _changes = StreamController<void>.broadcast();
|
||||
Stream<void> get changes => _changes.stream;
|
||||
AgentChatActivity _activity = AgentChatActivity.replying;
|
||||
AgentChatActivity get activity => _activity;
|
||||
String _partialResponse = '';
|
||||
String get partialResponse => _partialResponse;
|
||||
bool get busy => _busy;
|
||||
|
||||
void _notify() {
|
||||
if (!_changes.isClosed) _changes.add(null);
|
||||
}
|
||||
|
||||
AgentRun? _run;
|
||||
Completer<void>? _settled;
|
||||
bool _cancelRequested = false;
|
||||
bool _disposed = false;
|
||||
bool _busy = false;
|
||||
ConversationMetadata? _created;
|
||||
bool _startingNewConversation = false;
|
||||
int _identityRevision = 0;
|
||||
ConversationMetadata? get metadata => _created;
|
||||
|
||||
void startNewConversation() {
|
||||
if (_busy) throw AppException(AppErrorCode.agentLocationBusy);
|
||||
_identityRevision++;
|
||||
_created = null;
|
||||
_startingNewConversation = true;
|
||||
_partialResponse = '';
|
||||
}
|
||||
|
||||
void _checkActive() {
|
||||
if (_disposed || _cancelRequested) throw const _PreparationCancelled();
|
||||
}
|
||||
|
||||
List<AgentConversationMessage> _messages(
|
||||
SessionSnapshot snapshot, {
|
||||
List<int?> responseDurationsMs = const [],
|
||||
}) {
|
||||
final history = snapshot.history;
|
||||
final result = snapshot.completionEvidence?['result'];
|
||||
final rejectedFinal = result is Map && result['isError'] == true;
|
||||
final visible = <AgentConversationMessage>[];
|
||||
var responseIndex = 0;
|
||||
for (var i = 0; i < history.length; i++) {
|
||||
final message = history[i];
|
||||
if (message.role == MessageRole.tool ||
|
||||
message.runtimeNotice ||
|
||||
message.text.isEmpty ||
|
||||
(message.role == MessageRole.assistant &&
|
||||
((i + 1 < history.length &&
|
||||
history[i + 1].runtimeNotice &&
|
||||
history[i + 1].text.startsWith(
|
||||
'[Runtime artifact verification,',
|
||||
)) ||
|
||||
(i == history.length - 1 && rejectedFinal)))) {
|
||||
continue;
|
||||
}
|
||||
final isUser = message.role == MessageRole.user;
|
||||
visible.add(
|
||||
AgentConversationMessage(
|
||||
text: message.text,
|
||||
isUser: isUser,
|
||||
elapsedMs: isUser || responseIndex >= responseDurationsMs.length
|
||||
? null
|
||||
: responseDurationsMs[responseIndex],
|
||||
),
|
||||
);
|
||||
if (!isUser) responseIndex++;
|
||||
}
|
||||
return visible;
|
||||
}
|
||||
|
||||
Future<AgentConversationHistory?> restore() async {
|
||||
final identityRevision = _identityRevision;
|
||||
final id =
|
||||
_created?.id ?? (_startingNewConversation ? null : conversationId);
|
||||
if (id == null) return null;
|
||||
try {
|
||||
final repository = await loadRepository();
|
||||
final item = await repository.read(projectId, id);
|
||||
if (item == null) return null;
|
||||
final snapshot = await repository.store(item).read(item.id);
|
||||
if (identityRevision != _identityRevision) return null;
|
||||
_created = item;
|
||||
return snapshot == null
|
||||
? null
|
||||
: AgentConversationHistory(
|
||||
_messages(
|
||||
snapshot,
|
||||
responseDurationsMs: item.responseDurationsMs,
|
||||
),
|
||||
exportReplyFailed: _exportReplyFailed(snapshot),
|
||||
resumeAvailable:
|
||||
!_busy &&
|
||||
(snapshot.pending.isNotEmpty ||
|
||||
snapshot.status == RunStatus.running ||
|
||||
snapshot.status == RunStatus.paused),
|
||||
recoveryRequired:
|
||||
!_busy &&
|
||||
(snapshot.status == RunStatus.waiting ||
|
||||
snapshot.pending.any(
|
||||
(call) => call.status == CallStatus.started,
|
||||
)),
|
||||
);
|
||||
} catch (_) {
|
||||
throw const AgentConversationException(AgentConversationFailure.request);
|
||||
}
|
||||
}
|
||||
|
||||
Future<AgentConversationOutcome> send(
|
||||
String text, {
|
||||
required String timelineId,
|
||||
bool summaryOnly = false,
|
||||
bool resumeOnly = false,
|
||||
required void Function(AgentConversationPreparation value) onPrepared,
|
||||
required void Function(String text) onTextDelta,
|
||||
void Function(ConversationMetadata value)? onCreated,
|
||||
}) {
|
||||
final requestId = const Uuid().v4();
|
||||
return withDiagnosticContext(
|
||||
{
|
||||
'requestId': requestId,
|
||||
'projectId': projectId,
|
||||
'timelineId': timelineId,
|
||||
},
|
||||
() => _send(
|
||||
text,
|
||||
requestId: requestId,
|
||||
timelineId: timelineId,
|
||||
summaryOnly: summaryOnly,
|
||||
resumeOnly: resumeOnly,
|
||||
onPrepared: onPrepared,
|
||||
onTextDelta: onTextDelta,
|
||||
onCreated: onCreated,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<AgentConversationOutcome> _send(
|
||||
String text, {
|
||||
required String requestId,
|
||||
required String timelineId,
|
||||
bool summaryOnly = false,
|
||||
bool resumeOnly = false,
|
||||
required void Function(AgentConversationPreparation value) onPrepared,
|
||||
required void Function(String text) onTextDelta,
|
||||
void Function(ConversationMetadata value)? onCreated,
|
||||
}) async {
|
||||
if (canStart?.call() == false) {
|
||||
throw const AgentConversationException(AgentConversationFailure.request);
|
||||
}
|
||||
if (_busy) throw AppException(AppErrorCode.agentLocationBusy);
|
||||
_busy = true;
|
||||
_activity = AgentChatActivity.replying;
|
||||
_settled = Completer<void>();
|
||||
_cancelRequested = false;
|
||||
_partialResponse = '';
|
||||
_notify();
|
||||
final elapsed = Stopwatch()..start();
|
||||
final diagnostics = AgentRequestDiagnostics(requestId: requestId);
|
||||
AgentRun? measuredRun;
|
||||
StreamSubscription<AgentEvent>? subscription;
|
||||
EditorAgentBinding? binding;
|
||||
ConversationRepository? repository;
|
||||
ConversationMetadata? item;
|
||||
try {
|
||||
binding = summaryOnly
|
||||
// Each run needs a distinct ownership token.
|
||||
// ignore: prefer_const_constructors
|
||||
? EditorAgentBinding(owner: Object(), tools: const [])
|
||||
: await loadTools(timelineId);
|
||||
_checkActive();
|
||||
if (!summaryOnly) {
|
||||
final references = AgentComposerMessage.decode(text).references;
|
||||
for (final reference in references) {
|
||||
if (reference.kind == ComposerReferenceKind.timeline &&
|
||||
reference.projectId == projectId) {
|
||||
await binding.ensureTimeline?.call(reference.id);
|
||||
_checkActive();
|
||||
}
|
||||
}
|
||||
}
|
||||
repository = await loadRepository();
|
||||
_checkActive();
|
||||
final savedId =
|
||||
_created?.id ?? (_startingNewConversation ? null : conversationId);
|
||||
item = savedId == null ? null : await repository.read(projectId, savedId);
|
||||
if ((savedId != null || summaryOnly || resumeOnly) && item == null) {
|
||||
throw const AgentConversationException(
|
||||
AgentConversationFailure.request,
|
||||
);
|
||||
}
|
||||
final AgentRuntime? runtime;
|
||||
try {
|
||||
runtime = await loadRuntime(item);
|
||||
} catch (_) {
|
||||
throw const AgentConversationException(
|
||||
AgentConversationFailure.configurationRead,
|
||||
);
|
||||
}
|
||||
_checkActive();
|
||||
if (runtime == null) {
|
||||
throw const AgentConversationException(
|
||||
AgentConversationFailure.notConfigured,
|
||||
);
|
||||
}
|
||||
final system = summaryOnly
|
||||
? _summaryOnlyInstruction
|
||||
: AgentPromptPolicy.forTimeline(projectId, timelineId);
|
||||
final runTools = summaryOnly ? <AgentTool>[] : binding.tools;
|
||||
// Check the mandatory payload before committing a new user turn.
|
||||
try {
|
||||
await runtime.contextBuilder.build(
|
||||
system: system,
|
||||
history: [AgentMessage(role: MessageRole.user, text: text)],
|
||||
tools: [
|
||||
...runTools,
|
||||
...runtime.contextBuilder.runtimeTools(
|
||||
() => SessionSnapshot(id: 'preflight'),
|
||||
runTools,
|
||||
),
|
||||
],
|
||||
cancellation: CancellationToken(),
|
||||
);
|
||||
} on ContextOverflow {
|
||||
throw const AgentConversationException(
|
||||
AgentConversationFailure.contextBudget,
|
||||
);
|
||||
}
|
||||
_checkActive();
|
||||
item ??= await repository.begin(
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
providerId: runtime.providerId ?? runtime.sessionIdentity,
|
||||
modelId: runtime.modelId ?? runtime.sessionIdentity,
|
||||
title: () {
|
||||
final prompt = AgentComposerMessage.decode(text);
|
||||
final visible = prompt.text.isNotEmpty
|
||||
? prompt.text
|
||||
: prompt.attachments.firstOrNull?.name ?? text;
|
||||
return visible.length <= 64
|
||||
? visible
|
||||
: '${visible.substring(0, 64)}…';
|
||||
}(),
|
||||
);
|
||||
_created = item;
|
||||
final store = repository.store(item);
|
||||
final manager = SessionManager(
|
||||
model: runtime.model,
|
||||
store: store,
|
||||
tools: runTools,
|
||||
contextBuilder: runtime.contextBuilder,
|
||||
completionCheck: summaryOnly ? null : binding.completionCheck,
|
||||
);
|
||||
var snapshot = await store.read(item.id);
|
||||
_checkActive();
|
||||
snapshot ??= await manager.create(id: item.id, system: system);
|
||||
_checkActive();
|
||||
if (summaryOnly &&
|
||||
(!_exportReplyFailed(snapshot) ||
|
||||
snapshot.pending.isNotEmpty ||
|
||||
snapshot.queued.isNotEmpty)) {
|
||||
throw const AgentConversationException(
|
||||
AgentConversationFailure.request,
|
||||
);
|
||||
}
|
||||
final unfinished =
|
||||
snapshot.pending.isNotEmpty ||
|
||||
snapshot.queued.isNotEmpty ||
|
||||
snapshot.status == RunStatus.running ||
|
||||
snapshot.status == RunStatus.waiting ||
|
||||
snapshot.status == RunStatus.paused;
|
||||
if (resumeOnly && !unfinished) {
|
||||
throw const AgentConversationException(
|
||||
AgentConversationFailure.request,
|
||||
);
|
||||
}
|
||||
onPrepared(
|
||||
AgentConversationPreparation(
|
||||
_messages(snapshot, responseDurationsMs: item.responseDurationsMs),
|
||||
sessionChanged: conversationId == null || _startingNewConversation,
|
||||
),
|
||||
);
|
||||
if (!resumeOnly && unfinished) {
|
||||
return AgentConversationOutcome(
|
||||
response: '',
|
||||
completed: false,
|
||||
failed: true,
|
||||
recoveryRequired: true,
|
||||
conversation: item,
|
||||
);
|
||||
}
|
||||
final run = resumeOnly
|
||||
? await manager.resume(item.id, maxTurns: snapshot.turns + 80)
|
||||
: await manager.prompt(item.id, text, system: system, maxTurns: 80);
|
||||
_run = run;
|
||||
measuredRun = run;
|
||||
diagnostics.prepared();
|
||||
_activity = run.phase == AgentRunPhase.compacting
|
||||
? AgentChatActivity.compacting
|
||||
: AgentChatActivity.replying;
|
||||
_notify();
|
||||
subscription = run.events.listen((event) {
|
||||
if (_disposed) return;
|
||||
if (event.kind == AgentEventKind.phase) {
|
||||
_activity = event.text == AgentRunPhase.compacting.name
|
||||
? AgentChatActivity.compacting
|
||||
: AgentChatActivity.replying;
|
||||
_notify();
|
||||
} else if (event.kind == AgentEventKind.toolStarted) {
|
||||
_activity =
|
||||
event.text.endsWith('_query') ||
|
||||
event.text.endsWith('_list') ||
|
||||
event.text == 'cutdex_workspaces' ||
|
||||
event.text == 'completion_check'
|
||||
? AgentChatActivity.verifying
|
||||
: AgentChatActivity.editing;
|
||||
_notify();
|
||||
}
|
||||
if (!_disposed && event.kind == AgentEventKind.textDelta) {
|
||||
_activity = AgentChatActivity.replying;
|
||||
_partialResponse += event.text;
|
||||
_notify();
|
||||
onTextDelta(event.text);
|
||||
}
|
||||
});
|
||||
if (item.pending) {
|
||||
item = await repository.publish(item);
|
||||
_created = item;
|
||||
onPublished?.call(item.id);
|
||||
onCreated?.call(item);
|
||||
}
|
||||
if (_cancelRequested || _disposed) unawaited(run.cancel());
|
||||
final result = await run.done;
|
||||
diagnostics.outcome = result.status.name;
|
||||
if (result.status == RunStatus.failed ||
|
||||
result.status == RunStatus.waiting) {
|
||||
reportDiagnostic(
|
||||
AppDiagnostics.report,
|
||||
DiagnosticEvent(
|
||||
component: 'agent',
|
||||
operation: 'run',
|
||||
error: StateError(
|
||||
'Agent run ${result.status.name}: ${result.failure?.name ?? 'request'}',
|
||||
),
|
||||
context: {'failure': result.failure?.name},
|
||||
),
|
||||
);
|
||||
}
|
||||
final completed =
|
||||
result.status == RunStatus.completed && !_cancelRequested;
|
||||
final response =
|
||||
completed && result.history.last.role == MessageRole.assistant
|
||||
? result.history.last.text
|
||||
: '';
|
||||
final responseIndex =
|
||||
_messages(result).where((message) => !message.isUser).length - 1;
|
||||
final elapsedMs = completed && response.isNotEmpty
|
||||
? elapsed.elapsedMilliseconds
|
||||
: null;
|
||||
final responseDurationsMs = [...item.responseDurationsMs];
|
||||
if (elapsedMs != null && responseIndex >= 0) {
|
||||
while (responseDurationsMs.length <= responseIndex) {
|
||||
responseDurationsMs.add(null);
|
||||
}
|
||||
responseDurationsMs[responseIndex] = elapsedMs;
|
||||
}
|
||||
item = await repository.update(
|
||||
item.copyWith(
|
||||
timelineId: timelineId,
|
||||
responseDurationsMs: responseDurationsMs,
|
||||
),
|
||||
);
|
||||
_created = item;
|
||||
_partialResponse = '';
|
||||
_notify();
|
||||
return AgentConversationOutcome(
|
||||
response: response,
|
||||
completed: completed,
|
||||
failed:
|
||||
result.status == RunStatus.failed ||
|
||||
result.status == RunStatus.waiting,
|
||||
conversation: item,
|
||||
paused: result.status == RunStatus.paused && !_cancelRequested,
|
||||
recoveryRequired: result.status == RunStatus.waiting,
|
||||
failure: result.failure,
|
||||
exportReplyFailed: _exportReplyFailed(result),
|
||||
elapsedMs: elapsedMs,
|
||||
);
|
||||
} on _PreparationCancelled {
|
||||
diagnostics.outcome = 'cancelled';
|
||||
return AgentConversationOutcome(
|
||||
response: '',
|
||||
completed: false,
|
||||
failed: false,
|
||||
conversation: item,
|
||||
);
|
||||
} on AgentConversationException catch (error, stack) {
|
||||
AppDiagnostics.failure('agent', 'send', error, stack);
|
||||
rethrow;
|
||||
} catch (error, stack) {
|
||||
AppDiagnostics.failure('agent', 'send', error, stack);
|
||||
if (repository != null && item != null && item.pending) {
|
||||
try {
|
||||
final published = await repository.publish(item);
|
||||
_created = published;
|
||||
onPublished?.call(published.id);
|
||||
onCreated?.call(published);
|
||||
} catch (_) {
|
||||
// No user message committed; startup recovery ignores this draft.
|
||||
}
|
||||
}
|
||||
throw const AgentConversationException(AgentConversationFailure.request);
|
||||
} finally {
|
||||
if (measuredRun != null) {
|
||||
diagnostics.runs.add(measuredRun.diagnostics.toJson());
|
||||
}
|
||||
final report = diagnostics.stop();
|
||||
reportDiagnostic(
|
||||
AppDiagnostics.report,
|
||||
DiagnosticEvent(
|
||||
component: 'agent',
|
||||
operation: 'requestFinished',
|
||||
level: DiagnosticSeverity.info,
|
||||
context: {'outcome': report.outcome, 'elapsedUs': report.elapsedUs},
|
||||
),
|
||||
);
|
||||
unawaited(
|
||||
AppDiagnostics.instance?.request(report, requestId) ??
|
||||
Future<void>.value(),
|
||||
);
|
||||
if (repository != null) {
|
||||
await AgentRequestDiagnostics.persist(repository.root, report);
|
||||
}
|
||||
_run = null;
|
||||
_busy = false;
|
||||
_notify();
|
||||
try {
|
||||
await subscription?.cancel();
|
||||
await binding?.release?.call();
|
||||
} finally {
|
||||
_settled?.complete();
|
||||
_settled = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> cancel() async {
|
||||
_cancelRequested = true;
|
||||
final run = _run;
|
||||
if (run != null) {
|
||||
await run.cancel();
|
||||
await _settled?.future;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> cancelAndWait() async {
|
||||
await cancel();
|
||||
await _settled?.future;
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
unawaited(cancel());
|
||||
unawaited(_changes.close());
|
||||
}
|
||||
}
|
||||
|
||||
class _PreparationCancelled implements Exception {
|
||||
const _PreparationCancelled();
|
||||
}
|
||||
|
||||
const _summaryOnlyInstruction =
|
||||
'Summarize the already completed export and edits from successful tool results. No tools are available. Never claim a new edit or export occurred. State the saved destination and confirmed results in the user language.';
|
||||
|
||||
bool _exportReplyFailed(SessionSnapshot snapshot) {
|
||||
if (snapshot.status != RunStatus.failed ||
|
||||
snapshot.pending.isNotEmpty ||
|
||||
snapshot.queued.isNotEmpty) {
|
||||
return false;
|
||||
}
|
||||
final start = snapshot.system == _summaryOnlyInstruction
|
||||
? 0
|
||||
: snapshot.runStart;
|
||||
final history = snapshot.history.skip(start).toList();
|
||||
final tool = history.where((m) => m.role == MessageRole.tool).lastOrNull;
|
||||
if (tool == null || tool.isError) return false;
|
||||
final calls = history.expand((m) => m.calls);
|
||||
if (!calls.any((c) => c.id == tool.callId && c.name == 'project_export')) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
final result = jsonDecode(tool.text) as Map;
|
||||
final data = result['data'] as Map;
|
||||
return result['isError'] != true &&
|
||||
data['status'] == 'succeeded' &&
|
||||
(data['data'] as Map)['destination'] is String;
|
||||
} on FormatException {
|
||||
return false;
|
||||
} on TypeError {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,268 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_conversation_service.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(agentConversationRegistry)
|
||||
final agentConversationRegistryProvider = AgentConversationRegistryProvider._();
|
||||
|
||||
final class AgentConversationRegistryProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AgentConversationRegistry,
|
||||
AgentConversationRegistry,
|
||||
AgentConversationRegistry
|
||||
>
|
||||
with $Provider<AgentConversationRegistry> {
|
||||
AgentConversationRegistryProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentConversationRegistryProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentConversationRegistryHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<AgentConversationRegistry> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
AgentConversationRegistry create(Ref ref) {
|
||||
return agentConversationRegistry(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AgentConversationRegistry value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AgentConversationRegistry>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentConversationRegistryHash() =>
|
||||
r'3e4660057c1e9c91cb6432391f22f528a3589f40';
|
||||
|
||||
@ProviderFor(agentConversationRuntimeResolver)
|
||||
final agentConversationRuntimeResolverProvider =
|
||||
AgentConversationRuntimeResolverProvider._();
|
||||
|
||||
final class AgentConversationRuntimeResolverProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
Future<AgentRuntime?> Function(ConversationMetadata?),
|
||||
Future<AgentRuntime?> Function(ConversationMetadata?),
|
||||
Future<AgentRuntime?> Function(ConversationMetadata?)
|
||||
>
|
||||
with $Provider<Future<AgentRuntime?> Function(ConversationMetadata?)> {
|
||||
AgentConversationRuntimeResolverProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentConversationRuntimeResolverProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentConversationRuntimeResolverHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<Future<AgentRuntime?> Function(ConversationMetadata?)>
|
||||
$createElement($ProviderPointer pointer) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
Future<AgentRuntime?> Function(ConversationMetadata?) create(Ref ref) {
|
||||
return agentConversationRuntimeResolver(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(
|
||||
Future<AgentRuntime?> Function(ConversationMetadata?) value,
|
||||
) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride:
|
||||
$SyncValueProvider<
|
||||
Future<AgentRuntime?> Function(ConversationMetadata?)
|
||||
>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentConversationRuntimeResolverHash() =>
|
||||
r'5a74962d3d1c50771fe2a0743a71abbc8868405a';
|
||||
|
||||
@ProviderFor(agentConversationToolsResolver)
|
||||
final agentConversationToolsResolverProvider =
|
||||
AgentConversationToolsResolverProvider._();
|
||||
|
||||
final class AgentConversationToolsResolverProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
Future<EditorAgentBinding> Function(String, String),
|
||||
Future<EditorAgentBinding> Function(String, String),
|
||||
Future<EditorAgentBinding> Function(String, String)
|
||||
>
|
||||
with $Provider<Future<EditorAgentBinding> Function(String, String)> {
|
||||
AgentConversationToolsResolverProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentConversationToolsResolverProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentConversationToolsResolverHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<Future<EditorAgentBinding> Function(String, String)>
|
||||
$createElement($ProviderPointer pointer) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
Future<EditorAgentBinding> Function(String, String) create(Ref ref) {
|
||||
return agentConversationToolsResolver(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(
|
||||
Future<EditorAgentBinding> Function(String, String) value,
|
||||
) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride:
|
||||
$SyncValueProvider<
|
||||
Future<EditorAgentBinding> Function(String, String)
|
||||
>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentConversationToolsResolverHash() =>
|
||||
r'45a68e8151a75e872f48f6bc151046bf1720ae28';
|
||||
|
||||
/// Not auto-disposed: switching the visible conversation must not stop a run.
|
||||
|
||||
@ProviderFor(agentConversationService)
|
||||
final agentConversationServiceProvider = AgentConversationServiceFamily._();
|
||||
|
||||
/// Not auto-disposed: switching the visible conversation must not stop a run.
|
||||
|
||||
final class AgentConversationServiceProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AgentConversationService,
|
||||
AgentConversationService,
|
||||
AgentConversationService
|
||||
>
|
||||
with $Provider<AgentConversationService> {
|
||||
/// Not auto-disposed: switching the visible conversation must not stop a run.
|
||||
AgentConversationServiceProvider._({
|
||||
required AgentConversationServiceFamily super.from,
|
||||
required (String, String, String?) super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'agentConversationServiceProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentConversationServiceHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'agentConversationServiceProvider'
|
||||
''
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<AgentConversationService> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
AgentConversationService create(Ref ref) {
|
||||
final argument = this.argument as (String, String, String?);
|
||||
return agentConversationService(ref, argument.$1, argument.$2, argument.$3);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AgentConversationService value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AgentConversationService>(value),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is AgentConversationServiceProvider &&
|
||||
other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentConversationServiceHash() =>
|
||||
r'35f3a11cae37f2ab35527e851f468d2fb3467941';
|
||||
|
||||
/// Not auto-disposed: switching the visible conversation must not stop a run.
|
||||
|
||||
final class AgentConversationServiceFamily extends $Family
|
||||
with
|
||||
$FunctionalFamilyOverride<
|
||||
AgentConversationService,
|
||||
(String, String, String?)
|
||||
> {
|
||||
AgentConversationServiceFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'agentConversationServiceProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: false,
|
||||
);
|
||||
|
||||
/// Not auto-disposed: switching the visible conversation must not stop a run.
|
||||
|
||||
AgentConversationServiceProvider call(
|
||||
String projectId,
|
||||
String key,
|
||||
String? conversationId,
|
||||
) => AgentConversationServiceProvider._(
|
||||
argument: (projectId, key, conversationId),
|
||||
from: this,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() => r'agentConversationServiceProvider';
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'agent_media_attachments.freezed.dart';
|
||||
part 'agent_media_attachments.g.dart';
|
||||
|
||||
/// A project-media reference shown in chat and resolved through editor tools.
|
||||
@freezed
|
||||
abstract class AgentMediaAttachment with _$AgentMediaAttachment {
|
||||
const AgentMediaAttachment._();
|
||||
|
||||
const factory AgentMediaAttachment({
|
||||
required String id,
|
||||
required String name,
|
||||
required String kind,
|
||||
}) = _AgentMediaAttachment;
|
||||
|
||||
factory AgentMediaAttachment.fromAsset(AssetDocument asset) =>
|
||||
AgentMediaAttachment(
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
kind: asset.metadata['kind'] as String? ?? 'file',
|
||||
);
|
||||
|
||||
factory AgentMediaAttachment.fromJson(Map<String, Object?> json) =>
|
||||
_$AgentMediaAttachmentFromJson(json);
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'agent_media_attachments.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$AgentMediaAttachment {
|
||||
String get id;
|
||||
String get name;
|
||||
String get kind;
|
||||
|
||||
/// Create a copy of AgentMediaAttachment
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$AgentMediaAttachmentCopyWith<AgentMediaAttachment> get copyWith =>
|
||||
_$AgentMediaAttachmentCopyWithImpl<AgentMediaAttachment>(
|
||||
this as AgentMediaAttachment,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
/// Serializes this AgentMediaAttachment to a JSON map.
|
||||
Map<String, dynamic> toJson();
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as AgentMediaAttachment;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is AgentMediaAttachment &&
|
||||
(identical(other.id, _this.id) || other.id == _this.id) &&
|
||||
(identical(other.name, _this.name) || other.name == _this.name) &&
|
||||
(identical(other.kind, _this.kind) || other.kind == _this.kind));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as AgentMediaAttachment;
|
||||
return Object.hash(runtimeType, _this.id, _this.name, _this.kind);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as AgentMediaAttachment;
|
||||
return 'AgentMediaAttachment(id: ${_this.id}, name: ${_this.name}, kind: ${_this.kind})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $AgentMediaAttachmentCopyWith<$Res> {
|
||||
factory $AgentMediaAttachmentCopyWith(
|
||||
AgentMediaAttachment value,
|
||||
$Res Function(AgentMediaAttachment) _then,
|
||||
) = _$AgentMediaAttachmentCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({String id, String name, String kind});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$AgentMediaAttachmentCopyWithImpl<$Res>
|
||||
implements $AgentMediaAttachmentCopyWith<$Res> {
|
||||
_$AgentMediaAttachmentCopyWithImpl(this._self, this._then);
|
||||
|
||||
final AgentMediaAttachment _self;
|
||||
final $Res Function(AgentMediaAttachment) _then;
|
||||
|
||||
/// Create a copy of AgentMediaAttachment
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({Object? id = null, Object? name = null, Object? kind = null}) {
|
||||
return _then(
|
||||
AgentMediaAttachment(
|
||||
id: null == id
|
||||
? _self.id
|
||||
: id // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
name: null == name
|
||||
? _self.name
|
||||
: name // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
kind: null == kind
|
||||
? _self.kind
|
||||
: kind // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [AgentMediaAttachment].
|
||||
extension AgentMediaAttachmentPatterns on AgentMediaAttachment {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>(
|
||||
TResult Function(_AgentMediaAttachment value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentMediaAttachment() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>(
|
||||
TResult Function(_AgentMediaAttachment value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentMediaAttachment():
|
||||
return $default(_that);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>(
|
||||
TResult? Function(_AgentMediaAttachment value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentMediaAttachment() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>(
|
||||
TResult Function(String id, String name, String kind)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentMediaAttachment() when $default != null:
|
||||
return $default(_that.id, _that.name, _that.kind);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>(
|
||||
TResult Function(String id, String name, String kind) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentMediaAttachment():
|
||||
return $default(_that.id, _that.name, _that.kind);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>(
|
||||
TResult? Function(String id, String name, String kind)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentMediaAttachment() when $default != null:
|
||||
return $default(_that.id, _that.name, _that.kind);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
@JsonSerializable()
|
||||
class _AgentMediaAttachment extends AgentMediaAttachment {
|
||||
const _AgentMediaAttachment({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.kind,
|
||||
}) : super._();
|
||||
factory _AgentMediaAttachment.fromJson(Map<String, dynamic> json) =>
|
||||
_$AgentMediaAttachmentFromJson(json);
|
||||
|
||||
@override
|
||||
final String id;
|
||||
@override
|
||||
final String name;
|
||||
@override
|
||||
final String kind;
|
||||
|
||||
/// Create a copy of AgentMediaAttachment
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$AgentMediaAttachmentCopyWith<_AgentMediaAttachment> get copyWith =>
|
||||
__$AgentMediaAttachmentCopyWithImpl<_AgentMediaAttachment>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return _$AgentMediaAttachmentToJson(this);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _AgentMediaAttachment &&
|
||||
(identical(other.id, id) || other.id == id) &&
|
||||
(identical(other.name, name) || other.name == name) &&
|
||||
(identical(other.kind, kind) || other.kind == kind));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, id, name, kind);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'AgentMediaAttachment(id: $id, name: $name, kind: $kind)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$AgentMediaAttachmentCopyWith<$Res>
|
||||
implements $AgentMediaAttachmentCopyWith<$Res> {
|
||||
factory _$AgentMediaAttachmentCopyWith(
|
||||
_AgentMediaAttachment value,
|
||||
$Res Function(_AgentMediaAttachment) _then,
|
||||
) = __$AgentMediaAttachmentCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({String id, String name, String kind});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$AgentMediaAttachmentCopyWithImpl<$Res>
|
||||
implements _$AgentMediaAttachmentCopyWith<$Res> {
|
||||
__$AgentMediaAttachmentCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _AgentMediaAttachment _self;
|
||||
final $Res Function(_AgentMediaAttachment) _then;
|
||||
|
||||
/// Create a copy of AgentMediaAttachment
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({Object? id = null, Object? name = null, Object? kind = null}) {
|
||||
return _then(
|
||||
_AgentMediaAttachment(
|
||||
id: null == id
|
||||
? _self.id
|
||||
: id // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
name: null == name
|
||||
? _self.name
|
||||
: name // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
kind: null == kind
|
||||
? _self.kind
|
||||
: kind // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_media_attachments.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
_AgentMediaAttachment _$AgentMediaAttachmentFromJson(
|
||||
Map<String, dynamic> json,
|
||||
) => _AgentMediaAttachment(
|
||||
id: json['id'] as String,
|
||||
name: json['name'] as String,
|
||||
kind: json['kind'] as String,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$AgentMediaAttachmentToJson(
|
||||
_AgentMediaAttachment instance,
|
||||
) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'name': instance.name,
|
||||
'kind': instance.kind,
|
||||
};
|
||||
@@ -0,0 +1,79 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
import 'agent_media_attachments.dart';
|
||||
import 'composer_document.dart';
|
||||
|
||||
part 'agent_message_codec.freezed.dart';
|
||||
part 'agent_message_codec.g.dart';
|
||||
|
||||
@freezed
|
||||
abstract class AgentComposerMessage with _$AgentComposerMessage {
|
||||
const AgentComposerMessage._();
|
||||
|
||||
const factory AgentComposerMessage({
|
||||
required String text,
|
||||
required List<AgentMediaAttachment> attachments,
|
||||
required List<ComposerSegment> segments,
|
||||
}) = _AgentComposerMessage;
|
||||
|
||||
factory AgentComposerMessage.fromJson(Map<String, Object?> json) =>
|
||||
_$AgentComposerMessageFromJson(json);
|
||||
|
||||
List<ComposerReference> get references => [
|
||||
for (final segment in segments)
|
||||
if (segment case ComposerReferenceSegment(:final value)) value,
|
||||
];
|
||||
|
||||
static const _prefix = '[Cutdex composer message] ';
|
||||
static const _separator = '\n\n';
|
||||
|
||||
static String encodeDocument(
|
||||
List<ComposerSegment> segments,
|
||||
List<AgentMediaAttachment> attachments,
|
||||
) => _encode(
|
||||
AgentComposerMessage(
|
||||
text: segments.map((segment) => segment.displayText).join().trim(),
|
||||
attachments: attachments,
|
||||
segments: segments,
|
||||
),
|
||||
);
|
||||
|
||||
static String _encode(AgentComposerMessage message) {
|
||||
if (message.attachments.isEmpty && message.references.isEmpty) {
|
||||
return message.text;
|
||||
}
|
||||
final data = jsonEncode(message.toJson());
|
||||
return '$_prefix$data$_separator'
|
||||
'These references identify project resources by stable ID, not file '
|
||||
'contents. A referenced timeline is context, not an instruction to '
|
||||
"switch the user's current timeline. Resolve each ID with media_query "
|
||||
'or the relevant project tool when needed.$_separator${message.text}';
|
||||
}
|
||||
|
||||
static AgentComposerMessage decode(String value) {
|
||||
AgentComposerMessage plain() => AgentComposerMessage(
|
||||
text: value,
|
||||
attachments: const [],
|
||||
segments: const [],
|
||||
);
|
||||
if (!value.startsWith(_prefix)) return plain();
|
||||
final end = value.indexOf(_separator, _prefix.length);
|
||||
if (end < 0) return plain();
|
||||
try {
|
||||
final data = jsonDecode(value.substring(_prefix.length, end));
|
||||
return AgentComposerMessage.fromJson(
|
||||
(data as Map).cast<String, Object?>(),
|
||||
);
|
||||
} on FormatException {
|
||||
return plain();
|
||||
} on CheckedFromJsonException {
|
||||
return plain();
|
||||
} on TypeError {
|
||||
return plain();
|
||||
} on ArgumentError {
|
||||
return plain();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'agent_message_codec.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$AgentComposerMessage {
|
||||
String get text;
|
||||
List<AgentMediaAttachment> get attachments;
|
||||
List<ComposerSegment> get segments;
|
||||
|
||||
/// Create a copy of AgentComposerMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$AgentComposerMessageCopyWith<AgentComposerMessage> get copyWith =>
|
||||
_$AgentComposerMessageCopyWithImpl<AgentComposerMessage>(
|
||||
this as AgentComposerMessage,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
/// Serializes this AgentComposerMessage to a JSON map.
|
||||
Map<String, dynamic> toJson();
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as AgentComposerMessage;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is AgentComposerMessage &&
|
||||
(identical(other.text, _this.text) || other.text == _this.text) &&
|
||||
const DeepCollectionEquality().equals(
|
||||
other.attachments,
|
||||
_this.attachments,
|
||||
) &&
|
||||
const DeepCollectionEquality().equals(
|
||||
other.segments,
|
||||
_this.segments,
|
||||
));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as AgentComposerMessage;
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
_this.text,
|
||||
const DeepCollectionEquality().hash(_this.attachments),
|
||||
const DeepCollectionEquality().hash(_this.segments),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as AgentComposerMessage;
|
||||
return 'AgentComposerMessage(text: ${_this.text}, attachments: ${_this.attachments}, segments: ${_this.segments})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $AgentComposerMessageCopyWith<$Res> {
|
||||
factory $AgentComposerMessageCopyWith(
|
||||
AgentComposerMessage value,
|
||||
$Res Function(AgentComposerMessage) _then,
|
||||
) = _$AgentComposerMessageCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
String text,
|
||||
List<AgentMediaAttachment> attachments,
|
||||
List<ComposerSegment> segments,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$AgentComposerMessageCopyWithImpl<$Res>
|
||||
implements $AgentComposerMessageCopyWith<$Res> {
|
||||
_$AgentComposerMessageCopyWithImpl(this._self, this._then);
|
||||
|
||||
final AgentComposerMessage _self;
|
||||
final $Res Function(AgentComposerMessage) _then;
|
||||
|
||||
/// Create a copy of AgentComposerMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? text = null,
|
||||
Object? attachments = null,
|
||||
Object? segments = null,
|
||||
}) {
|
||||
return _then(
|
||||
AgentComposerMessage(
|
||||
text: null == text
|
||||
? _self.text
|
||||
: text // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
attachments: null == attachments
|
||||
? _self.attachments
|
||||
: attachments // ignore: cast_nullable_to_non_nullable
|
||||
as List<AgentMediaAttachment>,
|
||||
segments: null == segments
|
||||
? _self.segments
|
||||
: segments // ignore: cast_nullable_to_non_nullable
|
||||
as List<ComposerSegment>,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [AgentComposerMessage].
|
||||
extension AgentComposerMessagePatterns on AgentComposerMessage {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>(
|
||||
TResult Function(_AgentComposerMessage value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentComposerMessage() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>(
|
||||
TResult Function(_AgentComposerMessage value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentComposerMessage():
|
||||
return $default(_that);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>(
|
||||
TResult? Function(_AgentComposerMessage value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentComposerMessage() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>(
|
||||
TResult Function(
|
||||
String text,
|
||||
List<AgentMediaAttachment> attachments,
|
||||
List<ComposerSegment> segments,
|
||||
)?
|
||||
$default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentComposerMessage() when $default != null:
|
||||
return $default(_that.text, _that.attachments, _that.segments);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>(
|
||||
TResult Function(
|
||||
String text,
|
||||
List<AgentMediaAttachment> attachments,
|
||||
List<ComposerSegment> segments,
|
||||
)
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentComposerMessage():
|
||||
return $default(_that.text, _that.attachments, _that.segments);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>(
|
||||
TResult? Function(
|
||||
String text,
|
||||
List<AgentMediaAttachment> attachments,
|
||||
List<ComposerSegment> segments,
|
||||
)?
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentComposerMessage() when $default != null:
|
||||
return $default(_that.text, _that.attachments, _that.segments);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
@JsonSerializable()
|
||||
class _AgentComposerMessage extends AgentComposerMessage {
|
||||
const _AgentComposerMessage({
|
||||
required this.text,
|
||||
required List<AgentMediaAttachment> attachments,
|
||||
required List<ComposerSegment> segments,
|
||||
}) : _attachments = attachments,
|
||||
_segments = segments,
|
||||
super._();
|
||||
factory _AgentComposerMessage.fromJson(Map<String, dynamic> json) =>
|
||||
_$AgentComposerMessageFromJson(json);
|
||||
|
||||
@override
|
||||
final String text;
|
||||
final List<AgentMediaAttachment> _attachments;
|
||||
@override
|
||||
List<AgentMediaAttachment> get attachments {
|
||||
if (_attachments is EqualUnmodifiableListView) return _attachments;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_attachments);
|
||||
}
|
||||
|
||||
final List<ComposerSegment> _segments;
|
||||
@override
|
||||
List<ComposerSegment> get segments {
|
||||
if (_segments is EqualUnmodifiableListView) return _segments;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_segments);
|
||||
}
|
||||
|
||||
/// Create a copy of AgentComposerMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$AgentComposerMessageCopyWith<_AgentComposerMessage> get copyWith =>
|
||||
__$AgentComposerMessageCopyWithImpl<_AgentComposerMessage>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return _$AgentComposerMessageToJson(this);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _AgentComposerMessage &&
|
||||
(identical(other.text, text) || other.text == text) &&
|
||||
const DeepCollectionEquality().equals(
|
||||
other.attachments,
|
||||
_attachments,
|
||||
) &&
|
||||
const DeepCollectionEquality().equals(other.segments, _segments));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
text,
|
||||
const DeepCollectionEquality().hash(_attachments),
|
||||
const DeepCollectionEquality().hash(_segments),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'AgentComposerMessage(text: $text, attachments: $attachments, segments: $segments)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$AgentComposerMessageCopyWith<$Res>
|
||||
implements $AgentComposerMessageCopyWith<$Res> {
|
||||
factory _$AgentComposerMessageCopyWith(
|
||||
_AgentComposerMessage value,
|
||||
$Res Function(_AgentComposerMessage) _then,
|
||||
) = __$AgentComposerMessageCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({
|
||||
String text,
|
||||
List<AgentMediaAttachment> attachments,
|
||||
List<ComposerSegment> segments,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$AgentComposerMessageCopyWithImpl<$Res>
|
||||
implements _$AgentComposerMessageCopyWith<$Res> {
|
||||
__$AgentComposerMessageCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _AgentComposerMessage _self;
|
||||
final $Res Function(_AgentComposerMessage) _then;
|
||||
|
||||
/// Create a copy of AgentComposerMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({
|
||||
Object? text = null,
|
||||
Object? attachments = null,
|
||||
Object? segments = null,
|
||||
}) {
|
||||
return _then(
|
||||
_AgentComposerMessage(
|
||||
text: null == text
|
||||
? _self.text
|
||||
: text // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
attachments: null == attachments
|
||||
? _self._attachments
|
||||
: attachments // ignore: cast_nullable_to_non_nullable
|
||||
as List<AgentMediaAttachment>,
|
||||
segments: null == segments
|
||||
? _self._segments
|
||||
: segments // ignore: cast_nullable_to_non_nullable
|
||||
as List<ComposerSegment>,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_message_codec.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
_AgentComposerMessage _$AgentComposerMessageFromJson(
|
||||
Map<String, dynamic> json,
|
||||
) => _AgentComposerMessage(
|
||||
text: json['text'] as String,
|
||||
attachments: (json['attachments'] as List<dynamic>)
|
||||
.map((e) => AgentMediaAttachment.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
segments: (json['segments'] as List<dynamic>)
|
||||
.map((e) => ComposerSegment.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$AgentComposerMessageToJson(
|
||||
_AgentComposerMessage instance,
|
||||
) => <String, dynamic>{
|
||||
'text': instance.text,
|
||||
'attachments': instance.attachments.map((e) => e.toJson()).toList(),
|
||||
'segments': instance.segments.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
@@ -0,0 +1,100 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
const _softBreak = '\u200B';
|
||||
|
||||
String _breakLongAsciiRuns(String text) {
|
||||
final result = StringBuffer();
|
||||
int? previous;
|
||||
for (final rune in text.runes) {
|
||||
if (previous != null &&
|
||||
previous >= 0x21 &&
|
||||
previous <= 0x7e &&
|
||||
rune >= 0x21 &&
|
||||
rune <= 0x7e) {
|
||||
result.write(_softBreak);
|
||||
}
|
||||
result.writeCharCode(rune);
|
||||
previous = rune;
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
class _CopyPlainTextIntent extends Intent {
|
||||
const _CopyPlainTextIntent();
|
||||
}
|
||||
|
||||
/// Allows paths and other long ASCII runs to wrap without changing copied text.
|
||||
class BreakableSelectableText extends StatefulWidget {
|
||||
const BreakableSelectableText({
|
||||
super.key,
|
||||
required this.text,
|
||||
required this.style,
|
||||
});
|
||||
|
||||
final String text;
|
||||
final TextStyle style;
|
||||
|
||||
@override
|
||||
State<BreakableSelectableText> createState() =>
|
||||
_BreakableSelectableTextState();
|
||||
}
|
||||
|
||||
class _BreakableSelectableTextState extends State<BreakableSelectableText> {
|
||||
TextSelection _selection = const TextSelection.collapsed(offset: -1);
|
||||
|
||||
void _copySelection(String displayText, TextSelection selection) {
|
||||
if (!selection.isValid || selection.isCollapsed) return;
|
||||
final text = selection.textInside(displayText).replaceAll(_softBreak, '');
|
||||
Clipboard.setData(ClipboardData(text: text));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final displayText = _breakLongAsciiRuns(widget.text);
|
||||
return Shortcuts(
|
||||
shortcuts: const {
|
||||
SingleActivator(LogicalKeyboardKey.keyC, meta: true):
|
||||
_CopyPlainTextIntent(),
|
||||
SingleActivator(LogicalKeyboardKey.keyC, control: true):
|
||||
_CopyPlainTextIntent(),
|
||||
},
|
||||
child: Actions(
|
||||
actions: {
|
||||
_CopyPlainTextIntent: CallbackAction<_CopyPlainTextIntent>(
|
||||
onInvoke: (_) {
|
||||
_copySelection(displayText, _selection);
|
||||
return null;
|
||||
},
|
||||
),
|
||||
},
|
||||
child: SelectableText(
|
||||
displayText,
|
||||
style: widget.style,
|
||||
textAlign: TextAlign.start,
|
||||
semanticsLabel: widget.text,
|
||||
onSelectionChanged: (selection, _) => _selection = selection,
|
||||
contextMenuBuilder: (context, editable) =>
|
||||
AdaptiveTextSelectionToolbar.buttonItems(
|
||||
anchors: editable.contextMenuAnchors,
|
||||
buttonItems: [
|
||||
for (final button in editable.contextMenuButtonItems)
|
||||
if (button.type == ContextMenuButtonType.copy)
|
||||
button.copyWith(
|
||||
onPressed: () {
|
||||
_copySelection(
|
||||
displayText,
|
||||
editable.textEditingValue.selection,
|
||||
);
|
||||
editable.hideToolbar();
|
||||
},
|
||||
)
|
||||
else
|
||||
button,
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../integrations/agent/agent_settings.dart';
|
||||
import '../../integrations/agent/conversation_repository.dart';
|
||||
import 'agent_conversation_service.dart';
|
||||
import 'chat_state.dart';
|
||||
|
||||
part 'chat_controller.g.dart';
|
||||
|
||||
/// Presentation state for one project conversation.
|
||||
@riverpod
|
||||
class ChatController extends _$ChatController {
|
||||
late AgentConversationService _conversation;
|
||||
AgentConversationService? _activeConversation;
|
||||
int _sendRevision = 0;
|
||||
|
||||
@override
|
||||
ChatState build(
|
||||
String projectId, {
|
||||
String? conversationId,
|
||||
String? draftKey,
|
||||
}) {
|
||||
_conversation = ref.watch(
|
||||
agentConversationServiceProvider(
|
||||
projectId,
|
||||
draftKey ?? conversationId ?? 'new',
|
||||
conversationId,
|
||||
),
|
||||
);
|
||||
final subscription = _conversation.changes.listen((_) {
|
||||
if (!ref.mounted) return;
|
||||
state = state.copyWith(
|
||||
busy: _conversation.busy,
|
||||
partialResponse: _conversation.partialResponse,
|
||||
activity: _conversation.activity,
|
||||
);
|
||||
if (!_conversation.busy && _activeConversation == null) {
|
||||
unawaited(_restore(force: true));
|
||||
}
|
||||
});
|
||||
ref.onDispose(subscription.cancel);
|
||||
unawaited(Future<void>.microtask(_restore));
|
||||
return ChatState(
|
||||
busy: _conversation.busy,
|
||||
partialResponse: _conversation.partialResponse,
|
||||
activity: _conversation.activity,
|
||||
);
|
||||
}
|
||||
|
||||
List<ChatMessage> _messages(List<AgentConversationMessage> messages) => [
|
||||
for (final message in messages)
|
||||
ChatMessage(
|
||||
text: message.text,
|
||||
isUser: message.isUser,
|
||||
elapsedMs: message.elapsedMs,
|
||||
),
|
||||
];
|
||||
|
||||
Future<void> _restore({bool force = false}) async {
|
||||
if ((_sendRevision != 0 && !force) || !ref.mounted) return;
|
||||
final revision = _sendRevision;
|
||||
try {
|
||||
final history = await _conversation.restore();
|
||||
if (!ref.mounted || revision != _sendRevision) return;
|
||||
state = state.copyWith(
|
||||
messages: history == null
|
||||
? state.messages
|
||||
: _messages(history.messages),
|
||||
conversation: _conversation.metadata,
|
||||
error: history?.exportReplyFailed == true
|
||||
? AgentChatError.exportReplyFailed
|
||||
: history?.recoveryRequired == true
|
||||
? AgentChatError.recoveryRequired
|
||||
: history?.resumeAvailable == true
|
||||
? AgentChatError.interrupted
|
||||
: null,
|
||||
);
|
||||
} on AgentConversationException catch (error) {
|
||||
if (ref.mounted && revision == _sendRevision) {
|
||||
state = state.copyWith(
|
||||
error: error.failure == AgentConversationFailure.configurationRead
|
||||
? AgentChatError.configurationReadFailed
|
||||
: AgentChatError.sessionRestoreFailed,
|
||||
);
|
||||
}
|
||||
} catch (_) {
|
||||
if (ref.mounted && revision == _sendRevision) {
|
||||
state = state.copyWith(error: AgentChatError.sessionRestoreFailed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> selectModel(String providerId, String modelId) async {
|
||||
if (state.busy) return;
|
||||
final previous = state.conversation;
|
||||
await ref
|
||||
.read(agentSettingsProvider.notifier)
|
||||
.selectModel(providerId, modelId);
|
||||
if (!ref.mounted) return;
|
||||
if ((previous != null &&
|
||||
(previous.providerId != providerId ||
|
||||
previous.modelId != modelId)) ||
|
||||
(previous == null && conversationId != null)) {
|
||||
_sendRevision++;
|
||||
_conversation.startNewConversation();
|
||||
state = const ChatState();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> send(
|
||||
String input, {
|
||||
required String timelineId,
|
||||
bool summaryOnly = false,
|
||||
bool resumeOnly = false,
|
||||
void Function(ConversationMetadata value)? onCreated,
|
||||
void Function(ConversationMetadata value)? onUpdated,
|
||||
}) async {
|
||||
final text = input.trim();
|
||||
if (text.isEmpty || state.busy) return;
|
||||
_sendRevision++;
|
||||
state = state.copyWith(
|
||||
messages: [
|
||||
...state.messages,
|
||||
if (!resumeOnly) ChatMessage(text: text, isUser: true),
|
||||
],
|
||||
partialResponse: '',
|
||||
busy: true,
|
||||
stopping: false,
|
||||
error: null,
|
||||
);
|
||||
final conversation = _conversation;
|
||||
_activeConversation = conversation;
|
||||
var streamed = '';
|
||||
try {
|
||||
final outcome = await conversation.send(
|
||||
text,
|
||||
timelineId: timelineId,
|
||||
summaryOnly: summaryOnly,
|
||||
resumeOnly: resumeOnly,
|
||||
onCreated: (item) {
|
||||
if (ref.mounted) state = state.copyWith(conversation: item);
|
||||
onCreated?.call(item);
|
||||
},
|
||||
onPrepared: (preparation) {
|
||||
if (!ref.mounted || !preparation.sessionChanged) return;
|
||||
state = state.copyWith(
|
||||
messages: [
|
||||
..._messages(preparation.messages),
|
||||
if (!resumeOnly) ChatMessage(text: text, isUser: true),
|
||||
],
|
||||
);
|
||||
},
|
||||
onTextDelta: (delta) {
|
||||
streamed += delta;
|
||||
if (ref.mounted) {
|
||||
state = state.copyWith(
|
||||
partialResponse: state.partialResponse + delta,
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
if (outcome.conversation case final item?) {
|
||||
if (ref.mounted) state = state.copyWith(conversation: item);
|
||||
onUpdated?.call(item);
|
||||
}
|
||||
if (outcome.recoveryRequired) {
|
||||
final history = await conversation.restore();
|
||||
if (ref.mounted && history != null) {
|
||||
state = state.copyWith(messages: _messages(history.messages));
|
||||
}
|
||||
}
|
||||
if (!ref.mounted) return;
|
||||
final response = outcome.completed && outcome.response.isNotEmpty
|
||||
? outcome.response
|
||||
: streamed;
|
||||
state = state.copyWith(
|
||||
messages: [
|
||||
...state.messages,
|
||||
if (response.isNotEmpty)
|
||||
ChatMessage(
|
||||
text: response,
|
||||
interrupted: !outcome.completed,
|
||||
elapsedMs: outcome.elapsedMs,
|
||||
),
|
||||
],
|
||||
partialResponse: '',
|
||||
error: outcome.exportReplyFailed
|
||||
? AgentChatError.exportReplyFailed
|
||||
: outcome.recoveryRequired
|
||||
? AgentChatError.recoveryRequired
|
||||
: outcome.paused
|
||||
? AgentChatError.turnLimit
|
||||
: outcome.failed
|
||||
? switch (outcome.failure) {
|
||||
RunFailure.contextBudget => AgentChatError.contextBudget,
|
||||
RunFailure.authentication => AgentChatError.authentication,
|
||||
RunFailure.connection => AgentChatError.connection,
|
||||
RunFailure.protocol => AgentChatError.protocol,
|
||||
_ => AgentChatError.replyFailed,
|
||||
}
|
||||
: null,
|
||||
);
|
||||
} on AgentConversationException catch (error) {
|
||||
if (ref.mounted) {
|
||||
state = state.copyWith(
|
||||
messages: [
|
||||
...state.messages,
|
||||
if (streamed.isNotEmpty)
|
||||
ChatMessage(text: streamed, interrupted: true),
|
||||
],
|
||||
partialResponse: '',
|
||||
error: switch (error.failure) {
|
||||
AgentConversationFailure.configurationRead =>
|
||||
AgentChatError.configurationReadFailed,
|
||||
AgentConversationFailure.notConfigured =>
|
||||
AgentChatError.configurationRequired,
|
||||
AgentConversationFailure.contextBudget =>
|
||||
AgentChatError.contextBudget,
|
||||
AgentConversationFailure.authentication =>
|
||||
AgentChatError.authentication,
|
||||
AgentConversationFailure.connection => AgentChatError.connection,
|
||||
AgentConversationFailure.protocol => AgentChatError.protocol,
|
||||
AgentConversationFailure.request => AgentChatError.requestFailed,
|
||||
},
|
||||
);
|
||||
}
|
||||
} catch (_) {
|
||||
if (ref.mounted) {
|
||||
state = state.copyWith(
|
||||
partialResponse: '',
|
||||
error: AgentChatError.requestFailed,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (identical(_activeConversation, conversation)) {
|
||||
_activeConversation = null;
|
||||
}
|
||||
if (ref.mounted) {
|
||||
state = state.copyWith(busy: false, stopping: false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
if (!state.busy) return;
|
||||
state = state.copyWith(stopping: true);
|
||||
final conversation = _activeConversation ?? _conversation;
|
||||
await conversation.cancel();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'chat_controller.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
/// Presentation state for one project conversation.
|
||||
|
||||
@ProviderFor(ChatController)
|
||||
final chatControllerProvider = ChatControllerFamily._();
|
||||
|
||||
/// Presentation state for one project conversation.
|
||||
final class ChatControllerProvider
|
||||
extends $NotifierProvider<ChatController, ChatState> {
|
||||
/// Presentation state for one project conversation.
|
||||
ChatControllerProvider._({
|
||||
required ChatControllerFamily super.from,
|
||||
required (String, {String? conversationId, String? draftKey})
|
||||
super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'chatControllerProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$chatControllerHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'chatControllerProvider'
|
||||
''
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
ChatController create() => ChatController();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(ChatState value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<ChatState>(value),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is ChatControllerProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$chatControllerHash() => r'b10209ff2924c59cc7c70c57db289a73837aa257';
|
||||
|
||||
/// Presentation state for one project conversation.
|
||||
|
||||
final class ChatControllerFamily extends $Family
|
||||
with
|
||||
$ClassFamilyOverride<
|
||||
ChatController,
|
||||
ChatState,
|
||||
ChatState,
|
||||
ChatState,
|
||||
(String, {String? conversationId, String? draftKey})
|
||||
> {
|
||||
ChatControllerFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'chatControllerProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
/// Presentation state for one project conversation.
|
||||
|
||||
ChatControllerProvider call(
|
||||
String projectId, {
|
||||
String? conversationId,
|
||||
String? draftKey,
|
||||
}) => ChatControllerProvider._(
|
||||
argument: (projectId, conversationId: conversationId, draftKey: draftKey),
|
||||
from: this,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() => r'chatControllerProvider';
|
||||
}
|
||||
|
||||
/// Presentation state for one project conversation.
|
||||
|
||||
abstract class _$ChatController extends $Notifier<ChatState> {
|
||||
late final _$args =
|
||||
ref.$arg as (String, {String? conversationId, String? draftKey});
|
||||
String get projectId => _$args.$1;
|
||||
String? get conversationId => _$args.conversationId;
|
||||
String? get draftKey => _$args.draftKey;
|
||||
|
||||
ChatState build(String projectId, {String? conversationId, String? draftKey});
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref = this.ref as $Ref<ChatState, ChatState>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<ChatState, ChatState>,
|
||||
ChatState,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(
|
||||
ref,
|
||||
() => build(
|
||||
_$args.$1,
|
||||
conversationId: _$args.conversationId,
|
||||
draftKey: _$args.draftKey,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
import '../../integrations/agent/conversation_repository.dart';
|
||||
|
||||
part 'chat_state.freezed.dart';
|
||||
|
||||
enum AgentChatActivity { replying, compacting, editing, verifying }
|
||||
|
||||
enum AgentChatError {
|
||||
configurationReadFailed,
|
||||
configurationRequired,
|
||||
sessionRestoreFailed,
|
||||
contextBudget,
|
||||
authentication,
|
||||
connection,
|
||||
protocol,
|
||||
replyFailed,
|
||||
turnLimit,
|
||||
recoveryRequired,
|
||||
interrupted,
|
||||
exportReplyFailed,
|
||||
requestFailed,
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ChatMessage with _$ChatMessage {
|
||||
const factory ChatMessage({
|
||||
required String text,
|
||||
@Default(false) bool isUser,
|
||||
@Default(false) bool interrupted,
|
||||
int? elapsedMs,
|
||||
}) = _ChatMessage;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ChatState with _$ChatState {
|
||||
const factory ChatState({
|
||||
@Default([]) List<ChatMessage> messages,
|
||||
@Default('') String partialResponse,
|
||||
@Default(AgentChatActivity.replying) AgentChatActivity activity,
|
||||
@Default(false) bool busy,
|
||||
@Default(false) bool stopping,
|
||||
AgentChatError? error,
|
||||
ConversationMetadata? conversation,
|
||||
}) = _ChatState;
|
||||
}
|
||||
@@ -0,0 +1,935 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'chat_state.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$ChatMessage {
|
||||
String get text;
|
||||
bool get isUser;
|
||||
bool get interrupted;
|
||||
int? get elapsedMs;
|
||||
|
||||
/// Create a copy of ChatMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$ChatMessageCopyWith<ChatMessage> get copyWith =>
|
||||
_$ChatMessageCopyWithImpl<ChatMessage>(this as ChatMessage, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as ChatMessage;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is ChatMessage &&
|
||||
(identical(other.text, _this.text) || other.text == _this.text) &&
|
||||
(identical(other.isUser, _this.isUser) ||
|
||||
other.isUser == _this.isUser) &&
|
||||
(identical(other.interrupted, _this.interrupted) ||
|
||||
other.interrupted == _this.interrupted) &&
|
||||
(identical(other.elapsedMs, _this.elapsedMs) ||
|
||||
other.elapsedMs == _this.elapsedMs));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as ChatMessage;
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
_this.text,
|
||||
_this.isUser,
|
||||
_this.interrupted,
|
||||
_this.elapsedMs,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as ChatMessage;
|
||||
return 'ChatMessage(text: ${_this.text}, isUser: ${_this.isUser}, interrupted: ${_this.interrupted}, elapsedMs: ${_this.elapsedMs})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $ChatMessageCopyWith<$Res> {
|
||||
factory $ChatMessageCopyWith(
|
||||
ChatMessage value,
|
||||
$Res Function(ChatMessage) _then,
|
||||
) = _$ChatMessageCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({String text, bool isUser, bool interrupted, int? elapsedMs});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$ChatMessageCopyWithImpl<$Res> implements $ChatMessageCopyWith<$Res> {
|
||||
_$ChatMessageCopyWithImpl(this._self, this._then);
|
||||
|
||||
final ChatMessage _self;
|
||||
final $Res Function(ChatMessage) _then;
|
||||
|
||||
/// Create a copy of ChatMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? text = null,
|
||||
Object? isUser = null,
|
||||
Object? interrupted = null,
|
||||
Object? elapsedMs = freezed,
|
||||
}) {
|
||||
return _then(
|
||||
ChatMessage(
|
||||
text: null == text
|
||||
? _self.text
|
||||
: text // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
isUser: null == isUser
|
||||
? _self.isUser
|
||||
: isUser // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
interrupted: null == interrupted
|
||||
? _self.interrupted
|
||||
: interrupted // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
elapsedMs: freezed == elapsedMs
|
||||
? _self.elapsedMs
|
||||
: elapsedMs // ignore: cast_nullable_to_non_nullable
|
||||
as int?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [ChatMessage].
|
||||
extension ChatMessagePatterns on ChatMessage {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>(
|
||||
TResult Function(_ChatMessage value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatMessage() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>(
|
||||
TResult Function(_ChatMessage value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatMessage():
|
||||
return $default(_that);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>(
|
||||
TResult? Function(_ChatMessage value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatMessage() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>(
|
||||
TResult Function(
|
||||
String text,
|
||||
bool isUser,
|
||||
bool interrupted,
|
||||
int? elapsedMs,
|
||||
)?
|
||||
$default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatMessage() when $default != null:
|
||||
return $default(
|
||||
_that.text,
|
||||
_that.isUser,
|
||||
_that.interrupted,
|
||||
_that.elapsedMs,
|
||||
);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>(
|
||||
TResult Function(String text, bool isUser, bool interrupted, int? elapsedMs)
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatMessage():
|
||||
return $default(
|
||||
_that.text,
|
||||
_that.isUser,
|
||||
_that.interrupted,
|
||||
_that.elapsedMs,
|
||||
);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>(
|
||||
TResult? Function(
|
||||
String text,
|
||||
bool isUser,
|
||||
bool interrupted,
|
||||
int? elapsedMs,
|
||||
)?
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatMessage() when $default != null:
|
||||
return $default(
|
||||
_that.text,
|
||||
_that.isUser,
|
||||
_that.interrupted,
|
||||
_that.elapsedMs,
|
||||
);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _ChatMessage implements ChatMessage {
|
||||
const _ChatMessage({
|
||||
required this.text,
|
||||
this.isUser = false,
|
||||
this.interrupted = false,
|
||||
this.elapsedMs,
|
||||
});
|
||||
|
||||
@override
|
||||
final String text;
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool isUser;
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool interrupted;
|
||||
@override
|
||||
final int? elapsedMs;
|
||||
|
||||
/// Create a copy of ChatMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$ChatMessageCopyWith<_ChatMessage> get copyWith =>
|
||||
__$ChatMessageCopyWithImpl<_ChatMessage>(this, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _ChatMessage &&
|
||||
(identical(other.text, text) || other.text == text) &&
|
||||
(identical(other.isUser, isUser) || other.isUser == isUser) &&
|
||||
(identical(other.interrupted, interrupted) ||
|
||||
other.interrupted == interrupted) &&
|
||||
(identical(other.elapsedMs, elapsedMs) ||
|
||||
other.elapsedMs == elapsedMs));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, text, isUser, interrupted, elapsedMs);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'ChatMessage(text: $text, isUser: $isUser, interrupted: $interrupted, elapsedMs: $elapsedMs)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$ChatMessageCopyWith<$Res>
|
||||
implements $ChatMessageCopyWith<$Res> {
|
||||
factory _$ChatMessageCopyWith(
|
||||
_ChatMessage value,
|
||||
$Res Function(_ChatMessage) _then,
|
||||
) = __$ChatMessageCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({String text, bool isUser, bool interrupted, int? elapsedMs});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$ChatMessageCopyWithImpl<$Res> implements _$ChatMessageCopyWith<$Res> {
|
||||
__$ChatMessageCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _ChatMessage _self;
|
||||
final $Res Function(_ChatMessage) _then;
|
||||
|
||||
/// Create a copy of ChatMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({
|
||||
Object? text = null,
|
||||
Object? isUser = null,
|
||||
Object? interrupted = null,
|
||||
Object? elapsedMs = freezed,
|
||||
}) {
|
||||
return _then(
|
||||
_ChatMessage(
|
||||
text: null == text
|
||||
? _self.text
|
||||
: text // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
isUser: null == isUser
|
||||
? _self.isUser
|
||||
: isUser // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
interrupted: null == interrupted
|
||||
? _self.interrupted
|
||||
: interrupted // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
elapsedMs: freezed == elapsedMs
|
||||
? _self.elapsedMs
|
||||
: elapsedMs // ignore: cast_nullable_to_non_nullable
|
||||
as int?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
mixin _$ChatState {
|
||||
List<ChatMessage> get messages;
|
||||
String get partialResponse;
|
||||
AgentChatActivity get activity;
|
||||
bool get busy;
|
||||
bool get stopping;
|
||||
AgentChatError? get error;
|
||||
ConversationMetadata? get conversation;
|
||||
|
||||
/// Create a copy of ChatState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$ChatStateCopyWith<ChatState> get copyWith =>
|
||||
_$ChatStateCopyWithImpl<ChatState>(this as ChatState, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as ChatState;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is ChatState &&
|
||||
const DeepCollectionEquality().equals(
|
||||
other.messages,
|
||||
_this.messages,
|
||||
) &&
|
||||
(identical(other.partialResponse, _this.partialResponse) ||
|
||||
other.partialResponse == _this.partialResponse) &&
|
||||
(identical(other.activity, _this.activity) ||
|
||||
other.activity == _this.activity) &&
|
||||
(identical(other.busy, _this.busy) || other.busy == _this.busy) &&
|
||||
(identical(other.stopping, _this.stopping) ||
|
||||
other.stopping == _this.stopping) &&
|
||||
(identical(other.error, _this.error) ||
|
||||
other.error == _this.error) &&
|
||||
(identical(other.conversation, _this.conversation) ||
|
||||
other.conversation == _this.conversation));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as ChatState;
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
const DeepCollectionEquality().hash(_this.messages),
|
||||
_this.partialResponse,
|
||||
_this.activity,
|
||||
_this.busy,
|
||||
_this.stopping,
|
||||
_this.error,
|
||||
_this.conversation,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as ChatState;
|
||||
return 'ChatState(messages: ${_this.messages}, partialResponse: ${_this.partialResponse}, activity: ${_this.activity}, busy: ${_this.busy}, stopping: ${_this.stopping}, error: ${_this.error}, conversation: ${_this.conversation})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $ChatStateCopyWith<$Res> {
|
||||
factory $ChatStateCopyWith(ChatState value, $Res Function(ChatState) _then) =
|
||||
_$ChatStateCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
List<ChatMessage> messages,
|
||||
String partialResponse,
|
||||
AgentChatActivity activity,
|
||||
bool busy,
|
||||
bool stopping,
|
||||
AgentChatError? error,
|
||||
ConversationMetadata? conversation,
|
||||
});
|
||||
|
||||
$ConversationMetadataCopyWith<$Res>? get conversation;
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$ChatStateCopyWithImpl<$Res> implements $ChatStateCopyWith<$Res> {
|
||||
_$ChatStateCopyWithImpl(this._self, this._then);
|
||||
|
||||
final ChatState _self;
|
||||
final $Res Function(ChatState) _then;
|
||||
|
||||
/// Create a copy of ChatState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? messages = null,
|
||||
Object? partialResponse = null,
|
||||
Object? activity = null,
|
||||
Object? busy = null,
|
||||
Object? stopping = null,
|
||||
Object? error = freezed,
|
||||
Object? conversation = freezed,
|
||||
}) {
|
||||
return _then(
|
||||
ChatState(
|
||||
messages: null == messages
|
||||
? _self.messages
|
||||
: messages // ignore: cast_nullable_to_non_nullable
|
||||
as List<ChatMessage>,
|
||||
partialResponse: null == partialResponse
|
||||
? _self.partialResponse
|
||||
: partialResponse // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
activity: null == activity
|
||||
? _self.activity
|
||||
: activity // ignore: cast_nullable_to_non_nullable
|
||||
as AgentChatActivity,
|
||||
busy: null == busy
|
||||
? _self.busy
|
||||
: busy // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
stopping: null == stopping
|
||||
? _self.stopping
|
||||
: stopping // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
error: freezed == error
|
||||
? _self.error
|
||||
: error // ignore: cast_nullable_to_non_nullable
|
||||
as AgentChatError?,
|
||||
conversation: freezed == conversation
|
||||
? _self.conversation
|
||||
: conversation // ignore: cast_nullable_to_non_nullable
|
||||
as ConversationMetadata?,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Create a copy of ChatState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$ConversationMetadataCopyWith<$Res>? get conversation {
|
||||
if (_self.conversation == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $ConversationMetadataCopyWith<$Res>(_self.conversation!, (value) {
|
||||
return _then(_self.copyWith(conversation: value));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [ChatState].
|
||||
extension ChatStatePatterns on ChatState {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>(
|
||||
TResult Function(_ChatState value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatState() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>(
|
||||
TResult Function(_ChatState value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatState():
|
||||
return $default(_that);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>(
|
||||
TResult? Function(_ChatState value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatState() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>(
|
||||
TResult Function(
|
||||
List<ChatMessage> messages,
|
||||
String partialResponse,
|
||||
AgentChatActivity activity,
|
||||
bool busy,
|
||||
bool stopping,
|
||||
AgentChatError? error,
|
||||
ConversationMetadata? conversation,
|
||||
)?
|
||||
$default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatState() when $default != null:
|
||||
return $default(
|
||||
_that.messages,
|
||||
_that.partialResponse,
|
||||
_that.activity,
|
||||
_that.busy,
|
||||
_that.stopping,
|
||||
_that.error,
|
||||
_that.conversation,
|
||||
);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>(
|
||||
TResult Function(
|
||||
List<ChatMessage> messages,
|
||||
String partialResponse,
|
||||
AgentChatActivity activity,
|
||||
bool busy,
|
||||
bool stopping,
|
||||
AgentChatError? error,
|
||||
ConversationMetadata? conversation,
|
||||
)
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatState():
|
||||
return $default(
|
||||
_that.messages,
|
||||
_that.partialResponse,
|
||||
_that.activity,
|
||||
_that.busy,
|
||||
_that.stopping,
|
||||
_that.error,
|
||||
_that.conversation,
|
||||
);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>(
|
||||
TResult? Function(
|
||||
List<ChatMessage> messages,
|
||||
String partialResponse,
|
||||
AgentChatActivity activity,
|
||||
bool busy,
|
||||
bool stopping,
|
||||
AgentChatError? error,
|
||||
ConversationMetadata? conversation,
|
||||
)?
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatState() when $default != null:
|
||||
return $default(
|
||||
_that.messages,
|
||||
_that.partialResponse,
|
||||
_that.activity,
|
||||
_that.busy,
|
||||
_that.stopping,
|
||||
_that.error,
|
||||
_that.conversation,
|
||||
);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _ChatState implements ChatState {
|
||||
const _ChatState({
|
||||
List<ChatMessage> messages = const [],
|
||||
this.partialResponse = '',
|
||||
this.activity = AgentChatActivity.replying,
|
||||
this.busy = false,
|
||||
this.stopping = false,
|
||||
this.error,
|
||||
this.conversation,
|
||||
}) : _messages = messages;
|
||||
|
||||
final List<ChatMessage> _messages;
|
||||
@override
|
||||
@JsonKey()
|
||||
List<ChatMessage> get messages {
|
||||
if (_messages is EqualUnmodifiableListView) return _messages;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_messages);
|
||||
}
|
||||
|
||||
@override
|
||||
@JsonKey()
|
||||
final String partialResponse;
|
||||
@override
|
||||
@JsonKey()
|
||||
final AgentChatActivity activity;
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool busy;
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool stopping;
|
||||
@override
|
||||
final AgentChatError? error;
|
||||
@override
|
||||
final ConversationMetadata? conversation;
|
||||
|
||||
/// Create a copy of ChatState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$ChatStateCopyWith<_ChatState> get copyWith =>
|
||||
__$ChatStateCopyWithImpl<_ChatState>(this, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _ChatState &&
|
||||
const DeepCollectionEquality().equals(other.messages, _messages) &&
|
||||
(identical(other.partialResponse, partialResponse) ||
|
||||
other.partialResponse == partialResponse) &&
|
||||
(identical(other.activity, activity) ||
|
||||
other.activity == activity) &&
|
||||
(identical(other.busy, busy) || other.busy == busy) &&
|
||||
(identical(other.stopping, stopping) ||
|
||||
other.stopping == stopping) &&
|
||||
(identical(other.error, error) || other.error == error) &&
|
||||
(identical(other.conversation, conversation) ||
|
||||
other.conversation == conversation));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
const DeepCollectionEquality().hash(_messages),
|
||||
partialResponse,
|
||||
activity,
|
||||
busy,
|
||||
stopping,
|
||||
error,
|
||||
conversation,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'ChatState(messages: $messages, partialResponse: $partialResponse, activity: $activity, busy: $busy, stopping: $stopping, error: $error, conversation: $conversation)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$ChatStateCopyWith<$Res>
|
||||
implements $ChatStateCopyWith<$Res> {
|
||||
factory _$ChatStateCopyWith(
|
||||
_ChatState value,
|
||||
$Res Function(_ChatState) _then,
|
||||
) = __$ChatStateCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({
|
||||
List<ChatMessage> messages,
|
||||
String partialResponse,
|
||||
AgentChatActivity activity,
|
||||
bool busy,
|
||||
bool stopping,
|
||||
AgentChatError? error,
|
||||
ConversationMetadata? conversation,
|
||||
});
|
||||
|
||||
@override
|
||||
$ConversationMetadataCopyWith<$Res>? get conversation;
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$ChatStateCopyWithImpl<$Res> implements _$ChatStateCopyWith<$Res> {
|
||||
__$ChatStateCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _ChatState _self;
|
||||
final $Res Function(_ChatState) _then;
|
||||
|
||||
/// Create a copy of ChatState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({
|
||||
Object? messages = null,
|
||||
Object? partialResponse = null,
|
||||
Object? activity = null,
|
||||
Object? busy = null,
|
||||
Object? stopping = null,
|
||||
Object? error = freezed,
|
||||
Object? conversation = freezed,
|
||||
}) {
|
||||
return _then(
|
||||
_ChatState(
|
||||
messages: null == messages
|
||||
? _self._messages
|
||||
: messages // ignore: cast_nullable_to_non_nullable
|
||||
as List<ChatMessage>,
|
||||
partialResponse: null == partialResponse
|
||||
? _self.partialResponse
|
||||
: partialResponse // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
activity: null == activity
|
||||
? _self.activity
|
||||
: activity // ignore: cast_nullable_to_non_nullable
|
||||
as AgentChatActivity,
|
||||
busy: null == busy
|
||||
? _self.busy
|
||||
: busy // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
stopping: null == stopping
|
||||
? _self.stopping
|
||||
: stopping // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
error: freezed == error
|
||||
? _self.error
|
||||
: error // ignore: cast_nullable_to_non_nullable
|
||||
as AgentChatError?,
|
||||
conversation: freezed == conversation
|
||||
? _self.conversation
|
||||
: conversation // ignore: cast_nullable_to_non_nullable
|
||||
as ConversationMetadata?,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Create a copy of ChatState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$ConversationMetadataCopyWith<$Res>? get conversation {
|
||||
if (_self.conversation == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $ConversationMetadataCopyWith<$Res>(_self.conversation!, (value) {
|
||||
return _then(_self.copyWith(conversation: value));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
part 'composer_document.freezed.dart';
|
||||
part 'composer_document.g.dart';
|
||||
|
||||
enum ComposerReferenceKind { media, timeline }
|
||||
|
||||
@freezed
|
||||
abstract class ComposerReference with _$ComposerReference {
|
||||
const ComposerReference._();
|
||||
|
||||
const factory ComposerReference({
|
||||
required ComposerReferenceKind kind,
|
||||
required String projectId,
|
||||
required String id,
|
||||
required String label,
|
||||
}) = _ComposerReference;
|
||||
|
||||
String get display => '@$label';
|
||||
|
||||
factory ComposerReference.fromJson(Map<String, Object?> json) =>
|
||||
_$ComposerReferenceFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ComposerMark with _$ComposerMark {
|
||||
const ComposerMark._();
|
||||
|
||||
const factory ComposerMark({
|
||||
required int start,
|
||||
required int end,
|
||||
required ComposerReference reference,
|
||||
@Default(true) bool valid,
|
||||
}) = _ComposerMark;
|
||||
|
||||
ComposerMark shift(int delta) =>
|
||||
copyWith(start: start + delta, end: end + delta);
|
||||
|
||||
ComposerMark withValidity(bool value) => copyWith(valid: value);
|
||||
}
|
||||
|
||||
@freezed
|
||||
sealed class ComposerSegment with _$ComposerSegment {
|
||||
const ComposerSegment._();
|
||||
const factory ComposerSegment.text(String value) = ComposerText;
|
||||
const factory ComposerSegment.reference(ComposerReference value) =
|
||||
ComposerReferenceSegment;
|
||||
|
||||
factory ComposerSegment.fromJson(Map<String, Object?> json) =>
|
||||
_$ComposerSegmentFromJson(json);
|
||||
|
||||
String get displayText => switch (this) {
|
||||
ComposerText(:final value) => value,
|
||||
ComposerReferenceSegment(:final value) => value.label,
|
||||
};
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class _ComposerSnapshot with _$ComposerSnapshot {
|
||||
const factory _ComposerSnapshot(
|
||||
TextEditingValue value,
|
||||
List<ComposerMark> marks,
|
||||
) = _ComposerHistorySnapshot;
|
||||
}
|
||||
|
||||
/// Keeps Flutter's text offsets and stable resource references in one draft.
|
||||
class ComposerDocumentController extends TextEditingController {
|
||||
ComposerDocumentController({super.text}) {
|
||||
_history.add(_ComposerSnapshot(value, const []));
|
||||
}
|
||||
|
||||
List<ComposerMark> _marks = [];
|
||||
final List<_ComposerSnapshot> _history = [];
|
||||
int _historyIndex = 0;
|
||||
bool _applying = false;
|
||||
|
||||
List<ComposerMark> get marks => List.unmodifiable(_marks);
|
||||
bool get hasInvalidReferences => _marks.any((mark) => !mark.valid);
|
||||
|
||||
void _record() {
|
||||
if (_historyIndex + 1 < _history.length) {
|
||||
_history.removeRange(_historyIndex + 1, _history.length);
|
||||
}
|
||||
_history.add(_ComposerSnapshot(value, List.unmodifiable(_marks)));
|
||||
_historyIndex = _history.length - 1;
|
||||
}
|
||||
|
||||
void _apply(
|
||||
TextEditingValue next,
|
||||
List<ComposerMark> marks, {
|
||||
bool record = true,
|
||||
}) {
|
||||
_applying = true;
|
||||
_marks = List.of(marks);
|
||||
super.value = next;
|
||||
_applying = false;
|
||||
if (record) _record();
|
||||
}
|
||||
|
||||
@override
|
||||
set value(TextEditingValue next) {
|
||||
if (_applying) {
|
||||
super.value = next;
|
||||
return;
|
||||
}
|
||||
final old = super.value;
|
||||
if (old.text == next.text) {
|
||||
final selection = next.selection;
|
||||
if (selection.isCollapsed) {
|
||||
for (final mark in _marks) {
|
||||
if (selection.baseOffset > mark.start &&
|
||||
selection.baseOffset < mark.end) {
|
||||
final left = selection.baseOffset - mark.start;
|
||||
final right = mark.end - selection.baseOffset;
|
||||
final previous = old.selection;
|
||||
final boundary = previous.isValid && previous.isCollapsed
|
||||
? previous.extentOffset == mark.end &&
|
||||
selection.baseOffset == mark.end - 1
|
||||
? mark.start
|
||||
: previous.extentOffset == mark.start &&
|
||||
selection.baseOffset == mark.start + 1
|
||||
? mark.end
|
||||
: null
|
||||
: null;
|
||||
super.value = next.copyWith(
|
||||
selection: TextSelection.collapsed(
|
||||
offset: boundary ?? (left < right ? mark.start : mark.end),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else if (selection.isValid) {
|
||||
var start = selection.start;
|
||||
var end = selection.end;
|
||||
for (final mark in _marks) {
|
||||
if (start < mark.end && end > mark.start) {
|
||||
if (start > mark.start) start = mark.start;
|
||||
if (end < mark.end) end = mark.end;
|
||||
}
|
||||
}
|
||||
if (start != selection.start || end != selection.end) {
|
||||
super.value = next.copyWith(
|
||||
selection: TextSelection(baseOffset: start, extentOffset: end),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
super.value = next;
|
||||
return;
|
||||
}
|
||||
|
||||
var prefix = 0;
|
||||
while (prefix < old.text.length &&
|
||||
prefix < next.text.length &&
|
||||
old.text.codeUnitAt(prefix) == next.text.codeUnitAt(prefix)) {
|
||||
prefix++;
|
||||
}
|
||||
var suffix = 0;
|
||||
while (suffix < old.text.length - prefix &&
|
||||
suffix < next.text.length - prefix &&
|
||||
old.text.codeUnitAt(old.text.length - suffix - 1) ==
|
||||
next.text.codeUnitAt(next.text.length - suffix - 1)) {
|
||||
suffix++;
|
||||
}
|
||||
var start = prefix;
|
||||
var end = old.text.length - suffix;
|
||||
final inserted = next.text.substring(prefix, next.text.length - suffix);
|
||||
final insertion = start == end;
|
||||
var touchedMark = false;
|
||||
if (insertion) {
|
||||
for (final mark in _marks) {
|
||||
if (start > mark.start && start < mark.end) {
|
||||
touchedMark = true;
|
||||
start = mark.end;
|
||||
end = mark.end;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (final mark in _marks) {
|
||||
if (start < mark.end && end > mark.start) {
|
||||
touchedMark = true;
|
||||
if (mark.start < start) start = mark.start;
|
||||
if (mark.end > end) end = mark.end;
|
||||
}
|
||||
}
|
||||
}
|
||||
final changed = old.text.replaceRange(start, end, inserted);
|
||||
final delta = inserted.length - (end - start);
|
||||
final marks = [
|
||||
for (final mark in _marks)
|
||||
if (mark.end <= start)
|
||||
mark
|
||||
else if (mark.start >= end)
|
||||
mark.shift(delta),
|
||||
];
|
||||
_apply(
|
||||
next.copyWith(
|
||||
text: changed,
|
||||
selection: touchedMark
|
||||
? TextSelection.collapsed(offset: start + inserted.length)
|
||||
: next.selection,
|
||||
composing: touchedMark ? TextRange.empty : next.composing,
|
||||
),
|
||||
marks,
|
||||
);
|
||||
}
|
||||
|
||||
void insertReference(int start, int end, ComposerReference reference) {
|
||||
final current = value;
|
||||
if (start < 0 || end < start || end > current.text.length) return;
|
||||
final display = reference.display;
|
||||
final nextCharacter = end < current.text.length
|
||||
? current.text.substring(end, end + 1)
|
||||
: '';
|
||||
final hasFollowingWhitespace = RegExp(r'^\s$').hasMatch(nextCharacter);
|
||||
final inserted = '$display${hasFollowingWhitespace ? '' : ' '}';
|
||||
final delta = inserted.length - (end - start);
|
||||
final marks = [
|
||||
for (final mark in _marks)
|
||||
if (mark.end <= start)
|
||||
mark
|
||||
else if (mark.start >= end)
|
||||
mark.shift(delta),
|
||||
ComposerMark(
|
||||
start: start,
|
||||
end: start + display.length,
|
||||
reference: reference,
|
||||
),
|
||||
]..sort((a, b) => a.start.compareTo(b.start));
|
||||
_apply(
|
||||
current.copyWith(
|
||||
text: current.text.replaceRange(start, end, inserted),
|
||||
selection: TextSelection.collapsed(
|
||||
offset:
|
||||
start +
|
||||
inserted.length +
|
||||
(nextCharacter == ' ' || nextCharacter == '\t' ? 1 : 0),
|
||||
),
|
||||
composing: TextRange.empty,
|
||||
),
|
||||
marks,
|
||||
);
|
||||
}
|
||||
|
||||
void updateValidity(bool Function(ComposerReference reference) isValid) {
|
||||
final updated = [
|
||||
for (final mark in _marks) mark.withValidity(isValid(mark.reference)),
|
||||
];
|
||||
if (updated.asMap().entries.every(
|
||||
(entry) => entry.value.valid == _marks[entry.key].valid,
|
||||
)) {
|
||||
return;
|
||||
}
|
||||
_marks = updated;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
List<ComposerSegment> get segments {
|
||||
final result = <ComposerSegment>[];
|
||||
var offset = 0;
|
||||
for (final mark in _marks) {
|
||||
if (mark.start > offset) {
|
||||
result.add(ComposerSegment.text(text.substring(offset, mark.start)));
|
||||
}
|
||||
result.add(ComposerSegment.reference(mark.reference));
|
||||
offset = mark.end;
|
||||
}
|
||||
if (offset < text.length) {
|
||||
result.add(ComposerSegment.text(text.substring(offset)));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void clearDocument() => _apply(const TextEditingValue(), const []);
|
||||
|
||||
void undoDocument() {
|
||||
if (_historyIndex == 0) return;
|
||||
_historyIndex--;
|
||||
final snapshot = _history[_historyIndex];
|
||||
_apply(snapshot.value, snapshot.marks, record: false);
|
||||
}
|
||||
|
||||
void redoDocument() {
|
||||
if (_historyIndex >= _history.length - 1) return;
|
||||
_historyIndex++;
|
||||
final snapshot = _history[_historyIndex];
|
||||
_apply(snapshot.value, snapshot.marks, record: false);
|
||||
}
|
||||
|
||||
@override
|
||||
TextSpan buildTextSpan({
|
||||
required BuildContext context,
|
||||
TextStyle? style,
|
||||
required bool withComposing,
|
||||
}) {
|
||||
if (_marks.isEmpty) {
|
||||
return super.buildTextSpan(
|
||||
context: context,
|
||||
style: style,
|
||||
withComposing: withComposing,
|
||||
);
|
||||
}
|
||||
final theme = Theme.of(context);
|
||||
final children = <InlineSpan>[];
|
||||
var offset = 0;
|
||||
for (final mark in _marks) {
|
||||
if (mark.start > offset) {
|
||||
children.add(TextSpan(text: text.substring(offset, mark.start)));
|
||||
}
|
||||
final color = mark.valid
|
||||
? AppTheme.composerReferenceColor(context)
|
||||
: theme.colorScheme.error;
|
||||
children.add(
|
||||
WidgetSpan(
|
||||
alignment: PlaceholderAlignment.middle,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(right: 4),
|
||||
child: Icon(
|
||||
mark.reference.kind == ComposerReferenceKind.timeline
|
||||
? Icons.view_timeline_outlined
|
||||
: Icons.attach_file,
|
||||
size: 14,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
children.add(
|
||||
TextSpan(
|
||||
text: text.substring(mark.start + 1, mark.end),
|
||||
style: TextStyle(color: color, fontWeight: FontWeight.w600),
|
||||
),
|
||||
);
|
||||
offset = mark.end;
|
||||
}
|
||||
if (offset < text.length) {
|
||||
children.add(TextSpan(text: text.substring(offset)));
|
||||
}
|
||||
return TextSpan(style: style, children: children);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,50 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'composer_document.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
_ComposerReference _$ComposerReferenceFromJson(Map<String, dynamic> json) =>
|
||||
_ComposerReference(
|
||||
kind: $enumDecode(_$ComposerReferenceKindEnumMap, json['kind']),
|
||||
projectId: json['projectId'] as String,
|
||||
id: json['id'] as String,
|
||||
label: json['label'] as String,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ComposerReferenceToJson(_ComposerReference instance) =>
|
||||
<String, dynamic>{
|
||||
'kind': _$ComposerReferenceKindEnumMap[instance.kind]!,
|
||||
'projectId': instance.projectId,
|
||||
'id': instance.id,
|
||||
'label': instance.label,
|
||||
};
|
||||
|
||||
const _$ComposerReferenceKindEnumMap = {
|
||||
ComposerReferenceKind.media: 'media',
|
||||
ComposerReferenceKind.timeline: 'timeline',
|
||||
};
|
||||
|
||||
ComposerText _$ComposerTextFromJson(Map<String, dynamic> json) => ComposerText(
|
||||
json['value'] as String,
|
||||
$type: json['runtimeType'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ComposerTextToJson(ComposerText instance) =>
|
||||
<String, dynamic>{'value': instance.value, 'runtimeType': instance.$type};
|
||||
|
||||
ComposerReferenceSegment _$ComposerReferenceSegmentFromJson(
|
||||
Map<String, dynamic> json,
|
||||
) => ComposerReferenceSegment(
|
||||
ComposerReference.fromJson(json['value'] as Map<String, dynamic>),
|
||||
$type: json['runtimeType'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ComposerReferenceSegmentToJson(
|
||||
ComposerReferenceSegment instance,
|
||||
) => <String, dynamic>{
|
||||
'value': instance.value.toJson(),
|
||||
'runtimeType': instance.$type,
|
||||
};
|
||||
@@ -0,0 +1,214 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
import '../../shared/layout/composer_layout.dart';
|
||||
import '../../shared/theme/composer_style.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../../workspace/project_state.dart';
|
||||
|
||||
class ComposerProjectSelector extends StatefulWidget {
|
||||
const ComposerProjectSelector({
|
||||
super.key,
|
||||
required this.projects,
|
||||
required this.selected,
|
||||
required this.busy,
|
||||
required this.onSelect,
|
||||
required this.onCreate,
|
||||
required this.backgroundColor,
|
||||
});
|
||||
|
||||
final List<RecentProject> projects;
|
||||
final RecentProject? selected;
|
||||
final bool busy;
|
||||
final ValueChanged<RecentProject> onSelect;
|
||||
final VoidCallback? onCreate;
|
||||
final Color backgroundColor;
|
||||
|
||||
@override
|
||||
State<ComposerProjectSelector> createState() =>
|
||||
_ComposerProjectSelectorState();
|
||||
}
|
||||
|
||||
class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
|
||||
final _menu = MenuController();
|
||||
final _search = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_search.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Widget _item({
|
||||
required Key key,
|
||||
required String label,
|
||||
required IconData icon,
|
||||
bool? selected,
|
||||
bool secondary = false,
|
||||
VoidCallback? onPressed,
|
||||
}) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
return MenuItemButton(
|
||||
key: key,
|
||||
onPressed: onPressed,
|
||||
style: AppComposerStyle.projectMenuItem(context, secondary: secondary),
|
||||
child: Semantics(
|
||||
selected: selected,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
icon,
|
||||
size: ComposerLayout.menuIconSize,
|
||||
color: onPressed == null
|
||||
? Theme.of(context).disabledColor
|
||||
: colors.onSurfaceVariant,
|
||||
),
|
||||
const SizedBox(width: ComposerLayout.menuIconGap),
|
||||
Expanded(
|
||||
child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
),
|
||||
if (selected == true) ...[
|
||||
const SizedBox(width: ComposerLayout.menuIconGap),
|
||||
Icon(
|
||||
Icons.check,
|
||||
size: ComposerLayout.menuIconSize,
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _separator() => const Padding(
|
||||
padding: AppComposerStyle.menuSeparatorPadding,
|
||||
child: Divider(
|
||||
height: 1,
|
||||
thickness: AppComposerStyle.menuSeparatorThickness,
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final query = _search.text.trim().toLowerCase();
|
||||
final projects = widget.projects
|
||||
.where((project) => project.name.toLowerCase().contains(query))
|
||||
.toList();
|
||||
return Material(
|
||||
key: const Key('composer-project-bar'),
|
||||
color: widget.backgroundColor,
|
||||
borderRadius: const BorderRadius.vertical(
|
||||
top: Radius.circular(ComposerLayout.utilityRadius),
|
||||
),
|
||||
child: Padding(
|
||||
padding: AppComposerStyle.utilityPadding,
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: MenuAnchor(
|
||||
controller: _menu,
|
||||
consumeOutsideTap: false,
|
||||
onClose: () => setState(_search.clear),
|
||||
style: AppComposerStyle.projectMenu(context),
|
||||
menuChildren: [
|
||||
SizedBox(
|
||||
width: ComposerLayout.menuContentWidth,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
SizedBox(
|
||||
height: ComposerLayout.menuRowHeight,
|
||||
child: TextField(
|
||||
key: const Key('composer-project-search'),
|
||||
controller: _search,
|
||||
autofocus: true,
|
||||
style: AppTheme.composerTextStyle(context),
|
||||
onChanged: (_) => setState(() {}),
|
||||
decoration: AppComposerStyle.projectSearchDecoration(
|
||||
context,
|
||||
hintText: context.l10n.searchProjects,
|
||||
),
|
||||
),
|
||||
),
|
||||
_separator(),
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(
|
||||
maxHeight: ComposerLayout.menuListMaxHeight,
|
||||
),
|
||||
child: SingleChildScrollView(
|
||||
primary: false,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (projects.isEmpty)
|
||||
Padding(
|
||||
padding: AppComposerStyle.menuEmptyPadding,
|
||||
child: Text(
|
||||
query.isEmpty
|
||||
? context.l10n.projectsNone
|
||||
: context.l10n.noMatchingProjects,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
for (final project in projects)
|
||||
_item(
|
||||
key: ValueKey('composer-project-${project.id}'),
|
||||
label: project.name,
|
||||
icon: Icons.folder_outlined,
|
||||
selected: project.id == widget.selected?.id,
|
||||
onPressed:
|
||||
widget.busy || !project.availability.canOpen
|
||||
? null
|
||||
: () {
|
||||
_menu.close();
|
||||
widget.onSelect(project);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
_separator(),
|
||||
_item(
|
||||
key: const Key('composer-new-project'),
|
||||
secondary: true,
|
||||
label: context.l10n.newProject,
|
||||
icon: Icons.add,
|
||||
onPressed: widget.busy || widget.onCreate == null
|
||||
? null
|
||||
: () {
|
||||
_menu.close();
|
||||
widget.onCreate!();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
builder: (context, controller, _) => TextButton.icon(
|
||||
key: const Key('composer-project-trigger'),
|
||||
onPressed: widget.busy
|
||||
? null
|
||||
: () => controller.isOpen
|
||||
? controller.close()
|
||||
: controller.open(),
|
||||
style: AppComposerStyle.projectTrigger(context),
|
||||
icon: const Icon(
|
||||
Icons.folder_outlined,
|
||||
size: ComposerLayout.menuIconSize,
|
||||
),
|
||||
label: Text(
|
||||
widget.selected?.name ?? context.l10n.selectProject,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import '../../workspace/project_state.dart';
|
||||
import 'composer_document.dart';
|
||||
|
||||
/// Checks draft references against the project currently open in the composer.
|
||||
final class ComposerReferenceValidator {
|
||||
const ComposerReferenceValidator({
|
||||
required this.workspace,
|
||||
required this.projectId,
|
||||
});
|
||||
|
||||
final ProjectState? workspace;
|
||||
final String? projectId;
|
||||
|
||||
bool isValid(ComposerReference reference) {
|
||||
if (projectId != reference.projectId ||
|
||||
workspace?.activeProject?.id != reference.projectId) {
|
||||
return false;
|
||||
}
|
||||
return switch (reference.kind) {
|
||||
ComposerReferenceKind.media => workspace!.assets.any(
|
||||
(asset) => asset.id == reference.id,
|
||||
),
|
||||
ComposerReferenceKind.timeline => workspace!.timelines.any(
|
||||
(timeline) => timeline.id == reference.id,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
void validate(ComposerDocumentController document) {
|
||||
document.updateValidity(isValid);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,506 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../l10n/app_localizations.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import 'composer_document.dart';
|
||||
import 'composer_suggestions.dart';
|
||||
|
||||
part 'composer_suggestion_surface.freezed.dart';
|
||||
|
||||
/// Owns suggestion focus, keyboard navigation, selection and the anchored menu.
|
||||
/// The caller supplies the composer body and the action used when Enter sends.
|
||||
class ComposerSuggestionSurface extends StatefulWidget {
|
||||
const ComposerSuggestionSurface({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.width,
|
||||
required this.projectId,
|
||||
required this.assets,
|
||||
required this.timelines,
|
||||
required this.onSend,
|
||||
required this.builder,
|
||||
});
|
||||
|
||||
final ComposerDocumentController controller;
|
||||
final double width;
|
||||
final String? projectId;
|
||||
final Iterable<AssetDocument> assets;
|
||||
final Iterable<TimelineSummary> timelines;
|
||||
final VoidCallback onSend;
|
||||
final Widget Function(BuildContext context, FocusNode inputFocus) builder;
|
||||
|
||||
@override
|
||||
State<ComposerSuggestionSurface> createState() =>
|
||||
_ComposerSuggestionSurfaceState();
|
||||
}
|
||||
|
||||
class _ComposerSuggestionSurfaceState extends State<ComposerSuggestionSurface> {
|
||||
final _focus = FocusNode();
|
||||
final _link = LayerLink();
|
||||
final _portal = OverlayPortalController();
|
||||
final _anchorKey = GlobalKey();
|
||||
final _tapGroup = Object();
|
||||
final _menuScrollController = ScrollController(keepScrollOffset: false);
|
||||
ComposerTriggerQuery? _trigger;
|
||||
int _selected = 0;
|
||||
ComposerTriggerQuery? _suppressedQuery;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
widget.controller.addListener(_onDocumentChanged);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ComposerSuggestionSurface oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.controller != widget.controller) {
|
||||
oldWidget.controller.removeListener(_onDocumentChanged);
|
||||
widget.controller.addListener(_onDocumentChanged);
|
||||
_onDocumentChanged();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
widget.controller.removeListener(_onDocumentChanged);
|
||||
_menuScrollController.dispose();
|
||||
_focus.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onDocumentChanged() {
|
||||
final candidate = findComposerTrigger(
|
||||
widget.controller.value,
|
||||
widget.controller.marks,
|
||||
);
|
||||
final suppressed = _suppressedQuery;
|
||||
final stillSuppressed =
|
||||
candidate != null &&
|
||||
suppressed != null &&
|
||||
candidate.start == suppressed.start &&
|
||||
candidate.trigger == suppressed.trigger &&
|
||||
candidate.query == suppressed.query;
|
||||
if (!stillSuppressed) _suppressedQuery = null;
|
||||
final next = stillSuppressed ? null : candidate;
|
||||
if (next?.start == _trigger?.start &&
|
||||
next?.query == _trigger?.query &&
|
||||
next?.trigger == _trigger?.trigger) {
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_trigger = next;
|
||||
_selected = 0;
|
||||
});
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
if (_menuScrollController.hasClients) _menuScrollController.jumpTo(0);
|
||||
if (_trigger == null) {
|
||||
if (_portal.isShowing) _portal.hide();
|
||||
} else if (!_portal.isShowing) {
|
||||
_portal.show();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _dismiss({bool suppress = false}) {
|
||||
if (suppress) _suppressedQuery = _trigger;
|
||||
setState(() => _trigger = null);
|
||||
if (_portal.isShowing) _portal.hide();
|
||||
}
|
||||
|
||||
List<ComposerOption> _options(ComposerTriggerQuery query) =>
|
||||
filterComposerOptions(
|
||||
ComposerOptionCatalog.forTrigger(
|
||||
query.trigger,
|
||||
l10n: AppLocalizations.of(context)!,
|
||||
projectId: widget.projectId,
|
||||
assets: widget.assets,
|
||||
timelines: widget.timelines,
|
||||
),
|
||||
query.query,
|
||||
);
|
||||
|
||||
void _select(ComposerOption option) {
|
||||
final query = _trigger;
|
||||
if (query == null) return;
|
||||
_dismiss();
|
||||
switch (option) {
|
||||
case ComposerReferenceOption(:final reference):
|
||||
widget.controller.insertReference(query.start, query.end, reference);
|
||||
case ComposerTextOption(:final text):
|
||||
widget.controller.value = widget.controller.value.copyWith(
|
||||
text: widget.controller.text.replaceRange(
|
||||
query.start,
|
||||
query.end,
|
||||
text,
|
||||
),
|
||||
selection: TextSelection.collapsed(offset: query.start + text.length),
|
||||
);
|
||||
case ComposerPickerOption(:final onInvoke):
|
||||
case ComposerInvokeOption(:final onInvoke):
|
||||
onInvoke();
|
||||
}
|
||||
_focus.requestFocus();
|
||||
}
|
||||
|
||||
void _selectCurrent() {
|
||||
final query = _trigger;
|
||||
if (query == null) return;
|
||||
final options = _options(query);
|
||||
if (options.isNotEmpty) {
|
||||
_select(options[_selected.clamp(0, options.length - 1)]);
|
||||
}
|
||||
}
|
||||
|
||||
void _move(int delta) {
|
||||
final query = _trigger;
|
||||
if (query == null) return;
|
||||
final options = _options(query);
|
||||
final count = options.length;
|
||||
if (count > 0) {
|
||||
setState(() => _selected = (_selected + delta + count) % count);
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted || !_menuScrollController.hasClients) return;
|
||||
final currentQuery = _trigger;
|
||||
if (currentQuery == null) return;
|
||||
final rows = _rows(_options(currentQuery));
|
||||
var top = AppMenuMetrics.gutter;
|
||||
for (final row in rows) {
|
||||
if (row case _SuggestionOption(optionIndex: final index)
|
||||
when index == _selected) {
|
||||
final position = _menuScrollController.position;
|
||||
final bottom = top + row.height;
|
||||
final visibleTop = position.pixels;
|
||||
final visibleBottom = visibleTop + position.viewportDimension;
|
||||
final target = top < visibleTop
|
||||
? top - 4
|
||||
: bottom > visibleBottom
|
||||
? bottom - position.viewportDimension + 4
|
||||
: null;
|
||||
if (target != null) {
|
||||
_menuScrollController.animateTo(
|
||||
target.clamp(
|
||||
position.minScrollExtent,
|
||||
position.maxScrollExtent,
|
||||
),
|
||||
duration: const Duration(milliseconds: 120),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
top += row.height;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
List<_SuggestionRow> _rows(List<ComposerOption> options) {
|
||||
final rows = <_SuggestionRow>[];
|
||||
for (final group in ComposerOptionGroup.values) {
|
||||
final grouped = options.indexed.where((entry) => entry.$2.group == group);
|
||||
if (grouped.isEmpty) continue;
|
||||
rows.add(_SuggestionRow.header(group, rows.isEmpty ? 28 : 36));
|
||||
for (final (index, option) in grouped) {
|
||||
rows.add(_SuggestionRow.option(option, index));
|
||||
}
|
||||
}
|
||||
for (final (index, option) in options.indexed) {
|
||||
if (option.group == null) {
|
||||
rows.add(_SuggestionRow.option(option, index));
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
Widget _menu(BuildContext context) {
|
||||
final query = _trigger;
|
||||
if (query == null) return const SizedBox.shrink();
|
||||
final options = _options(query);
|
||||
final rows = _rows(options);
|
||||
final anchor = _anchorKey.currentContext?.findRenderObject();
|
||||
final availableAbove = anchor is RenderBox
|
||||
? anchor.localToGlobal(Offset.zero).dy - 16
|
||||
: MediaQuery.sizeOf(context).height / 2;
|
||||
final placeBelow = availableAbove < 100;
|
||||
final maxHeight = placeBelow
|
||||
? (MediaQuery.sizeOf(context).height - availableAbove - 120).clamp(
|
||||
72.0,
|
||||
320.0,
|
||||
)
|
||||
: availableAbove.clamp(72.0, 320.0);
|
||||
final theme = Theme.of(context);
|
||||
return Stack(
|
||||
children: [
|
||||
CompositedTransformFollower(
|
||||
link: _link,
|
||||
showWhenUnlinked: false,
|
||||
targetAnchor: placeBelow ? Alignment.bottomLeft : Alignment.topLeft,
|
||||
followerAnchor: placeBelow ? Alignment.topLeft : Alignment.bottomLeft,
|
||||
offset: Offset(0, placeBelow ? 4 : -4),
|
||||
child: TapRegion(
|
||||
groupId: _tapGroup,
|
||||
child: Material(
|
||||
color: AppTheme.popoverBackground(context),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(AppMenuMetrics.radius),
|
||||
side: BorderSide(
|
||||
color: theme.colorScheme.outlineVariant,
|
||||
width: AppMenuMetrics.borderWidth,
|
||||
),
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: SizedBox(
|
||||
key: const Key('agent-composer-suggestions'),
|
||||
width: widget.width,
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxHeight: maxHeight),
|
||||
child: options.isEmpty
|
||||
? Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Text(
|
||||
AppLocalizations.of(context)!.noAvailableOptions,
|
||||
),
|
||||
)
|
||||
: ListView.builder(
|
||||
key: const Key('agent-composer-suggestion-list'),
|
||||
controller: _menuScrollController,
|
||||
shrinkWrap: true,
|
||||
padding: const EdgeInsets.all(AppMenuMetrics.gutter),
|
||||
itemCount: rows.length,
|
||||
itemBuilder: (context, index) {
|
||||
final row = rows[index];
|
||||
if (row case _SuggestionHeader(:final group)) {
|
||||
final labels = AppLocalizations.of(context)!;
|
||||
return Container(
|
||||
key: Key(
|
||||
'agent-suggestion-group-${group.name}',
|
||||
),
|
||||
height: row.height,
|
||||
alignment: Alignment.centerLeft,
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
10,
|
||||
index == 0 ? 4 : 12,
|
||||
10,
|
||||
5,
|
||||
),
|
||||
child: Text(
|
||||
switch (group) {
|
||||
ComposerOptionGroup.media =>
|
||||
labels.materials,
|
||||
ComposerOptionGroup.timeline =>
|
||||
labels.timelines,
|
||||
},
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final _SuggestionOption(:option, :optionIndex) =
|
||||
row as _SuggestionOption;
|
||||
final selected = optionIndex == _selected;
|
||||
return InkWell(
|
||||
key: Key(
|
||||
'agent-suggestion-${option is ComposerReferenceOption ? option.reference.kind.name : option.trigger}-${option is ComposerReferenceOption ? option.reference.id : index}',
|
||||
),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppMenuMetrics.itemRadius,
|
||||
),
|
||||
onTap: () => _select(option),
|
||||
child: Container(
|
||||
height: 40,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 10,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: selected
|
||||
? theme.colorScheme.onSurface.withValues(
|
||||
alpha: .1,
|
||||
)
|
||||
: null,
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppMenuMetrics.itemRadius,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(option.icon, size: 15),
|
||||
const SizedBox(
|
||||
width: AppMenuMetrics.iconGap,
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
option.title,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodyMedium,
|
||||
),
|
||||
),
|
||||
if (option.group == null &&
|
||||
option.subtitle.isNotEmpty) ...[
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
option.subtitle,
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final content = widget.builder(context, _focus);
|
||||
return OverlayPortal(
|
||||
controller: _portal,
|
||||
overlayChildBuilder: _menu,
|
||||
child: TapRegion(
|
||||
groupId: _tapGroup,
|
||||
onTapOutside: (_) {
|
||||
if (_trigger != null) _dismiss(suppress: true);
|
||||
},
|
||||
child: CompositedTransformTarget(
|
||||
key: _anchorKey,
|
||||
link: _link,
|
||||
child: ValueListenableBuilder<TextEditingValue>(
|
||||
valueListenable: widget.controller,
|
||||
child: content,
|
||||
builder: (context, value, child) {
|
||||
final composing =
|
||||
value.composing.isValid && !value.composing.isCollapsed;
|
||||
final enter = composing
|
||||
? const DoNothingAndStopPropagationIntent()
|
||||
: _trigger != null
|
||||
? const _SelectSuggestionIntent()
|
||||
: const _SendComposerIntent();
|
||||
return Shortcuts(
|
||||
shortcuts: {
|
||||
const SingleActivator(LogicalKeyboardKey.enter): enter,
|
||||
const SingleActivator(LogicalKeyboardKey.numpadEnter): enter,
|
||||
if (_trigger != null) ...{
|
||||
const SingleActivator(LogicalKeyboardKey.arrowDown):
|
||||
const _MoveSuggestionIntent(1),
|
||||
const SingleActivator(LogicalKeyboardKey.arrowUp):
|
||||
const _MoveSuggestionIntent(-1),
|
||||
const SingleActivator(LogicalKeyboardKey.escape):
|
||||
const _DismissSuggestionIntent(),
|
||||
},
|
||||
const SingleActivator(LogicalKeyboardKey.keyZ, meta: true):
|
||||
const _UndoComposerIntent(),
|
||||
const SingleActivator(
|
||||
LogicalKeyboardKey.keyZ,
|
||||
meta: true,
|
||||
shift: true,
|
||||
): const _RedoComposerIntent(),
|
||||
},
|
||||
child: Actions(
|
||||
actions: {
|
||||
_SendComposerIntent: CallbackAction<_SendComposerIntent>(
|
||||
onInvoke: (_) {
|
||||
widget.onSend();
|
||||
return null;
|
||||
},
|
||||
),
|
||||
_SelectSuggestionIntent:
|
||||
CallbackAction<_SelectSuggestionIntent>(
|
||||
onInvoke: (_) {
|
||||
_selectCurrent();
|
||||
return null;
|
||||
},
|
||||
),
|
||||
_MoveSuggestionIntent:
|
||||
CallbackAction<_MoveSuggestionIntent>(
|
||||
onInvoke: (intent) {
|
||||
_move(intent.delta);
|
||||
return null;
|
||||
},
|
||||
),
|
||||
_DismissSuggestionIntent:
|
||||
CallbackAction<_DismissSuggestionIntent>(
|
||||
onInvoke: (_) {
|
||||
_dismiss(suppress: true);
|
||||
return null;
|
||||
},
|
||||
),
|
||||
_UndoComposerIntent: CallbackAction<_UndoComposerIntent>(
|
||||
onInvoke: (_) {
|
||||
widget.controller.undoDocument();
|
||||
return null;
|
||||
},
|
||||
),
|
||||
_RedoComposerIntent: CallbackAction<_RedoComposerIntent>(
|
||||
onInvoke: (_) {
|
||||
widget.controller.redoDocument();
|
||||
return null;
|
||||
},
|
||||
),
|
||||
},
|
||||
child: child!,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SendComposerIntent extends Intent {
|
||||
const _SendComposerIntent();
|
||||
}
|
||||
|
||||
class _SelectSuggestionIntent extends Intent {
|
||||
const _SelectSuggestionIntent();
|
||||
}
|
||||
|
||||
class _MoveSuggestionIntent extends Intent {
|
||||
const _MoveSuggestionIntent(this.delta);
|
||||
final int delta;
|
||||
}
|
||||
|
||||
class _DismissSuggestionIntent extends Intent {
|
||||
const _DismissSuggestionIntent();
|
||||
}
|
||||
|
||||
class _UndoComposerIntent extends Intent {
|
||||
const _UndoComposerIntent();
|
||||
}
|
||||
|
||||
class _RedoComposerIntent extends Intent {
|
||||
const _RedoComposerIntent();
|
||||
}
|
||||
|
||||
@freezed
|
||||
sealed class _SuggestionRow with _$SuggestionRow {
|
||||
const _SuggestionRow._();
|
||||
const factory _SuggestionRow.header(
|
||||
ComposerOptionGroup group,
|
||||
double height,
|
||||
) = _SuggestionHeader;
|
||||
const factory _SuggestionRow.option(ComposerOption option, int optionIndex) =
|
||||
_SuggestionOption;
|
||||
double get height => switch (this) {
|
||||
_SuggestionHeader(:final height) => height,
|
||||
_SuggestionOption() => 40,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'composer_suggestion_surface.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$SuggestionRow {
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType && other is _SuggestionRow);
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => runtimeType.hashCode;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return '_SuggestionRow()';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$SuggestionRowCopyWith<$Res> {
|
||||
_$SuggestionRowCopyWith(_SuggestionRow _, $Res Function(_SuggestionRow) __);
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [_SuggestionRow].
|
||||
extension _SuggestionRowPatterns on _SuggestionRow {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>({
|
||||
TResult Function(_SuggestionHeader value)? header,
|
||||
TResult Function(_SuggestionOption value)? option,
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SuggestionHeader() when header != null:
|
||||
return header(_that);
|
||||
case _SuggestionOption() when option != null:
|
||||
return option(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>({
|
||||
required TResult Function(_SuggestionHeader value) header,
|
||||
required TResult Function(_SuggestionOption value) option,
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SuggestionHeader():
|
||||
return header(_that);
|
||||
case _SuggestionOption():
|
||||
return option(_that);
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>({
|
||||
TResult? Function(_SuggestionHeader value)? header,
|
||||
TResult? Function(_SuggestionOption value)? option,
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SuggestionHeader() when header != null:
|
||||
return header(_that);
|
||||
case _SuggestionOption() when option != null:
|
||||
return option(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>({
|
||||
TResult Function(ComposerOptionGroup group, double height)? header,
|
||||
TResult Function(ComposerOption option, int optionIndex)? option,
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SuggestionHeader() when header != null:
|
||||
return header(_that.group, _that.height);
|
||||
case _SuggestionOption() when option != null:
|
||||
return option(_that.option, _that.optionIndex);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>({
|
||||
required TResult Function(ComposerOptionGroup group, double height) header,
|
||||
required TResult Function(ComposerOption option, int optionIndex) option,
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SuggestionHeader():
|
||||
return header(_that.group, _that.height);
|
||||
case _SuggestionOption():
|
||||
return option(_that.option, _that.optionIndex);
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>({
|
||||
TResult? Function(ComposerOptionGroup group, double height)? header,
|
||||
TResult? Function(ComposerOption option, int optionIndex)? option,
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SuggestionHeader() when header != null:
|
||||
return header(_that.group, _that.height);
|
||||
case _SuggestionOption() when option != null:
|
||||
return option(_that.option, _that.optionIndex);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _SuggestionHeader extends _SuggestionRow {
|
||||
const _SuggestionHeader(this.group, this.height) : super._();
|
||||
|
||||
final ComposerOptionGroup group;
|
||||
final double height;
|
||||
|
||||
/// Create a copy of _SuggestionRow
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$SuggestionHeaderCopyWith<_SuggestionHeader> get copyWith =>
|
||||
__$SuggestionHeaderCopyWithImpl<_SuggestionHeader>(this, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _SuggestionHeader &&
|
||||
(identical(other.group, group) || other.group == group) &&
|
||||
(identical(other.height, height) || other.height == height));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, group, height);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return '_SuggestionRow.header(group: $group, height: $height)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$SuggestionHeaderCopyWith<$Res>
|
||||
implements _$SuggestionRowCopyWith<$Res> {
|
||||
factory _$SuggestionHeaderCopyWith(
|
||||
_SuggestionHeader value,
|
||||
$Res Function(_SuggestionHeader) _then,
|
||||
) = __$SuggestionHeaderCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({ComposerOptionGroup group, double height});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$SuggestionHeaderCopyWithImpl<$Res>
|
||||
implements _$SuggestionHeaderCopyWith<$Res> {
|
||||
__$SuggestionHeaderCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _SuggestionHeader _self;
|
||||
final $Res Function(_SuggestionHeader) _then;
|
||||
|
||||
/// Create a copy of _SuggestionRow
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({Object? group = null, Object? height = null}) {
|
||||
return _then(
|
||||
_SuggestionHeader(
|
||||
null == group
|
||||
? _self.group
|
||||
: group // ignore: cast_nullable_to_non_nullable
|
||||
as ComposerOptionGroup,
|
||||
null == height
|
||||
? _self.height
|
||||
: height // ignore: cast_nullable_to_non_nullable
|
||||
as double,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _SuggestionOption extends _SuggestionRow {
|
||||
const _SuggestionOption(this.option, this.optionIndex) : super._();
|
||||
|
||||
final ComposerOption option;
|
||||
final int optionIndex;
|
||||
|
||||
/// Create a copy of _SuggestionRow
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$SuggestionOptionCopyWith<_SuggestionOption> get copyWith =>
|
||||
__$SuggestionOptionCopyWithImpl<_SuggestionOption>(this, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _SuggestionOption &&
|
||||
(identical(other.option, option) || other.option == option) &&
|
||||
(identical(other.optionIndex, optionIndex) ||
|
||||
other.optionIndex == optionIndex));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, option, optionIndex);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return '_SuggestionRow.option(option: $option, optionIndex: $optionIndex)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$SuggestionOptionCopyWith<$Res>
|
||||
implements _$SuggestionRowCopyWith<$Res> {
|
||||
factory _$SuggestionOptionCopyWith(
|
||||
_SuggestionOption value,
|
||||
$Res Function(_SuggestionOption) _then,
|
||||
) = __$SuggestionOptionCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({ComposerOption option, int optionIndex});
|
||||
|
||||
$ComposerOptionCopyWith<$Res> get option;
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$SuggestionOptionCopyWithImpl<$Res>
|
||||
implements _$SuggestionOptionCopyWith<$Res> {
|
||||
__$SuggestionOptionCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _SuggestionOption _self;
|
||||
final $Res Function(_SuggestionOption) _then;
|
||||
|
||||
/// Create a copy of _SuggestionRow
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({Object? option = null, Object? optionIndex = null}) {
|
||||
return _then(
|
||||
_SuggestionOption(
|
||||
null == option
|
||||
? _self.option
|
||||
: option // ignore: cast_nullable_to_non_nullable
|
||||
as ComposerOption,
|
||||
null == optionIndex
|
||||
? _self.optionIndex
|
||||
: optionIndex // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Create a copy of _SuggestionRow
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$ComposerOptionCopyWith<$Res> get option {
|
||||
return $ComposerOptionCopyWith<$Res>(_self.option, (value) {
|
||||
return _then(_self.copyWith(option: value));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../l10n/app_localizations.dart';
|
||||
import 'composer_document.dart';
|
||||
|
||||
part 'composer_suggestions.freezed.dart';
|
||||
|
||||
enum ComposerOptionGroup { media, timeline }
|
||||
|
||||
@freezed
|
||||
sealed class ComposerOption with _$ComposerOption {
|
||||
const factory ComposerOption.reference({
|
||||
required String trigger,
|
||||
required String title,
|
||||
required String subtitle,
|
||||
required IconData icon,
|
||||
ComposerOptionGroup? group,
|
||||
required ComposerReference reference,
|
||||
}) = ComposerReferenceOption;
|
||||
const factory ComposerOption.text({
|
||||
required String trigger,
|
||||
required String title,
|
||||
required String subtitle,
|
||||
required IconData icon,
|
||||
ComposerOptionGroup? group,
|
||||
required String text,
|
||||
}) = ComposerTextOption;
|
||||
const factory ComposerOption.invoke({
|
||||
required String trigger,
|
||||
required String title,
|
||||
required String subtitle,
|
||||
required IconData icon,
|
||||
ComposerOptionGroup? group,
|
||||
required VoidCallback onInvoke,
|
||||
}) = ComposerInvokeOption;
|
||||
const factory ComposerOption.openPicker({
|
||||
required String trigger,
|
||||
required String title,
|
||||
required String subtitle,
|
||||
required IconData icon,
|
||||
ComposerOptionGroup? group,
|
||||
required VoidCallback onInvoke,
|
||||
}) = ComposerPickerOption;
|
||||
}
|
||||
|
||||
/// System-owned entries. More triggers and actions register here later.
|
||||
abstract final class ComposerOptionCatalog {
|
||||
static List<ComposerOption> forTrigger(
|
||||
String trigger, {
|
||||
required AppLocalizations l10n,
|
||||
required String? projectId,
|
||||
required Iterable<AssetDocument> assets,
|
||||
required Iterable<TimelineSummary> timelines,
|
||||
}) {
|
||||
if (trigger != '@' || projectId == null) return const [];
|
||||
return [
|
||||
for (final asset in assets)
|
||||
ComposerOption.reference(
|
||||
trigger: '@',
|
||||
title: asset.name,
|
||||
subtitle: l10n.materials,
|
||||
icon: switch (asset.metadata['kind']) {
|
||||
'video' => Icons.movie_outlined,
|
||||
'audio' => Icons.audiotrack_outlined,
|
||||
'image' => Icons.image_outlined,
|
||||
_ => Icons.insert_drive_file_outlined,
|
||||
},
|
||||
group: ComposerOptionGroup.media,
|
||||
reference: ComposerReference(
|
||||
kind: ComposerReferenceKind.media,
|
||||
projectId: projectId,
|
||||
id: asset.id,
|
||||
label: asset.name,
|
||||
),
|
||||
),
|
||||
for (final timeline in timelines)
|
||||
ComposerOption.reference(
|
||||
trigger: '@',
|
||||
title: timeline.name,
|
||||
subtitle: l10n.timelines,
|
||||
icon: Icons.view_timeline_outlined,
|
||||
group: ComposerOptionGroup.timeline,
|
||||
reference: ComposerReference(
|
||||
kind: ComposerReferenceKind.timeline,
|
||||
projectId: projectId,
|
||||
id: timeline.id,
|
||||
label: timeline.name,
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ComposerTriggerQuery with _$ComposerTriggerQuery {
|
||||
const factory ComposerTriggerQuery({
|
||||
required String trigger,
|
||||
required int start,
|
||||
required int end,
|
||||
required String query,
|
||||
}) = _ComposerTriggerQuery;
|
||||
}
|
||||
|
||||
ComposerTriggerQuery? findComposerTrigger(
|
||||
TextEditingValue value,
|
||||
Iterable<ComposerMark> marks,
|
||||
) {
|
||||
if (!value.selection.isValid || !value.selection.isCollapsed) return null;
|
||||
if (value.composing.isValid && !value.composing.isCollapsed) return null;
|
||||
final caret = value.selection.extentOffset;
|
||||
if (caret <= 0 || caret > value.text.length) return null;
|
||||
for (final mark in marks) {
|
||||
if (caret > mark.start && caret <= mark.end) return null;
|
||||
}
|
||||
final lineStart = value.text.lastIndexOf('\n', caret - 1) + 1;
|
||||
for (var i = caret - 1; i >= lineStart; i--) {
|
||||
final char = value.text[i];
|
||||
if (char != '@' && char != '/' && char != r'$') continue;
|
||||
if (i > 0 &&
|
||||
!RegExp(r'[\s(\[{,;:!?,。!?;:、(“\u3400-\u9fff]')
|
||||
.hasMatch(value.text[i - 1])) {
|
||||
continue;
|
||||
}
|
||||
if (caret - i > 128) return null;
|
||||
if (marks.any((mark) => i >= mark.start && i < mark.end)) return null;
|
||||
final query = value.text.substring(i + 1, caret);
|
||||
if (char == '/' && (query.contains('/') || query.contains('\\'))) {
|
||||
return null;
|
||||
}
|
||||
return ComposerTriggerQuery(
|
||||
trigger: char,
|
||||
start: i,
|
||||
end: caret,
|
||||
query: query,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
List<ComposerOption> filterComposerOptions(
|
||||
Iterable<ComposerOption> options,
|
||||
String query,
|
||||
) {
|
||||
final normalized = query.trim().toLowerCase();
|
||||
if (normalized.isEmpty) return options.toList();
|
||||
return options
|
||||
.where((option) => option.title.toLowerCase().contains(normalized))
|
||||
.toList();
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,64 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../../workspace/project_state.dart';
|
||||
|
||||
import '../projects/conversation_sidebar.dart';
|
||||
import 'agent_chat_panel.dart';
|
||||
import 'agent_composer_store.dart';
|
||||
import 'composer_project_selector.dart';
|
||||
|
||||
/// Shared conversation presentation, independent of the navigation sidebar.
|
||||
class WorkspaceAgentSurface extends ConsumerWidget {
|
||||
const WorkspaceAgentSurface({
|
||||
super.key,
|
||||
required this.state,
|
||||
required this.onSelectProject,
|
||||
required this.onCreateProject,
|
||||
});
|
||||
|
||||
final ProjectState state;
|
||||
final ValueChanged<RecentProject>? onSelectProject;
|
||||
final VoidCallback? onCreateProject;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final selection = ref.watch(
|
||||
conversationSelectionProvider(state.activeProject?.id),
|
||||
);
|
||||
final conversations = ref.read(conversationSidebarProvider.notifier);
|
||||
final composers = ref.watch(agentComposerStoreProvider);
|
||||
final projectId = state.activeProject?.id;
|
||||
final conversationId = selection.selectedId;
|
||||
return AgentChatPanel(
|
||||
key: ValueKey((projectId, conversationId ?? selection.draftKey)),
|
||||
inputController: composers.input(projectId, conversationId),
|
||||
composer: composers.composer(
|
||||
projectId,
|
||||
conversationId ?? selection.draftKey,
|
||||
),
|
||||
projectSelector: ComposerProjectSelector(
|
||||
backgroundColor: AppTheme.composerUtilityBackground(context),
|
||||
projects: state.recent,
|
||||
selected: state.activeProject,
|
||||
busy: state.projectBusy,
|
||||
onSelect: (project) => onSelectProject?.call(project),
|
||||
onCreate: onCreateProject,
|
||||
),
|
||||
composerColor: AppSurfaces.of(context).composerBackground,
|
||||
projectId: projectId,
|
||||
timelineId: state.timeline?.id,
|
||||
conversationId: conversationId,
|
||||
draftKey: conversationId == null ? selection.draftKey : null,
|
||||
onConversationCreated: (item) => unawaited(
|
||||
conversations.updateListing(item, selectIfDraftKey: selection.draftKey),
|
||||
),
|
||||
onConversationUpdated: (item) =>
|
||||
unawaited(conversations.updateListing(item)),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user