This repository has been archived on 2026-06-02. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
FabledApp/lib/data/api/chat_api.dart
T
bvandeusen dd250788f6 feat(journal): replace briefing surface with journal; remove news/RSS
The backend retired /api/briefing/* and the RSS feature entirely. This
Flutter change mirrors what landed web-side: rename the briefing surface
to journal, repoint at /api/journal/*, and drop the news/RSS UI since
its endpoints no longer exist.

New (mirrors briefing structure with adapted shapes):
- lib/data/api/journal_api.dart — getToday, getDay, getDays, triggerPrep
- lib/data/models/journal_day.dart — {day_date, conversation, messages}
- lib/providers/journal_provider.dart — async notifier, sendReply, polling,
  silent refresh, regeneratePrep. Mirrors the briefing notifier 1:1
- lib/widgets/journal_prep_card.dart — adapted briefing_digest_card
- lib/screens/journal/journal_screen.dart — adapted briefing_screen,
  weather card preserved (rendered from msg_metadata.sections.weather
  on the daily-prep assistant message). News cards / RSS reactions /
  article-discuss removed
- lib/screens/journal/journal_history_screen.dart — past days picker
  pulls /api/journal/days, drills into /api/journal/day/<iso>

Wiring:
- Routes.briefing → Routes.journal (constants.dart)
- Routes.news removed
- briefingApiProvider → journalApiProvider (api_client_provider.dart)
- newsApiProvider removed
- app.dart: shell tab "Briefing" → "Journal"; News destination removed
  from nav rail, bottom nav, and the More sheet
- splash_screen.dart and login_screen.dart: redirect Routes.journal
  instead of Routes.briefing
- chat_api.dart: drop openArticleInChat (calls deleted /api/chat/from-article)
- settings_provider.dart: drop rssEnabled getter and rssEnabledProvider

Deleted:
- lib/screens/briefing/ (whole directory)
- lib/screens/news/ (whole directory)
- lib/data/api/briefing_api.dart, news_api.dart
- lib/data/models/briefing_conversation.dart, briefing_feed.dart, news_item.dart
- lib/providers/briefing_provider.dart, news_provider.dart
- lib/widgets/briefing_digest_card.dart, news_card.dart
- test cases for NewsItem and BriefingFeed in test/widget_test.dart

flutter analyze: 0 issues.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-27 07:58:09 -04:00

168 lines
5.5 KiB
Dart

import 'dart:convert';
import 'package:dio/dio.dart';
import '../models/conversation.dart';
import '../models/message.dart';
import 'api_client.dart';
sealed class ChatStreamEvent {}
class ChatTextChunk extends ChatStreamEvent {
final String text;
ChatTextChunk(this.text);
}
class ChatStatusUpdate extends ChatStreamEvent {
final String status; // empty string = clear status
ChatStatusUpdate(this.status);
}
/// A single tool call fired during generation. Mirrors the `tool_call` SSE
/// event emitted by `generation_task.py` and the `tool_calls` array persisted
/// on the assistant Message row — same shape either way so the UI can render
/// live chips during streaming and re-render them from storage after reload.
class ChatToolCall extends ChatStreamEvent {
final Map<String, dynamic> toolCall;
ChatToolCall(this.toolCall);
}
class ChatApi {
final Dio _dio;
const ChatApi(this._dio);
Future<List<Conversation>> getConversations() async {
try {
final response = await _dio.get('/api/chat/conversations');
final data = response.data as Map<String, dynamic>;
final list = data['conversations'] as List<dynamic>;
return list
.map((e) => Conversation.fromJson(e as Map<String, dynamic>))
.toList();
} on DioException catch (e) {
throw dioToApp(e);
}
}
Future<Conversation> createConversation(String title) async {
try {
final response = await _dio.post('/api/chat/conversations', data: {
'title': title,
});
return Conversation.fromJson(response.data as Map<String, dynamic>);
} on DioException catch (e) {
throw dioToApp(e);
}
}
Future<void> deleteConversation(int id) async {
try {
await _dio.delete('/api/chat/conversations/$id');
} on DioException catch (e) {
throw dioToApp(e);
}
}
// Returns the conversation metadata AND its messages in a single request.
Future<(Conversation, List<Message>)> getMessages(int conversationId) async {
try {
final response =
await _dio.get('/api/chat/conversations/$conversationId');
final conv = response.data as Map<String, dynamic>;
final conversation = Conversation.fromJson(conv);
final list = conv['messages'] as List<dynamic>? ?? [];
final messages = list
.map((e) => Message.fromJson(e as Map<String, dynamic>))
.toList();
return (conversation, messages);
} on DioException catch (e) {
throw dioToApp(e);
}
}
// Step 1: POST the user message — server starts background generation.
Future<void> sendMessage(int conversationId, String content) async {
try {
await _dio.post(
'/api/chat/conversations/$conversationId/messages',
data: {'content': content},
);
} on DioException catch (e) {
throw dioToApp(e);
}
}
// Step 2: GET the SSE stream and yield typed events (text chunks + status updates).
Stream<ChatStreamEvent> streamGeneration(int conversationId) async* {
try {
final response = await _dio.get(
'/api/chat/conversations/$conversationId/generation/stream',
options: Options(
responseType: ResponseType.stream,
receiveTimeout: Duration.zero, // SSE streams run indefinitely
sendTimeout: Duration.zero,
headers: {
'Accept': 'text/event-stream',
'Cache-Control': 'no-cache',
},
),
);
final stream = (response.data as ResponseBody).stream;
final buf = StringBuffer();
String currentEvent = '';
await for (final chunk in stream) {
buf.write(utf8.decode(chunk, allowMalformed: true));
final raw = buf.toString();
final lines = raw.split('\n');
// Keep the last (potentially incomplete) line in the buffer.
buf.clear();
buf.write(lines.last);
for (final line in lines.sublist(0, lines.length - 1)) {
if (line.startsWith('event: ')) {
currentEvent = line.substring(7).trim();
} else if (line.startsWith('data: ')) {
final data = line.substring(6).trim();
if (data == '[DONE]') return;
if (currentEvent == 'done' || currentEvent == 'error') return;
if (currentEvent == 'chunk' || currentEvent.isEmpty) {
try {
final obj = json.decode(data) as Map<String, dynamic>;
final text = obj['text'] as String? ?? '';
if (text.isNotEmpty) yield ChatTextChunk(text);
} catch (_) {
if (data.isNotEmpty) yield ChatTextChunk(data);
}
} else if (currentEvent == 'status') {
try {
final obj = json.decode(data) as Map<String, dynamic>;
final status = obj['status'] as String? ?? '';
yield ChatStatusUpdate(status);
} catch (_) {
// Ignore malformed status events
}
} else if (currentEvent == 'tool_call') {
try {
final obj = json.decode(data) as Map<String, dynamic>;
final tc = obj['tool_call'];
if (tc is Map<String, dynamic>) yield ChatToolCall(tc);
} catch (_) {
// Ignore malformed tool_call events
}
}
} else if (line.isEmpty) {
currentEvent = ''; // blank line = SSE event separator
}
}
}
} on DioException catch (e) {
throw dioToApp(e);
}
}
}