package com.cottondb.android.ui.activity import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.rotate import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.cottondb.android.activity.ActivityPresentationFacts import com.cottondb.android.activitybin.ActivityAuditEntry import com.cottondb.android.activitybin.ActivityRead import com.cottondb.android.activitybin.ActivityReplica import com.cottondb.android.activitybin.AssistantRun import com.cottondb.android.design.CottonFonts import com.cottondb.android.design.CottonMetrics import com.cottondb.android.design.CottonTextStyles import com.cottondb.android.generated.CottonPalette import com.cottondb.android.ui.paper.MemoryPaperDye import com.cottondb.android.ui.paper.PaperEdge import com.cottondb.android.ui.paper.TornPaper import java.time.Clock /** * Controlled `/activity` presentation. The host owns reading, refresh, admission, cancellation, * and navigation. Server-written task, receipt, error, and audit argument summary are rendered * verbatim and never reconstructed here. */ @Composable fun ActivityScreen( read: ActivityRead?, loading: Boolean, readProblem: String?, writeProblem: String?, canWrite: Boolean, onRetry: () -> Unit, onCancel: (AssistantRun) -> Unit, onOpenNote: (String) -> Unit, onBack: () -> Unit, modifier: Modifier = Modifier, clock: Clock = Clock.systemDefaultZone(), ) { val frozenClock = remember { Clock.fixed(clock.instant(), clock.zone) } Column( modifier .fillMaxSize() .background(CottonPalette.groundMuted) .safeDrawingPadding(), ) { ActivityHeader(onBack) when { read == null && (loading || readProblem == null) -> ActivitySkeleton() read == null -> ActivityUnreadable(readProblem, onRetry) else -> ActivityList( read = read, readProblem = readProblem, writeProblem = writeProblem, canWrite = canWrite, clock = frozenClock, onRetry = onRetry, onCancel = onCancel, onOpenNote = onOpenNote, ) } } } @Composable private fun ActivityHeader(onBack: () -> Unit) { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 12.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { TextButton( onClick = onBack, modifier = Modifier.semantics { contentDescription = "Back" }, ) { Text("Back") } Text( text = "Activity", modifier = Modifier.padding(start = 8.dp), style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.serif), color = CottonPalette.ink, ) } } @Composable private fun ActivityList( read: ActivityRead, readProblem: String?, writeProblem: String?, canWrite: Boolean, clock: Clock, onRetry: () -> Unit, onCancel: (AssistantRun) -> Unit, onOpenNote: (String) -> Unit, ) { LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues( horizontal = CottonMetrics.contentMargin, vertical = 8.dp, ), verticalArrangement = Arrangement.spacedBy(12.dp), ) { if (readProblem != null) { item(key = "read-problem") { CachedReadProblem(readProblem, onRetry) } } item(key = "database-section") { ActivitySection("This database") } item(key = "replica") { ReplicaSlip(read.replica) } item(key = "runs-section") { ActivitySection( title = "What the assistant did", count = read.runs.takeIf { it.isNotEmpty() }?.size?.toString(), ) } when { read.runs.isEmpty() -> item(key = "runs-empty") { ActivityEmpty( title = "No runs yet.", message = "When you ask something that needs work, the run shows up here.", ) } else -> items(read.runs, key = { run -> run.id }) { run -> RunSlip( run = run, canWrite = canWrite, clock = clock, onCancel = onCancel, onOpenNote = onOpenNote, ) } } if (writeProblem != null) { item(key = "write-problem") { Text( writeProblem, style = CottonTextStyles.caption, color = CottonPalette.statusError, ) } } item(key = "audit-section") { ActivitySection( title = "What assistants did here", count = read.audit.takeIf { it.isNotEmpty() }?.size?.toString(), ) } when { read.audit.isEmpty() -> item(key = "audit-empty") { ActivityEmpty( title = "Nothing yet.", message = "Every call a connected assistant makes to this database is listed here.", ) } else -> { val ledgerRows = auditLedgerRows(read.audit, clock) itemsIndexed(ledgerRows, key = { _, row -> row.key }) { index, row -> AuditLedgerRow( row = row, clock = clock, overlapsPrevious = index > 0, ) } if (read.auditTruncated) { item(key = "audit-truncated") { AuditLedgerTruncated(overlapsPrevious = ledgerRows.isNotEmpty()) } } } } } } @Composable private fun ActivitySection(title: String, count: String? = null) { Row( modifier = Modifier .fillMaxWidth() .padding(top = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { Text(title, style = CottonTextStyles.sectionLabel, color = CottonPalette.inkSecondary) count?.let { Spacer(Modifier.width(8.dp)) Text(it, style = CottonTextStyles.caption, color = CottonPalette.inkTertiary) } } } @Composable private fun ReplicaSlip(replica: ActivityReplica) { TornPaper( id = "activity-replica", dye = MemoryPaperDye.Cream, modifier = Modifier.fillMaxWidth(), edge = PaperEdge.Cut, ) { Column( modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp), ) { ReplicaLine("Project", replica.workspaceId) ReplicaLine("This device", replica.deviceId) ReplicaLine("File", ActivityPresentationFacts.heldLine(replica.held)) ReplicaLine("Waiting to sync", ActivityPresentationFacts.pendingLine(replica.pending)) } } } @Composable private fun ReplicaLine(label: String, value: String) { Row(Modifier.fillMaxWidth()) { Text( text = label, modifier = Modifier.width(120.dp), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary, ) Text( text = value, modifier = Modifier.weight(1f), style = CottonTextStyles.caption, color = CottonPalette.ink, ) } } @Composable private fun RunSlip( run: AssistantRun, canWrite: Boolean, clock: Clock, onCancel: (AssistantRun) -> Unit, onOpenNote: (String) -> Unit, ) { val stateInk = when (ActivityPresentationFacts.stateInk(run.state)) { ActivityPresentationFacts.StateInk.Green -> CottonPalette.statusSuccess ActivityPresentationFacts.StateInk.Red -> CottonPalette.statusError ActivityPresentationFacts.StateInk.Pencil -> CottonPalette.inkSecondary } val canCancel = ActivityPresentationFacts.canCancel(run.id, run.state) val noteId = run.resultNoteId?.takeUnless(String::isBlank) val stamp = ActivityPresentationFacts.stampDone(run.state) TornPaper( id = run.id, dye = MemoryPaperDye.Cream, modifier = Modifier.fillMaxWidth(), edge = PaperEdge.Cut, ) { Box(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { Row(verticalAlignment = Alignment.CenterVertically) { if (ActivityPresentationFacts.isUnfinished(run.state)) { Box( modifier = Modifier .size(7.dp) .background(CottonPalette.statusSuccess, androidx.compose.foundation.shape.CircleShape) .semantics { contentDescription = "Run in progress" }, ) Spacer(Modifier.width(8.dp)) } Text( text = run.task, modifier = Modifier.weight(1f), style = CottonTextStyles.rowTitleCompact.copy(fontFamily = CottonFonts.serif), color = CottonPalette.ink, ) } Text( text = ActivityPresentationFacts.caption( state = run.state, stamp = run.finishedAt ?: run.startedAt ?: run.queuedAt, turns = run.turns, clock = clock, zone = clock.zone, ), modifier = Modifier.padding(top = 4.dp), style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand), color = stateInk, ) run.receipt.takeIf(String::isNotEmpty)?.let { receipt -> Text( text = receipt, modifier = Modifier.padding(top = 8.dp), style = CottonTextStyles.caption, color = CottonPalette.ink, ) } ActivityPresentationFacts.spentLine(run.stoppedReason, run.costUsd)?.let { spent -> Text( text = spent, modifier = Modifier.padding(top = 6.dp), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary, ) } ActivityPresentationFacts.failureSentence(run.state, run.error)?.let { failure -> Text( text = failure, modifier = Modifier.padding(top = 8.dp), style = CottonTextStyles.caption, color = CottonPalette.statusError, ) } if (canCancel || noteId != null) { Row(Modifier.padding(top = 8.dp)) { if (canCancel) { TextButton( onClick = { onCancel(run) }, enabled = canWrite, modifier = Modifier.semantics { contentDescription = "Cancel ${run.task}" }, ) { Text("Cancel") } } if (noteId != null) { TextButton( onClick = { onOpenNote(noteId) }, modifier = Modifier.semantics { contentDescription = "Open the note" }, ) { Text("Open the note") } } } } } if (stamp) { Text( text = "DONE", modifier = Modifier .align(Alignment.TopEnd) .padding(top = 10.dp, end = 12.dp) .rotate(-9f), style = CottonTextStyles.sectionLabel.copy(fontWeight = FontWeight.Bold), color = CottonPalette.statusSuccess, ) } } } } private sealed interface ActivityLedgerRow { val key: String data class Day( override val key: String, val label: String, ) : ActivityLedgerRow data class Entry( override val key: String, val entry: ActivityAuditEntry, ) : ActivityLedgerRow } private fun auditLedgerRows( entries: List, clock: Clock, ): List = buildList { ActivityPresentationFacts.ledgerDays( entries = entries, createdAt = ActivityAuditEntry::createdAt, clock = clock, zone = clock.zone, ).forEachIndexed { dayIndex, day -> add(ActivityLedgerRow.Day("activity-ledger-day-$dayIndex-${day.key}", day.label)) day.entries.forEachIndexed { entryIndex, entry -> add(ActivityLedgerRow.Entry("activity-ledger-entry-$dayIndex-$entryIndex-${entry.id}", entry)) } } } @Composable private fun AuditLedgerRow( row: ActivityLedgerRow, clock: Clock, overlapsPrevious: Boolean, ) { TornPaper( id = row.key, dye = MemoryPaperDye.Cream, modifier = Modifier .fillMaxWidth() .then(if (overlapsPrevious) Modifier.offset(y = (-12).dp) else Modifier), elevation = 0.dp, edge = PaperEdge.Cut, ) { when (row) { is ActivityLedgerRow.Day -> { Column(Modifier.padding(start = 18.dp, end = 18.dp, top = 12.dp, bottom = 4.dp)) { Text(row.label, style = CottonTextStyles.rowTitleCompact.copy(fontFamily = CottonFonts.serif)) HorizontalDivider( modifier = Modifier.padding(top = 4.dp), thickness = CottonMetrics.hairline, color = CottonPalette.hairline, ) } } is ActivityLedgerRow.Entry -> AuditLine(row.entry, row.entry.ledgerFact(), clock) } } } @Composable private fun AuditLedgerTruncated(overlapsPrevious: Boolean) { TornPaper( id = "activity-ledger-truncated", dye = MemoryPaperDye.Cream, modifier = Modifier .fillMaxWidth() .then(if (overlapsPrevious) Modifier.offset(y = (-12).dp) else Modifier), elevation = 0.dp, edge = PaperEdge.Cut, ) { Text( "There are more, not shown.", modifier = Modifier.padding(18.dp), style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary, ) } } private fun ActivityAuditEntry.ledgerFact(): ActivityPresentationFacts.LedgerEntry = ActivityPresentationFacts.LedgerEntry( createdAt = createdAt, tokenName = tokenName, tool = tool, argsSummary = argsSummary, ok = ok, ) @Composable private fun AuditLine( entry: ActivityAuditEntry, fact: ActivityPresentationFacts.LedgerEntry, clock: Clock, ) { Row( modifier = Modifier.padding(horizontal = 18.dp, vertical = 7.dp), verticalAlignment = Alignment.Top, ) { Text( text = ActivityPresentationFacts.ledgerTime(entry.createdAt, clock.zone), modifier = Modifier.width(58.dp), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary, ) Column(Modifier.weight(1f)) { Row(verticalAlignment = Alignment.CenterVertically) { Text(entry.tool, style = CottonTextStyles.preview, color = CottonPalette.ink) if (ActivityPresentationFacts.refused(fact)) { Spacer(Modifier.width(8.dp)) Text("refused", style = CottonTextStyles.preview, color = CottonPalette.statusError) } } ActivityPresentationFacts.ledgerDetail(fact).takeIf(String::isNotEmpty)?.let { detail -> Text(detail, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } } } } @Composable private fun ActivitySkeleton() { LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(CottonMetrics.contentMargin), verticalArrangement = Arrangement.spacedBy(12.dp), ) { items(listOf("activity-loading-1", "activity-loading-2", "activity-loading-3")) { id -> TornPaper( id = id, dye = MemoryPaperDye.Cream, modifier = Modifier.fillMaxWidth().height(96.dp), edge = PaperEdge.Cut, ) {} } } } @Composable private fun ActivityEmpty(title: String, message: String) { TornPaper( id = "activity-empty-$title", dye = MemoryPaperDye.Cream, modifier = Modifier.fillMaxWidth(), edge = PaperEdge.Cut, ) { Column( modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { Text(title, style = CottonTextStyles.rowTitleCompact, color = CottonPalette.ink) Text(message, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } } } @Composable private fun ActivityUnreadable(problem: String?, onRetry: () -> Unit) { Column( modifier = Modifier.padding(CottonMetrics.contentMargin), verticalArrangement = Arrangement.spacedBy(8.dp), ) { Text("Activity could not be read.", style = CottonTextStyles.body, color = CottonPalette.statusError) Text( "This phone could not read its own database just now.", style = CottonTextStyles.caption, color = CottonPalette.inkSecondary, ) problem?.takeIf(String::isNotEmpty)?.let { Text(it, style = CottonTextStyles.caption, color = CottonPalette.statusError) } TextButton( onClick = onRetry, modifier = Modifier.semantics { contentDescription = "Try again" }, ) { Text("Try again") } } } @Composable private fun CachedReadProblem(problem: String, onRetry: () -> Unit) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, ) { Text( problem, modifier = Modifier.weight(1f), style = CottonTextStyles.caption, color = CottonPalette.statusError, ) TextButton( onClick = onRetry, modifier = Modifier.semantics { contentDescription = "Try again" }, ) { Text("Try again") } } }