Skip to content

Commit e00a245

Browse files
authored
Merge pull request #133 from foureight84/feat/131-coach-history
Coach: past conversations list with delete (#131)
2 parents 408178a + 074d160 commit e00a245

6 files changed

Lines changed: 431 additions & 15 deletions

File tree

‎app/src/main/java/com/pulseloop/data/dao/Daos.kt‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,8 +437,44 @@ interface CoachConversationDao {
437437

438438
@Upsert
439439
suspend fun upsert(conversation: CoachConversationEntity)
440+
441+
@Query("SELECT * FROM coach_conversations WHERE id = :id LIMIT 1")
442+
suspend fun byId(id: String): CoachConversationEntity?
443+
444+
/**
445+
* The coach's past conversations for the history sheet (issue #131), newest first. Only ones
446+
* with at least one message: "+" persists its thread up front, so an unused one is an empty
447+
* row that would otherwise list as a blank entry.
448+
*/
449+
@Query(
450+
"""SELECT c.id, c.createdAt, c.updatedAt,
451+
(SELECT m.body FROM coach_messages m WHERE m.conversationId = c.id AND m.role = 'user'
452+
ORDER BY m.createdAt ASC LIMIT 1) AS firstQuestion,
453+
(SELECT COUNT(*) FROM coach_messages m WHERE m.conversationId = c.id) AS messageCount
454+
FROM coach_conversations c
455+
WHERE EXISTS (SELECT 1 FROM coach_messages m WHERE m.conversationId = c.id)
456+
ORDER BY c.updatedAt DESC"""
457+
)
458+
fun historyFlow(): Flow<List<CoachConversationSummary>>
459+
460+
/** Delete its messages and tool calls first — see [CoachMessageDao], [CoachToolCallDao]. */
461+
@Query("DELETE FROM coach_conversations WHERE id = :id")
462+
suspend fun deleteById(id: String)
463+
464+
@Query("DELETE FROM coach_conversations")
465+
suspend fun deleteAll()
440466
}
441467

468+
/** One row of the coach history sheet (issue #131). */
469+
data class CoachConversationSummary(
470+
val id: String,
471+
val createdAt: Long,
472+
val updatedAt: Long,
473+
/** The first thing the user asked; null only if the thread holds no user message. */
474+
val firstQuestion: String?,
475+
val messageCount: Int,
476+
)
477+
442478
@Dao
443479
interface CoachMessageDao {
444480
@Query("SELECT * FROM coach_messages WHERE conversationId = :convId ORDER BY createdAt ASC")
@@ -449,6 +485,20 @@ interface CoachMessageDao {
449485

450486
@Insert
451487
suspend fun insert(message: CoachMessageEntity)
488+
489+
/** Attachment refs of a conversation's messages, so deleting it can delete the image files. */
490+
@Query("SELECT attachmentsJson FROM coach_messages WHERE conversationId = :convId AND attachmentsJson IS NOT NULL")
491+
suspend fun attachmentsJsonFor(convId: String): List<String>
492+
493+
@Query("SELECT attachmentsJson FROM coach_messages WHERE attachmentsJson IS NOT NULL")
494+
suspend fun allAttachmentsJson(): List<String>
495+
496+
/** Explicit rather than trusting the cascade, which only fires with SQLite's foreign keys on. */
497+
@Query("DELETE FROM coach_messages WHERE conversationId = :convId")
498+
suspend fun deleteForConversation(convId: String)
499+
500+
@Query("DELETE FROM coach_messages")
501+
suspend fun deleteAll()
452502
}
453503

454504
@Dao
@@ -479,6 +529,13 @@ interface CoachToolCallDao {
479529

480530
@Insert
481531
suspend fun insert(call: CoachToolCallEntity)
532+
533+
/** `coach_tool_calls` has no foreign key to its conversation, so a delete has to clear it. */
534+
@Query("DELETE FROM coach_tool_calls WHERE conversationId = :convId")
535+
suspend fun deleteForConversation(convId: String)
536+
537+
@Query("DELETE FROM coach_tool_calls")
538+
suspend fun deleteAll()
482539
}
483540

484541
@Dao

‎app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,9 @@ fun PulseLoopApp() {
141141
com.pulseloop.coach.attachments.CoachAttachmentStore.payloads(context, refs)
142142
},
143143
environmentSnapshot = { weatherContextService.snapshot() },
144+
deleteAttachments = { refs ->
145+
refs.forEach { com.pulseloop.coach.attachments.CoachAttachmentStore.delete(context, it) }
146+
},
144147
)
145148
}
146149

@@ -391,10 +394,24 @@ fun PulseLoopApp() {
391394
// frosted glass bar the other tabs use so the chat scrolls under it
392395
// (owner choice, issue #22).
393396
var showCoachUsage by remember { mutableStateOf(false) }
397+
var showCoachHistory by remember { mutableStateOf(false) }
394398
CoachHeader(
395399
onNewChat = { coachVM.newConversation() },
396400
onOpenUsage = { showCoachUsage = true },
401+
onOpenHistory = { showCoachHistory = true },
397402
)
403+
if (showCoachHistory) {
404+
val history by coachVM.history.collectAsState(initial = emptyList())
405+
val coachState by coachVM.state.collectAsState()
406+
com.pulseloop.ui.screens.CoachHistorySheet(
407+
conversations = history,
408+
currentId = coachState.conversationId,
409+
onOpen = { id -> coachVM.openConversation(id); showCoachHistory = false },
410+
onDelete = { id -> coachVM.deleteConversation(id) },
411+
onDeleteAll = { coachVM.deleteAllConversations(); showCoachHistory = false },
412+
onDismiss = { showCoachHistory = false },
413+
)
414+
}
398415
if (showCoachUsage) {
399416
var usageData by remember {
400417
mutableStateOf<Pair<com.pulseloop.data.entity.CoachConversationEntity, List<com.pulseloop.data.entity.CoachMessageEntity>>?>(null)
Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
package com.pulseloop.ui.screens
2+
3+
import androidx.compose.foundation.background
4+
import androidx.compose.foundation.border
5+
import androidx.compose.foundation.clickable
6+
import androidx.compose.foundation.layout.*
7+
import androidx.compose.foundation.lazy.LazyColumn
8+
import androidx.compose.foundation.lazy.items
9+
import androidx.compose.foundation.shape.RoundedCornerShape
10+
import androidx.compose.material.icons.Icons
11+
import androidx.compose.material.icons.filled.Delete
12+
import androidx.compose.material3.*
13+
import androidx.compose.runtime.*
14+
import androidx.compose.ui.Alignment
15+
import androidx.compose.ui.Modifier
16+
import androidx.compose.ui.draw.clip
17+
import androidx.compose.ui.text.font.FontWeight
18+
import androidx.compose.ui.text.style.TextOverflow
19+
import androidx.compose.ui.unit.dp
20+
import androidx.compose.ui.unit.sp
21+
import com.pulseloop.data.dao.CoachConversationSummary
22+
import com.pulseloop.ui.theme.PulseColors
23+
import java.time.Instant
24+
import java.time.LocalDate
25+
import java.time.ZoneId
26+
import java.time.format.DateTimeFormatter
27+
import java.time.format.FormatStyle
28+
import java.util.Locale
29+
30+
/**
31+
* The coach's past conversations (issue #131): tap one to reopen it, swipe it away to delete it,
32+
* or delete them all. Every delete asks first — it takes the messages, the tool-call trace and any
33+
* attached photos with it, and there is no undo.
34+
*/
35+
@OptIn(ExperimentalMaterial3Api::class)
36+
@Composable
37+
fun CoachHistorySheet(
38+
conversations: List<CoachConversationSummary>,
39+
currentId: String?,
40+
onOpen: (String) -> Unit,
41+
onDelete: (String) -> Unit,
42+
onDeleteAll: () -> Unit,
43+
onDismiss: () -> Unit,
44+
) {
45+
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false)
46+
var pendingDelete by remember { mutableStateOf<CoachConversationSummary?>(null) }
47+
var confirmDeleteAll by remember { mutableStateOf(false) }
48+
49+
ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState, containerColor = PulseColors.background) {
50+
Column(
51+
Modifier
52+
.fillMaxWidth()
53+
.padding(horizontal = 16.dp)
54+
.padding(bottom = 24.dp),
55+
verticalArrangement = Arrangement.spacedBy(12.dp),
56+
) {
57+
Text("Past conversations", fontSize = 17.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary)
58+
if (conversations.isEmpty()) {
59+
Text(
60+
"No conversations yet. Ask the coach something and it will show up here.",
61+
fontSize = 13.sp, color = PulseColors.textMuted,
62+
)
63+
} else {
64+
Text("Swipe a conversation to delete it.", fontSize = 12.sp, color = PulseColors.textMuted)
65+
LazyColumn(
66+
Modifier.weight(1f, fill = false),
67+
verticalArrangement = Arrangement.spacedBy(8.dp),
68+
) {
69+
items(conversations, key = { it.id }) { convo ->
70+
HistoryRow(
71+
convo = convo,
72+
isCurrent = convo.id == currentId,
73+
onOpen = { onOpen(convo.id) },
74+
onSwipedAway = { pendingDelete = convo },
75+
)
76+
}
77+
}
78+
TextButton(
79+
onClick = { confirmDeleteAll = true },
80+
modifier = Modifier.align(Alignment.CenterHorizontally),
81+
) { Text("Delete all conversations", color = PulseColors.danger) }
82+
}
83+
}
84+
}
85+
86+
pendingDelete?.let { convo ->
87+
AlertDialog(
88+
onDismissRequest = { pendingDelete = null },
89+
title = { Text("Delete this conversation?") },
90+
text = { Text("“${CoachHistoryText.title(convo.firstQuestion)}” and its replies will be deleted. This can't be undone.") },
91+
confirmButton = {
92+
TextButton(onClick = { onDelete(convo.id); pendingDelete = null }) {
93+
Text("Delete", color = PulseColors.danger)
94+
}
95+
},
96+
dismissButton = { TextButton(onClick = { pendingDelete = null }) { Text("Cancel") } },
97+
)
98+
}
99+
if (confirmDeleteAll) {
100+
AlertDialog(
101+
onDismissRequest = { confirmDeleteAll = false },
102+
title = { Text("Delete all conversations?") },
103+
text = { Text("All ${conversations.size} conversations and their replies will be deleted. This can't be undone.") },
104+
confirmButton = {
105+
TextButton(onClick = { confirmDeleteAll = false; onDeleteAll() }) {
106+
Text("Delete all", color = PulseColors.danger)
107+
}
108+
},
109+
dismissButton = { TextButton(onClick = { confirmDeleteAll = false }) { Text("Cancel") } },
110+
)
111+
}
112+
}
113+
114+
@OptIn(ExperimentalMaterial3Api::class)
115+
@Composable
116+
private fun HistoryRow(
117+
convo: CoachConversationSummary,
118+
isCurrent: Boolean,
119+
onOpen: () -> Unit,
120+
onSwipedAway: () -> Unit,
121+
) {
122+
// The swipe only asks; the row snaps back and the dialog decides. Returning false keeps the
123+
// state from settling on "dismissed", which would leave a cancelled row swiped off screen.
124+
val dismissState = rememberSwipeToDismissBoxState(
125+
confirmValueChange = { value ->
126+
if (value != SwipeToDismissBoxValue.Settled) onSwipedAway()
127+
false
128+
},
129+
)
130+
val shape = RoundedCornerShape(12.dp)
131+
SwipeToDismissBox(
132+
state = dismissState,
133+
backgroundContent = {
134+
Box(
135+
Modifier
136+
.fillMaxSize()
137+
.clip(shape)
138+
.background(PulseColors.danger.copy(alpha = 0.25f))
139+
.padding(horizontal = 16.dp),
140+
contentAlignment = Alignment.CenterEnd,
141+
) {
142+
Icon(Icons.Filled.Delete, "Delete", tint = PulseColors.danger)
143+
}
144+
},
145+
) {
146+
Column(
147+
Modifier
148+
.fillMaxWidth()
149+
.clip(shape)
150+
.background(PulseColors.card)
151+
.border(1.dp, if (isCurrent) PulseColors.accent else PulseColors.borderSubtle, shape)
152+
.clickable(onClick = onOpen)
153+
.padding(horizontal = 14.dp, vertical = 10.dp),
154+
) {
155+
Text(
156+
CoachHistoryText.title(convo.firstQuestion),
157+
fontSize = 14.sp, color = PulseColors.textPrimary,
158+
maxLines = 2, overflow = TextOverflow.Ellipsis,
159+
)
160+
Spacer(Modifier.height(2.dp))
161+
Text(
162+
CoachHistoryText.subtitle(convo, isCurrent),
163+
fontSize = 12.sp, color = PulseColors.textMuted,
164+
)
165+
}
166+
}
167+
}
168+
169+
/** The history row's text, kept out of the composable so it can be unit-tested. */
170+
internal object CoachHistoryText {
171+
172+
fun title(firstQuestion: String?): String =
173+
firstQuestion?.replace(Regex("\\s+"), " ")?.trim()?.takeIf { it.isNotEmpty() }
174+
?: "Untitled conversation"
175+
176+
fun subtitle(
177+
convo: CoachConversationSummary,
178+
isCurrent: Boolean,
179+
zone: ZoneId = ZoneId.systemDefault(),
180+
today: LocalDate = LocalDate.now(zone),
181+
): String {
182+
val parts = mutableListOf(whenText(convo.updatedAt, zone, today))
183+
parts += if (convo.messageCount == 1) "1 message" else "${convo.messageCount} messages"
184+
if (isCurrent) parts += "open now"
185+
return parts.joinToString(" · ")
186+
}
187+
188+
fun whenText(epochMs: Long, zone: ZoneId, today: LocalDate): String {
189+
val at = Instant.ofEpochMilli(epochMs).atZone(zone)
190+
val day = at.toLocalDate()
191+
return when {
192+
day == today -> "Today " + at.format(TIME)
193+
day == today.minusDays(1) -> "Yesterday " + at.format(TIME)
194+
day.year == today.year -> at.format(SAME_YEAR)
195+
else -> at.format(OTHER_YEAR)
196+
}
197+
}
198+
199+
private val TIME = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
200+
private val SAME_YEAR = DateTimeFormatter.ofPattern("MMM d", Locale.getDefault())
201+
private val OTHER_YEAR = DateTimeFormatter.ofPattern("MMM d, yyyy", Locale.getDefault())
202+
}

‎app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import androidx.compose.material.icons.Icons
2020
import androidx.compose.material.icons.filled.Add
2121
import androidx.compose.material.icons.filled.ArrowUpward
2222
import androidx.compose.material.icons.filled.Close
23+
import androidx.compose.material.icons.filled.History
2324
import androidx.compose.material.icons.filled.Info
2425
import androidx.compose.material3.Icon
2526
import androidx.compose.material3.IconButton
@@ -131,7 +132,11 @@ fun CoachScreen(
131132
* chat then scrolls under it.
132133
*/
133134
@Composable
134-
fun CoachHeader(onNewChat: () -> Unit, onOpenUsage: (() -> Unit)? = null) {
135+
fun CoachHeader(
136+
onNewChat: () -> Unit,
137+
onOpenUsage: (() -> Unit)? = null,
138+
onOpenHistory: (() -> Unit)? = null,
139+
) {
135140
Row(
136141
Modifier
137142
.fillMaxWidth()
@@ -171,6 +176,19 @@ fun CoachHeader(onNewChat: () -> Unit, onOpenUsage: (() -> Unit)? = null) {
171176
Icon(Icons.Filled.Info, "Usage & cost", tint = PulseColors.textSecondary, modifier = Modifier.size(16.dp))
172177
}
173178
}
179+
if (onOpenHistory != null) {
180+
Box(
181+
Modifier
182+
.size(36.dp)
183+
.clip(CircleShape)
184+
.background(PulseColors.card)
185+
.border(1.dp, PulseColors.borderSubtle, CircleShape)
186+
.clickable(onClick = onOpenHistory),
187+
contentAlignment = Alignment.Center,
188+
) {
189+
Icon(Icons.Filled.History, "Past conversations", tint = PulseColors.textSecondary, modifier = Modifier.size(18.dp))
190+
}
191+
}
174192
Box(
175193
Modifier
176194
.size(36.dp)

0 commit comments

Comments
 (0)