Review: a report's conversation, ids from outside, the form's notify, the drawer, the channels
CI / check (push) Canceled after 0s

Contract at server dev 40813d1 (84 files): a chat's `controls` and `report`,
a text step's `pages` and `text`, a report's `schedule_title`.

- B1 (must): a `user` row the server wrote (`machine`) is never the person's
  bubble -- a quiet note; in a report's conversation the first such line is
  left out. A report chat's bar takes its title from the chat's own `report`
  (so it survives the app being closed), and its menu offers only what
  `controls` allows.
- A1: ids from a push payload or an intent extra pass `safeId`
  (^[A-Za-z0-9_-]{1,64}$) before they become a route: chat, schedule, run,
  report.
- C1-C3: an empty "When..." is sent empty (the server's default) and the
  field shows the default as a placeholder; editing sends `notify` only once
  the schedule was read or the person chose, and a failed read says so and
  disables Save.
- B2: Reports is in the drawer only where the instance has the route.
- A text step with pages is drawn from the server's `text`; a report from
  its `text`. A fence with a space before `html-view` is a code block, as
  the spec has it.
- A push of a kind the app does not know shows nothing. An important report
  uses a channel of high importance. A report read or deleted in the app
  cancels its notification.
- stop() and compact() post an empty body again: a search-and-replace in
  adc1c4f had changed them to "{}" by mistake.

One commit: the model, the screens and the push share these files.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-13 11:38:14 +00:00
1 parent 24669b7cd6
commit af290cd7d5
46 files changed
+519 -68

No files matched your search

@@ -43,6 +43,7 @@ class LembasApp : Application() {
NotificationChannel(CHANNEL_SCHEDULED, getString(R.string.channel_scheduled), NotificationManager.IMPORTANCE_DEFAULT),
NotificationChannel(CHANNEL_SCHEDULED_FAILURES, getString(R.string.channel_scheduled_failures), NotificationManager.IMPORTANCE_HIGH),
NotificationChannel(CHANNEL_REPORTS, getString(R.string.channel_reports), NotificationManager.IMPORTANCE_DEFAULT),
NotificationChannel(CHANNEL_REPORTS_HIGH, getString(R.string.channel_reports_high), NotificationManager.IMPORTANCE_HIGH),
).onEach { it.lockscreenVisibility = android.app.Notification.VISIBILITY_PRIVATE } +
// A new version of the app says nothing about the account.
NotificationChannel(CHANNEL_UPDATES, getString(R.string.channel_updates), NotificationManager.IMPORTANCE_LOW),
@@ -60,6 +61,7 @@ class LembasApp : Application() {
const val CHANNEL_SCHEDULED = "scheduled_results"
const val CHANNEL_SCHEDULED_FAILURES = "scheduled_failures"
const val CHANNEL_REPORTS = "reports_filed"
const val CHANNEL_REPORTS_HIGH = "reports_important"
const val CHANNEL_UPDATES = "updates"
}
}
@@ -35,6 +35,7 @@ import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import eu.llembas.android.api.Chat
import eu.llembas.android.api.Folder
import eu.llembas.android.api.safeId
import eu.llembas.android.auth.Instance
import eu.llembas.android.auth.Prefs
import eu.llembas.android.push.Notifications
@@ -138,11 +139,13 @@ class MainActivity : ComponentActivity() {
if (intent?.getBooleanExtra(WakeBootReceiver.EXTRA_RESUME, false) == true) {
lifecycleScope.launch { if (lembas.instances.prefs.first().wakeWord) WakeWordService.start(this@MainActivity) }
}
val chat = intent?.getStringExtra(Notifications.EXTRA_CHAT)
val schedule = intent?.getStringExtra(Notifications.EXTRA_SCHEDULE)
val run = intent?.getStringExtra(Notifications.EXTRA_RUN)
// Extras are whatever the sender put there (this activity can be started from outside):
// only ids that look like ids go on to become routes.
val chat = safeId(intent?.getStringExtra(Notifications.EXTRA_CHAT))
val schedule = safeId(intent?.getStringExtra(Notifications.EXTRA_SCHEDULE))
val run = safeId(intent?.getStringExtra(Notifications.EXTRA_RUN))
val instance = intent?.getStringExtra(Notifications.EXTRA_INSTANCE)
val report = intent?.getStringExtra(Notifications.EXTRA_REPORT)
val report = safeId(intent?.getStringExtra(Notifications.EXTRA_REPORT))
if (chat == null && schedule == null && report == null) return
opening.value = Opening(chat, schedule, run, instance, report)
// A notification from another of the person's instances: that one comes into use, and
@@ -291,7 +291,8 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
suspend fun deleteChat(chatId: String) = empty(authed("$v2/chats/$chatId").delete().build())
suspend fun stop(chatId: String, messageId: String) = empty(authed("$v2/chats/$chatId/messages/$messageId/stop").post("{}".toRequestBody(JSON)).build())
suspend fun stop(chatId: String, messageId: String) =
empty(authed("$v2/chats/$chatId/messages/$messageId/stop").post(ByteArray(0).toRequestBody(null)).build())
suspend fun edit(chatId: String, messageId: String, text: String): Turn =
send("POST", "/chats/$chatId/messages/$messageId/edit", buildJsonObject { put("text", text) })
@@ -333,7 +334,7 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
* server refuses in its own words (409) while a reply is being written or with nothing to
* summarise; the transcript is read again after, for the divider it leaves.
*/
suspend fun compact(chatId: String) = empty(authed("$v2/chats/$chatId/compact").post("{}".toRequestBody(JSON)).build())
suspend fun compact(chatId: String) = empty(authed("$v2/chats/$chatId/compact").post(ByteArray(0).toRequestBody(null)).build())
suspend fun team(chatId: String, since: Int = 0): TeamView = get<TeamEnvelope>("/chats/$chatId/team?since=$since").team
@@ -380,7 +381,8 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
// Notify when (spec 3.8.0): left out where the form did not say, so an older server is sent nothing new.
if (notify != null) {
put("notify", notify)
if (notify == "when") put("notify_when", notifyWhen.trim().ifBlank { NOTIFY_DEFAULT_CONDITION })
// The person's own words, or none: an empty condition is the server's default, in its own words.
if (notify == "when") put("notify_when", notifyWhen.trim())
}
}
return if (id == null) {
@@ -115,3 +115,32 @@ fun localeNumber(n: Double, decimals: Int, locale: Locale): String {
format.roundingMode = java.math.RoundingMode.HALF_UP
return format.format(n)
}
/** How a message is drawn in the transcript. */
enum class Drawn {
/** The person's own words: their bubble. */
Person,
/** The model's reply. */
Reply,
/** A line the server wrote in the person's place (`machine`): a quiet note, never their bubble. */
Note,
/** Not drawn at all. */
Hidden,
}
/**
* How [message] is drawn. A `user` row the server wrote itself (`machine`: a schedule's
* instruction, the line that opens a report's conversation) is not something the person said,
* so it is never their bubble: a quiet note -- and in a report's conversation ([reportChat]) the
* [first] such line, which only tells the model what the conversation continues, is left out,
* since the report itself is one tap back.
*/
fun drawn(message: Message, first: Boolean, reportChat: Boolean): Drawn = when {
!message.isUser -> Drawn.Reply
!message.machine -> Drawn.Person
reportChat && first -> Drawn.Hidden
else -> Drawn.Note
}
@@ -314,6 +314,10 @@ data class Chat(
@SerialName("created_at") val createdAt: String? = null,
@SerialName("updated_at") val updatedAt: String? = null,
@SerialName("system_prompt") val systemPrompt: String? = null,
/** What may be done to this chat (`rename`, `delete`, `archive`, `pin`, `folder`); null from a server that does not say: everything. */
val controls: List<String>? = null,
/** The report this chat continues (`kind` `report`): such a chat lives under Reports, not among the chats. */
val report: ChatReport? = null,
val plan: JsonObject? = null,
/** The team's size: how many agents, its own included, the chat may have. */
val agents: AgentsSetting? = null,
@@ -321,8 +325,14 @@ data class Chat(
val subagents: SubagentsOffer? = null,
) {
val isAgent: Boolean get() = kind == "agent"
fun allows(control: String): Boolean = controls?.contains(control) ?: true
}
/** The report a chat continues: its id and title. */
@Serializable
data class ChatReport(val id: String = "", val title: String = "")
/** A chat's `agents {min, max}` (harness spec 3.2.0): `1 ≤ min ≤ max ≤` the instance's cap. */
@Serializable
data class AgentsSetting(val min: Int = 1, val max: Int = 4) {
@@ -523,6 +533,8 @@ data class Step(
val markdown: String? = null,
/** A `page` step's title (spec 3.8.0): the page itself is not sent to a client that does not draw it. */
val title: String? = null,
/** A `text` step's pages (spec 3.8.0): where it has any, [text] is its markdown with each page as the one line `[page: Title]`. */
val pages: List<StepPage> = emptyList(),
val calls: List<ToolCall> = emptyList(),
val messages: List<SteerNote> = emptyList(),
)
@@ -535,6 +547,16 @@ data class Step(
@Serializable
data class MessageEnd(val phase: String = "", val reason: String = "", val text: String = "")
/** A page in a reply's text: its title (the page itself is fetched by its digest, by a client that draws pages). */
@Serializable
data class StepPage(val title: String = "", val digest: String = "")
/**
* What a client that draws no pages shows of a `text` step: the server's own text where the step
* has pages (each page its one line), else the markdown as it is.
*/
val Step.shownMarkdown: String get() = text?.takeIf { pages.isNotEmpty() && it.isNotBlank() } ?: markdown.orEmpty()
@Serializable
data class Message(
val id: String,
@@ -1,6 +1,7 @@
package eu.llembas.android.api
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNames
@@ -35,6 +36,8 @@ data class Report(
val summary: String = "",
val importance: String = "normal",
val schedule: ReportSchedule? = null,
/** The schedule's name as it was when the report was filed: what is left once the schedule itself is gone. */
@SerialName("schedule_title") val scheduleTitle: String = "",
@JsonNames("created_at") val created: String? = null,
val unread: Boolean = false,
val body: String? = null,
@@ -45,6 +48,9 @@ data class Report(
) {
val high: Boolean get() = importance == "high"
/** The name of the task it came from: the schedule's as it is now, else as it was. */
val from: String get() = schedule?.title?.ifBlank { null } ?: scheduleTitle
/** The chat a reply to this report continues in; null before the first reply. */
val chatId: String? get() = idOf(chat)
}
@@ -85,5 +91,11 @@ fun notifyChoice(notify: String): String = when (notify) {
else -> "when"
}
/** `scheduled.notify.default_condition`: what "When…" starts from, in the spec's words. */
const val NOTIFY_DEFAULT_CONDITION = "something needs my attention"
/**
* An id as the server makes them -- letters, digits, `_` and `-`, at most 64 -- or null. Anything
* that came from outside the app (a push payload, an intent's extra) is passed through this
* before it becomes part of a route or an address: a `/` in it must not open another page.
*/
fun safeId(id: String?): String? = id?.takeIf { SAFE_ID.matches(it) }
private val SAFE_ID = Regex("^[A-Za-z0-9_-]{1,64}$")
@@ -17,6 +17,7 @@ import eu.llembas.android.R
import eu.llembas.android.api.CardAnswer
import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.PushPayload
import eu.llembas.android.api.safeId
import eu.llembas.android.auth.Instance
import eu.llembas.android.lembas
import kotlinx.coroutines.CoroutineScope
@@ -102,11 +103,16 @@ object Notifications {
const val EXTRA_RUN = "eu.llembas.android.RUN"
const val EXTRA_REPORT = "eu.llembas.android.REPORT"
/** Whether [kind] is about a chat: a finished reply (which older payloads leave unnamed) or a question or an approval. */
fun chatKind(kind: String): Boolean = kind == "" || kind == "reply" || kind == "ask"
fun show(context: Context, instance: String, payload: PushPayload) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return
if (payload.kind == "schedule" || payload.kind == "schedule_failed") return scheduled(context, instance, payload)
if (payload.kind == ReportNotice.KIND) return report(context, instance, payload)
val chatId = payload.chatId ?: payload.url.removePrefix("/chat/").takeIf { payload.url.startsWith("/chat/") }
// A kind this app does not know -- a newer server's -- is not guessed at: no notification.
if (!chatKind(payload.kind)) return
val chatId = safeId(payload.chatId ?: payload.url.removePrefix("/chat/").takeIf { payload.url.startsWith("/chat/") })
val id = (chatId ?: payload.url).hashCode()
val open = opener(context, instance, id, chatId = chatId)
val channel = when (payload.kind) {
@@ -195,7 +201,10 @@ object Notifications {
fun reportNotification(context: Context, instance: String, notice: ReportNotice): Notification {
val fixed = context.getString(R.string.report_new_public)
val open = opener(context, instance, notice.id, chatId = null, reportId = notice.reportId)
val public = NotificationCompat.Builder(context, LembasApp.CHANNEL_REPORTS)
// A report the model called important goes on a channel of its own that may come up over
// what is on screen: on Android 8 and later the channel decides that, not the notification.
val channel = if (notice.high) LembasApp.CHANNEL_REPORTS_HIGH else LembasApp.CHANNEL_REPORTS
val public = NotificationCompat.Builder(context, channel)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(fixed)
@@ -209,7 +218,7 @@ object Notifications {
.putExtra("notification", notice.id),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
return NotificationCompat.Builder(context, LembasApp.CHANNEL_REPORTS)
return NotificationCompat.Builder(context, channel)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(notice.title.ifBlank { fixed })
.setContentText(notice.summary)
@@ -225,6 +234,11 @@ object Notifications {
.build()
}
/** The report was read or deleted in the app: its notification has nothing left to say. */
fun reportSeen(context: Context, reportId: String) {
NotificationManagerCompat.from(context).cancel(ReportNotice.notificationId(reportId))
}
/** A notification action Android runs only once the phone is unlocked. */
private fun unlocked(title: String, intent: PendingIntent): NotificationCompat.Action =
NotificationCompat.Action.Builder(0, title, intent).setAuthenticationRequired(true).build()
@@ -1,6 +1,7 @@
package eu.llembas.android.push
import eu.llembas.android.api.PushPayload
import eu.llembas.android.api.safeId
/**
* What a filed report's push asks the app to show (harness spec 3.8.0, `reports.md` §4:
@@ -11,14 +12,18 @@ import eu.llembas.android.api.PushPayload
*/
data class ReportNotice(val reportId: String, val title: String, val summary: String, val high: Boolean) {
/** One notification per report: a later push about the same report replaces it. */
val id: Int get() = "report:$reportId".hashCode()
val id: Int get() = notificationId(reportId)
companion object {
const val KIND = "report"
/** The notification of the report with this id: what is cancelled once the report is read or deleted in the app. */
fun notificationId(reportId: String): Int = "report:$reportId".hashCode()
fun from(payload: PushPayload): ReportNotice? {
if (payload.kind != KIND) return null
val id = payload.reportId?.takeIf { it.isNotBlank() } ?: fromUrl(payload.url) ?: return null
// Only an id that looks like one: it becomes part of a route and of an address.
val id = safeId(payload.reportId?.takeIf { it.isNotBlank() } ?: fromUrl(payload.url)) ?: return null
// The report's own words are in the payload's `notification` (the payload's top is
// what an older client would show: the app's name and "New report"). A payload
// without one is read by its top.
@@ -1,6 +1,7 @@
package eu.llembas.android.push
import eu.llembas.android.api.PushPayload
import eu.llembas.android.api.safeId
/**
* What a scheduled run's push asks the app to show, read from the server's payload alone
@@ -40,8 +41,9 @@ data class ScheduledNotice(
fun from(payload: PushPayload): ScheduledNotice? {
if (payload.kind != KIND_RESULT && payload.kind != KIND_FAILED) return null
val (urlSchedule, urlRun) = fromUrl(payload.url)
val schedule = payload.scheduleId?.takeIf { it.isNotBlank() } ?: urlSchedule ?: return null
val run = payload.runId?.takeIf { it.isNotBlank() } ?: urlRun
// Only ids that look like ids: they become parts of a route and of an address.
val schedule = safeId(payload.scheduleId?.takeIf { it.isNotBlank() } ?: urlSchedule) ?: return null
val run = safeId(payload.runId?.takeIf { it.isNotBlank() } ?: urlRun)
val failed = payload.kind == KIND_FAILED
val words = payload.notification
val ask = words?.ask?.takeIf { it.isNotBlank() } ?: payload.ask
@@ -91,8 +91,10 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.llembas.android.R
import eu.llembas.android.api.Drawn
import eu.llembas.android.api.Message
import eu.llembas.android.api.ShowCard
import eu.llembas.android.api.drawn
import eu.llembas.android.ui.ModelAvatar
import eu.llembas.android.ui.ProgressStatus
import eu.llembas.android.ui.theme.LocalPalette
@@ -244,7 +246,13 @@ fun ChatContent(
ModelTitle(
model = info,
fallback = state.modelId ?: stringResource(R.string.app_name),
subtitle = if (report != null) reportTitle(report) else chat?.title?.ifBlank { null },
// A report's conversation says which report: by what it was entered with, else by
// what the chat itself says (after the app was closed in between).
subtitle = if (report != null || chat?.report != null) {
reportTitle(report?.ifBlank { null } ?: chat?.report?.title.orEmpty())
} else {
chat?.title?.ifBlank { null }
},
onClick = { picking = true },
)
},
@@ -264,10 +272,13 @@ fun ChatContent(
menu = false
actions.continueChat()
}
MenuItem(Icons.Filled.Archive, stringResource(R.string.archive)) {
menu = false
actions.change("archived", "true")
onLeave()
// Only what may be done to this chat: a report's conversation is not archived.
if (chat.allows("archive")) {
MenuItem(Icons.Filled.Archive, stringResource(R.string.archive)) {
menu = false
actions.change("archived", "true")
onLeave()
}
}
MenuItem(Icons.Filled.Delete, stringResource(R.string.delete)) {
menu = false
@@ -348,20 +359,29 @@ fun ChatContent(
item { TextButton(onClick = actions::older) { Text(stringResource(R.string.older)) } }
}
items(rows, key = { it.id }) { message ->
when {
message.isUser -> UserMessage(message, canEdit = !message.machine && live == null, onEdit = { editing = message })
// The first row is the chat's first message only once nothing older is left to load.
val first = !state.more && message.id == rows.firstOrNull()?.id
when (drawn(message, first, reportChat = report != null || chat?.report != null)) {
// The server's own line in the person's place: nothing, or a note.
Drawn.Hidden -> Unit
live != null && live.messageId == message.id && live.finished == null ->
AssistantMessage(message, live.shown, writing = true, canRegenerate = false, onRegenerate = {}, onShow = onShow)
Drawn.Note -> MachineNote(message.text.orEmpty())
else -> AssistantMessage(
message,
message.steps,
writing = false,
canRegenerate = live == null && message == rows.lastOrNull(),
onRegenerate = { actions.regenerate(message) },
onShow = onShow,
)
Drawn.Person -> UserMessage(message, canEdit = live == null, onEdit = { editing = message })
Drawn.Reply -> when {
live != null && live.messageId == message.id && live.finished == null ->
AssistantMessage(message, live.shown, writing = true, canRegenerate = false, onRegenerate = {}, onShow = onShow)
else -> AssistantMessage(
message,
message.steps,
writing = false,
canRegenerate = live == null && message == rows.lastOrNull(),
onRegenerate = { actions.regenerate(message) },
onShow = onShow,
)
}
}
}
}
@@ -87,6 +87,7 @@ import eu.llembas.android.api.ShowCard
import eu.llembas.android.api.Step
import eu.llembas.android.api.ToolCall
import eu.llembas.android.api.ending
import eu.llembas.android.api.shownMarkdown
import eu.llembas.android.lembas
import eu.llembas.android.ui.MarkdownText
import eu.llembas.android.ui.Segment
@@ -170,6 +171,25 @@ fun UserMessage(message: Message, canEdit: Boolean, onEdit: () -> Unit, modifier
}
}
/**
* A line the server wrote in the person's place (a schedule's instruction, what opens a report's
* conversation): a quiet note across the width, a few lines of it -- never the person's bubble,
* and never markdown.
*/
@Composable
fun MachineNote(text: String, modifier: Modifier = Modifier) {
val palette = LocalPalette.current
if (text.isBlank()) return
Text(
text.trim(),
style = MaterialTheme.typography.bodySmall,
color = palette.inkFaint,
maxLines = 4,
overflow = TextOverflow.Ellipsis,
modifier = modifier.fillMaxWidth().padding(horizontal = 8.dp),
)
}
/**
* The model's turn, full width and without a bubble: its steps (thinking and tools folded into
* chips that open), its words as markdown, and under it Copy, Regenerate and what it cost. While
@@ -301,7 +321,7 @@ fun AssistantMessage(
fun replyText(message: Message): String = pageProjection(
message.steps.mapNotNull { step ->
when (step.kind) {
"text" -> step.markdown
"text" -> step.shownMarkdown
"page" -> "[page: ${step.title.orEmpty()}]"
else -> null
}
@@ -368,7 +388,7 @@ fun StepsCompact(steps: List<Step>, modifier: Modifier = Modifier, onShow: ((Sho
when (step.kind) {
"thinking" -> ThinkingChip(step)
"text" -> RichMarkdown(step.markdown.orEmpty(), onLongPress = onLongPress)
"text" -> RichMarkdown(step.shownMarkdown, onLongPress = onLongPress)
// A page the server took out of the text as a step of its own: the same card.
"page" -> PageCard(step.title.orEmpty())
@@ -73,6 +73,7 @@ import androidx.compose.ui.unit.dp
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import eu.llembas.android.R
import eu.llembas.android.api.ApiException
import eu.llembas.android.api.Chat
import eu.llembas.android.api.Doorstep
import eu.llembas.android.api.Folder
@@ -106,6 +107,8 @@ data class ChatsState(
val foundFor: String = "",
/** How many reports are unread: the badge on Reports. */
val unreadReports: Int = 0,
/** Whether the instance has Reports at all: one before 2.0.0-beta.12 has no such page to open. */
val reports: Boolean = false,
)
/** The drawer's list: every chat of the instance in use, both kinds, newest first. */
@@ -139,8 +142,23 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
// Folders are a side dish: the chats show without them if they cannot be read.
val folders = runCatching { api.folders() }.getOrDefault(_state.value.folders)
// So is the count of unread reports: an instance before Reports simply has none.
val unread = runCatching { api.unreadReports() }.getOrDefault(0)
_state.value = ChatsState(chats = page.chats, more = page.more, folders = folders, unreadReports = unread)
val unread = runCatching { api.unreadReports() }
// No such route (404, 405): no Reports. Any other trouble leaves what was known.
val refused = (unread.exceptionOrNull() as? ApiException)?.status
val has = if (unread.isSuccess) {
true
} else if (refused == 404 || refused == 405) {
false
} else {
_state.value.reports
}
_state.value = ChatsState(
chats = page.chats,
more = page.more,
folders = folders,
unreadReports = unread.getOrDefault(_state.value.unreadReports),
reports = has,
)
} catch (e: Exception) {
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
}
@@ -337,7 +355,9 @@ fun DrawerContent(
item { DrawerItem(Icons.Filled.EditNote, stringResource(R.string.new_chat), onClick = actions::newChat) }
item { DrawerItem(Icons.Filled.Terminal, stringResource(R.string.new_agent_chat), onClick = actions::newAgentChat) }
item { DrawerItem(Icons.Filled.Folder, stringResource(R.string.files), onClick = actions::files) }
item { DrawerItem(Icons.Filled.Summarize, stringResource(R.string.reports), badge = state.unreadReports, onClick = actions::reports) }
if (state.reports) {
item { DrawerItem(Icons.Filled.Summarize, stringResource(R.string.reports), badge = state.unreadReports, onClick = actions::reports) }
}
item { DrawerItem(Icons.Filled.Schedule, stringResource(R.string.scheduled), onClick = actions::scheduled) }
item { DrawerItem(Icons.Filled.Inventory2, stringResource(R.string.archived), onClick = actions::archived) }
item { DrawerItem(Icons.Filled.Psychology, stringResource(R.string.memory), onClick = actions::memory) }
@@ -68,6 +68,7 @@ import eu.llembas.android.api.ApiException
import eu.llembas.android.api.Report
import eu.llembas.android.api.sortedReports
import eu.llembas.android.lembas
import eu.llembas.android.push.Notifications
import eu.llembas.android.ui.chat.RichMarkdown
import eu.llembas.android.ui.explain
import eu.llembas.android.ui.pageProjection
@@ -115,11 +116,13 @@ class ReportsViewModel(app: Application) : AndroidViewModel(app) {
/** Read: it stays in the list, among those read. A failure is put right by reading the list again. */
fun markRead(report: Report) {
_state.update { s -> s.copy(reports = sortedReports(s.reports.map { if (it.id == report.id) it.copy(unread = false) else it })) }
Notifications.reportSeen(getApplication(), report.id)
viewModelScope.launch { runCatching { getApplication<Application>().api().readReport(report.id) }.onFailure { fail(it) } }
}
fun delete(report: Report) {
_state.update { s -> s.copy(reports = s.reports.filterNot { it.id == report.id }) }
Notifications.reportSeen(getApplication(), report.id)
viewModelScope.launch { runCatching { getApplication<Application>().api().deleteReport(report.id) }.onFailure { fail(it) } }
}
@@ -292,7 +295,7 @@ private fun ReportRow(report: Report, onOpen: () -> Unit, onRead: () -> Unit, on
@Composable
private fun ReportFacts(report: Report) {
val palette = LocalPalette.current
val facts = listOfNotNull(report.schedule?.title?.ifBlank { null }, ScheduleLogic.moment(report.created)).joinToString(" · ")
val facts = listOfNotNull(report.from.ifBlank { null }, ScheduleLogic.moment(report.created)).joinToString(" · ")
if (facts.isNotBlank()) Text(facts, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
@@ -312,6 +315,8 @@ class ReportViewModel(app: Application) : AndroidViewModel(app) {
val api = getApplication<Application>().api()
val report = api.report(id)
_state.value = ReportState(report = report.copy(unread = false), loading = false)
// Read here: its notification, if one is still up, goes.
Notifications.reportSeen(getApplication(), id)
if (report.unread) runCatching { api.readReport(id) }
} catch (e: Exception) {
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
@@ -424,7 +429,8 @@ fun ReportContent(state: ReportState, onBack: () -> Unit = {}, onRetry: () -> Un
}
}
ReportFacts(report)
RichMarkdown(report.body.orEmpty().ifBlank { report.summary })
// The server's own text of the body, where each page is its one line; else the body.
RichMarkdown((report.text?.ifBlank { null } ?: report.body.orEmpty()).ifBlank { report.summary })
}
}
}
@@ -804,8 +804,26 @@ data class EditState(
val reports: Boolean = false,
/** The server's default condition in the account's language, when it said one. */
val notifyDefault: String = "",
/** Editing: the schedule was read, so the form shows what it really has; or reading it failed, and nothing may be saved over it. */
val loaded: Boolean = false,
val loadFailed: Boolean = false,
/** The person chose a "notify when" themselves. */
val notifyTouched: Boolean = false,
)
/**
* The `notify` a save sends, or null for none: only to an instance with Reports, and when
* [editing] only what the form really knows -- the schedule's own value once it was read, or the
* person's choice. A form that could not read the schedule must not write its default over an
* "every run" or a "never".
*/
fun notifyToSend(state: EditState, editing: Boolean): String? = when {
!state.reports -> null
!editing -> state.notify
state.loaded || state.notifyTouched -> state.notify
else -> null
}
class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
private val _state = MutableStateFlow(EditState())
val state = _state.asStateFlow()
@@ -828,23 +846,26 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
runCatching { getApplication<Application>().api().schedule(id) }.onSuccess { s ->
_state.update {
it.copy(
words = s.request.ifBlank {
s.instruction
},
notify = notifyChoice(s.notify),
notifyWhen = s.notifyWhen,
words = s.request.ifBlank { s.instruction },
// What the person chose while it was read stays chosen.
notify = if (it.notifyTouched) it.notify else notifyChoice(s.notify),
notifyWhen = if (it.notifyTouched) it.notifyWhen else s.notifyWhen,
notifyDefault = s.notifyDefault,
loaded = true,
)
}
}.onFailure { e ->
// Not read: said, and Save waits -- the form would write its own defaults over the schedule.
_state.update { it.copy(loadFailed = true, error = getApplication<Application>().explain(e)) }
}
}
}
fun words(text: String) = _state.update { it.copy(words = text, compiled = null) }
fun notify(value: String) = _state.update { it.copy(notify = notifyChoice(value)) }
fun notify(value: String) = _state.update { it.copy(notify = notifyChoice(value), notifyTouched = true) }
fun notifyWhen(text: String) = _state.update { it.copy(notifyWhen = text) }
fun notifyWhen(text: String) = _state.update { it.copy(notifyWhen = text, notifyTouched = true) }
/** The server reads the words: the title, the instruction, the rule and the next runs. */
fun preview() {
@@ -873,7 +894,7 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
compiled,
now.words.trim(),
editing,
notify = now.notify.takeIf { now.reports },
notify = notifyToSend(now, editing = editing != null),
notifyWhen = now.notifyWhen,
)
then(saved.id)
@@ -930,7 +951,7 @@ fun ScheduleEditContent(
Box(Modifier.background(palette.bg).navigationBarsPadding().imePadding().padding(16.dp)) {
Button(
onClick = onSave,
enabled = state.compiled?.savable == true && !state.saving,
enabled = state.compiled?.savable == true && !state.saving && !state.loadFailed,
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
) { Text(stringResource(R.string.save)) }
}
@@ -1004,9 +1025,11 @@ private fun NotifyWhen(notify: String, words: String, default: String, onNotify:
if (value == "when" && notify == "when") {
val usual = default.ifBlank { stringResource(R.string.notify_when_default) }
OutlinedTextField(
value = words.ifEmpty { usual },
// Empty is allowed and means the default, which stands there as the placeholder.
value = words,
onValueChange = onWords,
label = { Text(stringResource(R.string.notify_when_label)) },
placeholder = { Text(usual) },
shape = RoundedCornerShape(16.dp),
modifier = Modifier.fillMaxWidth().padding(start = 52.dp, end = 16.dp, bottom = 8.dp),
)