restoreSession method
Restore the most relevant session for this topic+mode.
Loads messages for ONLY the active session (or, if none, the most
recently ENDED session in read-only mode for card regeneration).
Older ENDED sessions are NOT merged into the message list — their
summary jsonb digests surface in the system prompt via the
proxy's priorSessionDigests fetch, giving the model lightweight
cross-session memory without paying the context-window cost of a
raw transcript merge.
Implementation
Future<bool> restoreSession() async {
if (params.topicId == null) return false;
state = state.copyWith(isRestoring: true);
try {
final supabase = ref.read(supabaseDatasourceProvider);
final sessionType = _modeToSessionType(params.mode);
// Fetch every session (active + ended) for this topic+mode.
final sessions = await supabase.getAllSessionsForTopic(
topicId: params.topicId!,
sessionType: sessionType,
);
if (sessions.isEmpty) {
state = state.copyWith(isRestoring: false);
return false;
}
// Identify the active session (for new messages) and latest ended
// session (for card regeneration).
final activeSession = sessions.where((s) => s.endedAt == null).lastOrNull;
_sessionId = activeSession?.id;
_sessionStartedAt = activeSession?.startedAt;
final endedSessions = sessions.where((s) => s.endedAt != null).toList();
_endedSessionId = endedSessions.isEmpty ? null : endedSessions.last.id;
// Load messages for the SINGLE relevant session — active when
// present, otherwise the most recent ended session for read-only
// review. Older ENDED sessions are referenced via their digest
// (server-side) rather than loaded as raw history.
final sessionToLoad =
activeSession ??
(endedSessions.isNotEmpty ? endedSessions.last : null);
if (sessionToLoad == null) {
state = state.copyWith(isRestoring: false);
return false;
}
final rawMessages = await supabase.getMessagesForSessions([
sessionToLoad.id,
]);
final restored = rawMessages
.map(
(row) => ChatMessage(
role: row['role'] as String,
content: row['content'] as String,
timestamp: DateTime.parse(row['created_at'] as String),
),
)
.toList();
if (restored.isEmpty) {
state = state.copyWith(isRestoring: false);
return false;
}
state = state.copyWith(
messages: restored,
isRestoring: false,
isReadOnly: activeSession == null,
);
return true;
} catch (e) {
debugPrint('Failed to restore session: $e');
state = state.copyWith(isRestoring: false);
return false;
}
}