import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:cutdex_agent/cutdex_agent.dart'; import 'package:cutdex_agent/io.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:uuid/uuid.dart'; import '../../persistence/app_settings_repositories.dart'; import '../../errors/app_failure.dart'; part 'conversation_repository.g.dart'; part 'conversation_repository.freezed.dart'; @Riverpod(keepAlive: true) ConversationLocation conversationLocation(Ref ref) => ConversationLocation( ref.watch(conversationLocationSettingsRepositoryProvider), ); @Riverpod(keepAlive: true) FutureOr conversationRepository(Ref ref) async => ConversationRepository( await ref.watch(conversationLocationProvider).load(), ); /// The location pointer is replaceable; the conversation files are not app data. class ConversationLocation { ConversationLocation( this._settings, { Future Function()? documentsDirectory, }) : _documentsDirectory = documentsDirectory ?? getApplicationDocumentsDirectory; final ConversationLocationSettingsRepository _settings; final Future Function() _documentsDirectory; Future load() async { final configured = await _settings.load(); if (configured != null) { final root = Directory(configured); if (!root.isAbsolute || !await root.exists()) { throw AppException( AppErrorCode.agentLocationUnavailable, diagnostic: root.path, ); } return root; } final documents = await _documentsDirectory(); return Directory(p.join(documents.path, 'Cutdex', 'Conversations')); } Future useExisting(Directory root) async { if (!root.isAbsolute || !await root.exists()) { throw AppException( AppErrorCode.agentLocationUnavailable, diagnostic: root.path, ); } if (!await ConversationRepository(root).verify()) { throw const FormatException('Invalid conversation directory'); } await _settings.save(root.path); } Future relocate(Directory source, Directory target) async { if (!target.isAbsolute || await target.exists()) { throw const FileSystemException( 'Destination must be an unused directory', ); } final sourcePath = p.normalize(source.absolute.path); final targetPath = p.normalize(target.absolute.path); if (targetPath == sourcePath || p.isWithin(sourcePath, targetPath)) { throw const FileSystemException( 'Destination cannot be inside the current conversations directory', ); } final staging = await target.parent.createTemp('.cutdex-conversations-'); try { await _copyDirectory(source, staging); if (!(await ConversationRepository(staging).verify())) { throw const FormatException('Copied conversations failed validation'); } await staging.rename(target.path); await _settings.save(target.path); } finally { if (await staging.exists()) await staging.delete(recursive: true); } } static Future _copyDirectory(Directory source, Directory target) async { if (!await source.exists()) return; await for (final entry in source.list(followLinks: false)) { final destination = p.join(target.path, p.basename(entry.path)); if (entry is Directory) { final child = await Directory(destination).create(); await _copyDirectory(entry, child); } else if (entry is File) { await entry.copy(destination); } else { throw const FileSystemException('Unsupported conversation entry'); } } } } @freezed abstract class ConversationMetadata with _$ConversationMetadata { const factory ConversationMetadata({ required String id, required String projectId, required String title, required DateTime createdAt, required DateTime updatedAt, required String providerId, required String modelId, required String timelineId, @JsonKey(required: true, disallowNullValue: true) required bool pending, @JsonKey(required: true, disallowNullValue: true) required List responseDurationsMs, }) = _ConversationMetadata; factory ConversationMetadata.fromJson(Map json) => _$ConversationMetadataFromJson(json); } /// Owns project-to-conversation membership; the Agent owns journal contents. class ConversationRepository { ConversationRepository(this.root); final Directory root; static const _uuid = Uuid(); final Set _pendingInProcess = {}; String _projectName(String id) => base64Url.encode(utf8.encode(id)).replaceAll('=', ''); Directory _project(String id, {bool trash = false}) => Directory(p.joinAll([root.path, if (trash) 'Trash', _projectName(id)])); Directory directory( String projectId, String conversationId, { bool trash = false, }) { if (!Uuid.isValidUUID(fromString: conversationId)) { throw ArgumentError.value(conversationId, 'conversationId'); } return Directory( p.join(_project(projectId, trash: trash).path, conversationId), ); } FileSessionStore store(ConversationMetadata conversation) => FileSessionStore(directory(conversation.projectId, conversation.id)); Future begin({ required String projectId, required String timelineId, required String providerId, required String modelId, required String title, }) async { final now = DateTime.now().toUtc(); final item = ConversationMetadata( id: _uuid.v4(), projectId: projectId, title: title.trim(), createdAt: now, updatedAt: now, providerId: providerId, modelId: modelId, timelineId: timelineId, pending: true, responseDurationsMs: const [], ); await directory(projectId, item.id).create(recursive: true); await _write(item); _pendingInProcess.add(item.id); return item; } Future publish(ConversationMetadata item) async { final snapshot = await store(item).read(item.id); if (snapshot == null || !snapshot.history.any((message) => message.role == MessageRole.user)) { throw StateError('Conversation has no saved user message'); } final published = item.copyWith( pending: false, updatedAt: DateTime.now().toUtc(), ); await _write(published); _pendingInProcess.remove(item.id); return published; } Future read( String projectId, String id, { bool trash = false, }) async { final file = File( p.join(directory(projectId, id, trash: trash).path, 'metadata.json'), ); if (!await file.exists()) return null; final json = (jsonDecode(await file.readAsString()) as Map) .cast(); final item = ConversationMetadata.fromJson(json); if (item.id != id || item.projectId != projectId) { throw const FormatException('Conversation identity mismatch'); } return item; } Future> list( String projectId, { bool trash = false, }) async { final parent = _project(projectId, trash: trash); if (!await parent.exists()) return []; final result = []; await for (final entry in parent.list(followLinks: false)) { if (entry is! Directory) continue; try { final item = await read( projectId, p.basename(entry.path), trash: trash, ); if (item == null) { continue; } if (item.pending && !trash) { if (_pendingInProcess.contains(item.id)) continue; final snapshot = await store(item).read(item.id); if (snapshot?.history.any( (message) => message.role == MessageRole.user, ) == true) { result.add(await publish(item)); } else { await entry.delete(recursive: true); } } else { result.add(item); } } on FormatException { // One corrupt metadata file must not hide the remaining conversations. } on BadKeyException { // Entries outside the current metadata contract stay untouched. } on TypeError { // Malformed field types are isolated to the affected conversation. } on FileSystemException { // A damaged or inaccessible entry does not hide its siblings. } on ArgumentError { // Ignore unrelated folders without treating them as conversations. } } result.sort((a, b) => b.updatedAt.compareTo(a.updatedAt)); return result; } Future selected(String projectId) async { final state = File(p.join(_project(projectId).path, 'state.json')); try { final json = (jsonDecode(await state.readAsString()) as Map) .cast(); if (json['version'] != 1) { throw const FormatException('Unsupported conversation state'); } final id = json['conversationId'] as String?; if (id != null && await read(projectId, id) != null) return id; } on FileSystemException { // Missing selection is recovered from the conversation list. } on FormatException { // The selection is disposable view state. } on BadKeyException { // Select only conversations that satisfy the current metadata contract. } on TypeError { // A malformed selection is disposable view state. } on ArgumentError { // An invalid UUID is disposable view state. } return (await list(projectId)).firstOrNull?.id; } Future select(String projectId, String? id) async { if (id != null && await read(projectId, id) == null) { throw ArgumentError.value(id, 'conversationId'); } final parent = _project(projectId); await parent.create(recursive: true); await _writeJson(File(p.join(parent.path, 'state.json')), { 'version': 1, 'conversationId': id, }); } Future update(ConversationMetadata item) async { if (await read(item.projectId, item.id) == null) { throw StateError('Conversation no longer exists'); } final updated = item.copyWith(updatedAt: DateTime.now().toUtc()); await _write(updated); return updated; } Future trash(String projectId, String id) async { final source = directory(projectId, id); if (!await source.exists()) return; final wasSelected = await selected(projectId) == id; final destination = directory(projectId, id, trash: true); await destination.parent.create(recursive: true); await source.rename(destination.path); if (wasSelected) await select(projectId, null); } Future restore(String projectId, String id) async { final source = directory(projectId, id, trash: true); if (!await source.exists()) throw ArgumentError.value(id, 'conversationId'); final target = directory(projectId, id); if (await target.exists()) throw StateError('Conversation already exists'); await target.parent.create(recursive: true); await source.rename(target.path); } Future deletePermanently(String projectId, String id) async { if (await selected(projectId) == id) await select(projectId, null); for (final trash in [false, true]) { final target = directory(projectId, id, trash: trash); if (await target.exists()) await target.delete(recursive: true); } } Future verify() async { if (!await root.exists()) return true; if (!await _verifyProjects(root)) return false; final trash = Directory(p.join(root.path, 'Trash')); if (await trash.exists() && !await _verifyProjects(trash)) return false; return true; } Future _verifyProjects(Directory parent) async { await for (final project in parent.list(followLinks: false)) { if (project is! Directory || p.basename(project.path) == 'Trash') { continue; } await for (final entry in project.list(followLinks: false)) { if (entry is! Directory) continue; try { final file = File(p.join(entry.path, 'metadata.json')); final json = (jsonDecode(await file.readAsString()) as Map) .cast(); final item = ConversationMetadata.fromJson(json); if (item.id != p.basename(entry.path) || _projectName(item.projectId) != p.basename(project.path)) { return false; } await FileSessionStore(entry).verify(item.id); } catch (_) { return false; } } } return true; } Future _write(ConversationMetadata item) => _writeJson( File(p.join(directory(item.projectId, item.id).path, 'metadata.json')), item.toJson(), ); Future _writeJson(File target, Map json) async { await target.parent.create(recursive: true); final temp = File('${target.path}.${_uuid.v4()}.tmp'); try { await temp.writeAsString(jsonEncode(json), flush: true); await temp.rename(target.path); } finally { if (await temp.exists()) await temp.delete(); } } }