chore: formatting

This commit is contained in:
cogwheel0
2025-08-19 13:35:32 +05:30
parent dbe66ece8c
commit d3742944bc

View File

@@ -97,8 +97,12 @@ class ApiService {
final dataMap = options.data as Map<String, dynamic>;
debugPrint('Data type: Map');
debugPrint('Data keys: ${dataMap.keys.toList()}');
debugPrint('Has background_tasks: ${dataMap.containsKey('background_tasks')}');
debugPrint('Has session_id: ${dataMap.containsKey('session_id')}');
debugPrint(
'Has background_tasks: ${dataMap.containsKey('background_tasks')}',
);
debugPrint(
'Has session_id: ${dataMap.containsKey('session_id')}',
);
debugPrint('Has id: ${dataMap.containsKey('id')}');
debugPrint('Full data: ${jsonEncode(dataMap)}');
} else {
@@ -338,11 +342,15 @@ class ApiService {
);
if (response.data is! List) {
throw Exception('Expected array of chats, got ${response.data.runtimeType}');
throw Exception(
'Expected array of chats, got ${response.data.runtimeType}',
);
}
final pageChats = response.data as List;
debugPrint('DEBUG: Page $currentPage returned ${pageChats.length} conversations');
debugPrint(
'DEBUG: Page $currentPage returned ${pageChats.length} conversations',
);
if (pageChats.isEmpty) {
debugPrint('DEBUG: No more conversations, stopping pagination');
@@ -354,24 +362,27 @@ class ApiService {
// Safety break to avoid infinite loops (adjust as needed)
if (currentPage > 100) {
debugPrint('WARNING: Reached maximum page limit (100), stopping pagination');
debugPrint(
'WARNING: Reached maximum page limit (100), stopping pagination',
);
break;
}
}
debugPrint('DEBUG: Fetched total of ${allRegularChats.length} conversations across $currentPage pages');
debugPrint(
'DEBUG: Fetched total of ${allRegularChats.length} conversations across $currentPage pages',
);
} else {
// Original single page fetch
final regularResponse = await _dio.get(
'/api/v1/chats/',
queryParameters: {
if (limit > 0)
'page': ((skip ?? 0) / limit).floor(),
},
queryParameters: {if (limit > 0) 'page': ((skip ?? 0) / limit).floor()},
);
if (regularResponse.data is! List) {
throw Exception('Expected array of chats, got ${regularResponse.data.runtimeType}');
throw Exception(
'Expected array of chats, got ${regularResponse.data.runtimeType}',
);
}
allRegularChats = regularResponse.data as List;
@@ -381,7 +392,9 @@ class ApiService {
final archivedResponse = await _dio.get('/api/v1/chats/all/archived');
debugPrint('DEBUG: Pinned response status: ${pinnedResponse.statusCode}');
debugPrint('DEBUG: Archived response status: ${archivedResponse.statusCode}');
debugPrint(
'DEBUG: Archived response status: ${archivedResponse.statusCode}',
);
if (pinnedResponse.data is! List) {
throw Exception(
@@ -438,14 +451,21 @@ class ApiService {
for (final chatData in regularChatList) {
try {
// Debug: Check if conversation has folder_id in raw data
if (chatData.containsKey('folder_id') && chatData['folder_id'] != null) {
debugPrint('🔍 DEBUG: Found conversation with folder_id in raw data: ${chatData['id']} -> ${chatData['folder_id']}');
if (chatData.containsKey('folder_id') &&
chatData['folder_id'] != null) {
debugPrint(
'🔍 DEBUG: Found conversation with folder_id in raw data: ${chatData['id']} -> ${chatData['folder_id']}',
);
}
// Debug: Check what fields are available in the chat data
if (regularChatList.indexOf(chatData) == 0) {
debugPrint('🔍 DEBUG: Sample chat data fields: ${chatData.keys.toList()}');
debugPrint('🔍 DEBUG: Sample chat data: ${chatData.toString().substring(0, 200)}...');
debugPrint(
'🔍 DEBUG: Sample chat data fields: ${chatData.keys.toList()}',
);
debugPrint(
'🔍 DEBUG: Sample chat data: ${chatData.toString().substring(0, 200)}...',
);
}
final conversation = _parseOpenWebUIChat(chatData);
@@ -524,7 +544,9 @@ class ApiService {
// Debug logging for folder assignment
if (folderId != null) {
debugPrint('🔍 DEBUG: Conversation ${id.substring(0, 8)} has folderId: $folderId');
debugPrint(
'🔍 DEBUG: Conversation ${id.substring(0, 8)} has folderId: $folderId',
);
}
debugPrint(
@@ -614,7 +636,9 @@ class ApiService {
// Convert map to list format to use common parsing logic
messagesList = [];
for (final entry in messagesMap.entries) {
final msgData = Map<String, dynamic>.from(entry.value as Map<String, dynamic>);
final msgData = Map<String, dynamic>.from(
entry.value as Map<String, dynamic>,
);
msgData['id'] = entry.key; // Use the key as the message ID
messagesList.add(msgData);
}
@@ -793,7 +817,9 @@ class ApiService {
final response = await _dio.post('/api/v1/chats/new', data: chatData);
debugPrint('DEBUG: Create conversation response status: ${response.statusCode}');
debugPrint(
'DEBUG: Create conversation response status: ${response.statusCode}',
);
debugPrint('DEBUG: Create conversation response data: ${response.data}');
// Parse the response
@@ -831,7 +857,8 @@ class ApiService {
'content': msg.content,
'timestamp': msg.timestamp.millisecondsSinceEpoch ~/ 1000,
if (msg.role == 'assistant' && msg.model != null) 'model': msg.model,
if (msg.role == 'assistant' && msg.model != null) 'modelName': msg.model,
if (msg.role == 'assistant' && msg.model != null)
'modelName': msg.model,
if (msg.role == 'assistant') 'modelIdx': 0,
if (msg.role == 'assistant') 'done': true,
if (msg.role == 'user' && model != null) 'models': [model],
@@ -853,7 +880,8 @@ class ApiService {
'content': msg.content,
'timestamp': msg.timestamp.millisecondsSinceEpoch ~/ 1000,
if (msg.role == 'assistant' && msg.model != null) 'model': msg.model,
if (msg.role == 'assistant' && msg.model != null) 'modelName': msg.model,
if (msg.role == 'assistant' && msg.model != null)
'modelName': msg.model,
if (msg.role == 'assistant') 'modelIdx': 0,
if (msg.role == 'assistant') 'done': true,
if (msg.role == 'user' && model != null) 'models': [model],
@@ -950,8 +978,6 @@ class ApiService {
await _dio.post('/api/v1/users/user/settings', data: settings);
}
// Suggestions
Future<List<String>> getSuggestions() async {
debugPrint('DEBUG: Fetching conversation suggestions');
@@ -1496,7 +1522,9 @@ class ApiService {
Map<String, dynamic>? modelItem,
String? sessionId,
}) async {
debugPrint('DEBUG: Sending chat completed notification (optional endpoint)');
debugPrint(
'DEBUG: Sending chat completed notification (optional endpoint)',
);
// This endpoint appears to be optional or deprecated in newer OpenWebUI versions
// The main chat synchronization happens through /api/v1/chats/{id} updates
@@ -1509,7 +1537,8 @@ class ApiService {
// Don't include 'id' - it causes 400 error with detail: 'id'
'role': msg['role'],
'content': msg['content'],
'timestamp': msg['timestamp'] ?? DateTime.now().millisecondsSinceEpoch ~/ 1000,
'timestamp':
msg['timestamp'] ?? DateTime.now().millisecondsSinceEpoch ~/ 1000,
};
// Add model info for assistant messages
@@ -1529,7 +1558,8 @@ class ApiService {
'chat_id': chatId,
'model': model,
'messages': formattedMessages,
'session_id': sessionId ?? const Uuid().v4().substring(0, 20), // Add session_id
'session_id':
sessionId ?? const Uuid().v4().substring(0, 20), // Add session_id
// Don't include model_item as it might not be expected
};
@@ -1541,7 +1571,9 @@ class ApiService {
debugPrint('DEBUG: Chat completed response: ${response.statusCode}');
} catch (e) {
// This is a non-critical endpoint - main sync happens via /api/v1/chats/{id}
debugPrint('DEBUG: Chat completed endpoint not available or failed (non-critical): $e');
debugPrint(
'DEBUG: Chat completed endpoint not available or failed (non-critical): $e',
);
}
}
@@ -2379,8 +2411,7 @@ class ApiService {
// Send message with SSE streaming
// Returns a record with (stream, messageId, sessionId)
({Stream<String> stream, String messageId, String sessionId})
sendMessage({
({Stream<String> stream, String messageId, String sessionId}) sendMessage({
required List<Map<String, dynamic>> messages,
required String model,
String? conversationId,
@@ -2478,7 +2509,9 @@ class ApiService {
// Debug the data being sent
debugPrint('DEBUG: SSE request data keys: ${data.keys.toList()}');
debugPrint('DEBUG: Has background_tasks: ${data.containsKey('background_tasks')}');
debugPrint(
'DEBUG: Has background_tasks: ${data.containsKey('background_tasks')}',
);
debugPrint('DEBUG: Has session_id: ${data.containsKey('session_id')}');
debugPrint('DEBUG: background_tasks value: ${data['background_tasks']}');
debugPrint('DEBUG: session_id value: ${data['session_id']}');
@@ -2535,12 +2568,17 @@ class ApiService {
String? persistentStreamId;
try {
debugPrint('DEBUG: Making SSE request with parser to /api/chat/completions');
debugPrint(
'DEBUG: Making SSE request with parser to /api/chat/completions',
);
// Create a fresh Dio instance optimized for SSE streaming
final streamDio = Dio(BaseOptions(
final streamDio = Dio(
BaseOptions(
baseUrl: serverConfig.url,
connectTimeout: const Duration(seconds: 60), // Longer for initial connection
connectTimeout: const Duration(
seconds: 60,
), // Longer for initial connection
receiveTimeout: null, // No timeout for streaming
sendTimeout: const Duration(seconds: 30),
headers: {
@@ -2553,7 +2591,8 @@ class ApiService {
validateStatus: (status) => status != null && status < 400,
followRedirects: true,
maxRedirects: 3,
));
),
);
debugPrint('DEBUG: Sending SSE request with data: ${jsonEncode(data)}');
@@ -2568,17 +2607,23 @@ class ApiService {
debugPrint('DEBUG: SSE response status: ${response.statusCode}');
debugPrint('DEBUG: SSE response headers: ${response.headers}');
debugPrint('DEBUG: SSE content-type: ${response.headers.value('content-type')}');
debugPrint(
'DEBUG: SSE content-type: ${response.headers.value('content-type')}',
);
if (response.statusCode != 200) {
throw Exception('HTTP ${response.statusCode}: Failed to start streaming');
throw Exception(
'HTTP ${response.statusCode}: Failed to start streaming',
);
}
// Check if we got SSE or JSON response
final contentType = response.headers.value('content-type') ?? '';
if (!contentType.contains('text/event-stream')) {
debugPrint('WARNING: Expected SSE but got content-type: $contentType');
debugPrint('WARNING: This usually means the server didn\'t receive the streaming parameters');
debugPrint(
'WARNING: This usually means the server didn\'t receive the streaming parameters',
);
// Try to read the response to see what we got
final stream = response.data.stream as Stream<List<int>>;
@@ -2608,7 +2653,9 @@ class ApiService {
final message = choice['message'] as Map<String, dynamic>;
final content = message['content']?.toString() ?? '';
if (content.isNotEmpty) {
debugPrint('DEBUG: Successfully extracted content from JSON response');
debugPrint(
'DEBUG: Successfully extracted content from JSON response',
);
// Stream the content word by word for better UX
final words = content.split(' ');
for (final word in words) {
@@ -2627,7 +2674,9 @@ class ApiService {
// Check if it's a task-based response
if (json is Map && json.containsKey('task_id')) {
debugPrint('DEBUG: Got task-based response with task_id: ${json['task_id']}');
debugPrint(
'DEBUG: Got task-based response with task_id: ${json['task_id']}',
);
debugPrint('DEBUG: Status: ${json['status']}');
// This might be a polling-based async pattern
// TODO: Implement polling for task completion
@@ -2636,7 +2685,9 @@ class ApiService {
} catch (e) {
debugPrint('ERROR: Failed to parse JSON response: $e');
// Try to show something to the user
streamController.add('Response received but could not be parsed properly.');
streamController.add(
'Response received but could not be parsed properly.',
);
}
} else {
// Not JSON, might be plain text
@@ -2662,7 +2713,9 @@ class ApiService {
}
// Parse SSE events with enhanced parser (includes heartbeat monitoring)
final sseParser = SSEParser(heartbeatTimeout: const Duration(seconds: 45));
final sseParser = SSEParser(
heartbeatTimeout: const Duration(seconds: 45),
);
int contentIndex = 0;
int chunkSequence = 0;
String accumulatedContent = '';
@@ -2673,7 +2726,9 @@ class ApiService {
});
sseParser.reconnectRequests.listen((lastEventId) {
debugPrint('Persistent: SSE reconnection requested, lastEventId: $lastEventId');
debugPrint(
'Persistent: SSE reconnection requested, lastEventId: $lastEventId',
);
// The persistent service will handle the reconnection
});
@@ -2705,8 +2760,11 @@ class ApiService {
}
// Update recovery state
recoveryService.updateStreamProgress(streamId, event.data, contentIndex++);
recoveryService.updateStreamProgress(
streamId,
event.data,
contentIndex++,
);
} catch (e) {
debugPrint('Persistent: Error processing SSE event: $e');
streamController.addError(e);
@@ -2757,7 +2815,8 @@ class ApiService {
streamController.addError(error);
}
},
cancelOnError: false, // Continue processing despite individual event errors
cancelOnError:
false, // Continue processing despite individual event errors
);
// Register with persistent streaming service now that subscription is created
@@ -2775,7 +2834,6 @@ class ApiService {
'requestData': data,
},
);
} catch (e) {
debugPrint('Persistent: Failed to create SSE stream: $e');
if (persistentStreamId != null) {
@@ -2802,7 +2860,9 @@ class ApiService {
PersistentStreamingService persistentService,
String persistentStreamId,
) {
debugPrint('Persistent: SSE event - type: ${event.event}, data: ${event.data}');
debugPrint(
'Persistent: SSE event - type: ${event.event}, data: ${event.data}',
);
// Handle completion signal
if (event.data == '[DONE]') {
@@ -2858,7 +2918,9 @@ class ApiService {
// Check for completion in delta
if (delta.containsKey('finish_reason')) {
final finishReason = delta['finish_reason'];
debugPrint('Persistent: Stream finished with reason: $finishReason');
debugPrint(
'Persistent: Stream finished with reason: $finishReason',
);
if (!streamController.isClosed) {
streamController.close();
}
@@ -2868,7 +2930,9 @@ class ApiService {
// Check for completion at choice level
final finishReason = choice['finish_reason'];
if (finishReason != null) {
debugPrint('Persistent: Stream finished with reason: $finishReason');
debugPrint(
'Persistent: Stream finished with reason: $finishReason',
);
if (!streamController.isClosed) {
streamController.close();
}
@@ -2921,7 +2985,6 @@ class ApiService {
}
}
}
} catch (e) {
debugPrint('Persistent: Error parsing SSE event data: $e');
// Don't fail the entire stream for one bad event