Scheduled on the server's real routes: runs in full, the models, the push
CI / check (push) Canceled after 0s
CI / check (push) Canceled after 0s
api/Schedules.kt and ApiClient now follow /api/v2 exactly (src/lembas/api/v2/schedules.py):
the schedule's enabled/description/request/rule, a run's model object, error class and
text, waiting and retry, preview; compile returns ok/reason and the rule in words; a run
in full (GET runs/{run}, Markdown through Markwon); the scheduling models (GET/PUT) with
a tick per model; /events keeps the list current while it is on screen.
Notifications are built from the payload notify.py sends (ids, status, private, actions,
ask): VISIBILITY_PRIVATE with a public version, Open always, Pause when the server offers
it, a tap opens the run (switching to the instance it came from).
ScheduleContractTest reads all eight fixtures and the push payload; shots for the run and
the models screen, fakes shaped like the fixtures.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
25 files changed
+1335
-208
No files matched your search
@@ -25,6 +25,7 @@ import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
@@ -34,24 +35,28 @@ import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.push.Push
|
||||
import eu.llembas.android.ui.chat.ChatScreen
|
||||
import eu.llembas.android.ui.files.FilesScreen
|
||||
import eu.llembas.android.ui.home.ChatsViewModel
|
||||
import eu.llembas.android.ui.home.DrawerActions
|
||||
import eu.llembas.android.ui.home.DrawerContent
|
||||
import eu.llembas.android.ui.scheduled.RunScreen
|
||||
import eu.llembas.android.ui.scheduled.ScheduleEditScreen
|
||||
import eu.llembas.android.ui.scheduled.ScheduleScreen
|
||||
import eu.llembas.android.ui.scheduled.ScheduledScreen
|
||||
import eu.llembas.android.ui.scheduled.SchedulingModelsScreen
|
||||
import eu.llembas.android.ui.settings.SettingsScreen
|
||||
import eu.llembas.android.ui.signin.SignInScreen
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
private data class Loaded(val instance: Instance?)
|
||||
|
||||
/** Where a notification (or the assistant, or a share) asked the app to open. */
|
||||
private data class Opening(val chat: String?, val schedule: String?)
|
||||
private data class Opening(val chat: String?, val schedule: String?, val run: String? = null, val instance: String? = null)
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
/** A chat or a schedule a notification, the assistant or a share asked to open; consumed once. */
|
||||
@@ -82,7 +87,19 @@ class MainActivity : ComponentActivity() {
|
||||
private fun take(intent: Intent?) {
|
||||
val chat = intent?.getStringExtra(Notifications.EXTRA_CHAT)
|
||||
val schedule = intent?.getStringExtra(Notifications.EXTRA_SCHEDULE)
|
||||
if (chat != null || schedule != null) opening.value = Opening(chat, schedule)
|
||||
val run = intent?.getStringExtra(Notifications.EXTRA_RUN)
|
||||
val instance = intent?.getStringExtra(Notifications.EXTRA_INSTANCE)
|
||||
if (chat == null && schedule == null) return
|
||||
opening.value = Opening(chat, schedule, run, instance)
|
||||
// A notification from another of the person's instances: that one comes into use, and
|
||||
// its pages (keyed by the instance) open what was asked.
|
||||
if (instance != null) {
|
||||
lifecycleScope.launch {
|
||||
if (lembas.instances.active.first()?.id != instance && Push.instance(this@MainActivity, instance) != null) {
|
||||
lembas.instances.use(instance)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -129,9 +146,15 @@ class MainActivity : ComponentActivity() {
|
||||
LaunchedEffect(drawer.isOpen) { if (drawer.isOpen) chats.load() }
|
||||
LaunchedEffect(open) {
|
||||
open?.let {
|
||||
// Meant for another instance: left for that one's pages, once it is in use.
|
||||
if (it.instance != null && it.instance != instance.id) return@let
|
||||
when {
|
||||
it.chat != null -> top("chat/${it.chat}")
|
||||
it.schedule != null -> over("schedule/${it.schedule}")
|
||||
|
||||
it.schedule != null -> {
|
||||
over("schedule/${it.schedule}")
|
||||
it.run?.let { run -> over("schedule/${it.schedule}/run/$run") }
|
||||
}
|
||||
}
|
||||
opened()
|
||||
}
|
||||
@@ -196,11 +219,32 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
composable("files") { FilesScreen(onBack = { nav.popBackStack() }) }
|
||||
composable("scheduled") {
|
||||
ScheduledScreen(onBack = { nav.popBackStack() }, onOpen = { over("schedule/$it") }, onNew = { over("schedule-new") })
|
||||
ScheduledScreen(
|
||||
onBack = { nav.popBackStack() },
|
||||
onOpen = { over("schedule/$it") },
|
||||
onNew = { over("schedule-new") },
|
||||
onModels = { over("scheduled-models") },
|
||||
)
|
||||
}
|
||||
composable("scheduled-models") {
|
||||
SchedulingModelsScreen(onBack = { nav.popBackStack() })
|
||||
}
|
||||
composable("schedule/{id}") { e ->
|
||||
val id = e.arguments?.getString("id").orEmpty()
|
||||
ScheduleScreen(id, onBack = { nav.popBackStack() }, onEdit = { over("schedule-edit/$it") }, onOpenChat = { top("chat/$it") })
|
||||
ScheduleScreen(
|
||||
id,
|
||||
onBack = { nav.popBackStack() },
|
||||
onEdit = { over("schedule-edit/$it") },
|
||||
onOpenRun = { run -> over("schedule/$id/run/$run") },
|
||||
)
|
||||
}
|
||||
composable("schedule/{id}/run/{run}") { e ->
|
||||
RunScreen(
|
||||
e.arguments?.getString("id").orEmpty(),
|
||||
e.arguments?.getString("run").orEmpty(),
|
||||
onBack = { nav.popBackStack() },
|
||||
onOpenChat = { top("chat/$it") },
|
||||
)
|
||||
}
|
||||
composable("schedule-new") {
|
||||
ScheduleEditScreen(null, onBack = { nav.popBackStack() }, onSaved = { id ->
|
||||
|
||||
@@ -252,24 +252,44 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
|
||||
suspend fun stopMember(chatId: String, name: String): List<String> = send<Stopped>("POST", "/chats/$chatId/team/${segment(name)}/stop", null).stopped
|
||||
|
||||
// --- Scheduled tasks (provisional routes; see api/Schedules.kt) ---------------------------
|
||||
// --- Scheduled tasks (`/api/v2/schedules`; shapes in api/Schedules.kt) ----------------------
|
||||
|
||||
/** Every schedule of this person, newest first, each with its last run. */
|
||||
suspend fun schedules(): List<Schedule> = get<ScheduleList>("/schedules").schedules
|
||||
|
||||
suspend fun schedule(id: String): Schedule = get<ScheduleEnvelope>("/schedules/${segment(id)}").schedule
|
||||
|
||||
suspend fun scheduleRuns(id: String, before: String? = null): ScheduleRuns =
|
||||
get("/schedules/${segment(id)}/runs" + (before?.let { "?before=${segment(it)}" } ?: ""))
|
||||
/** A page of a schedule's runs, newest first; [before] is the last run's id of the page before. */
|
||||
suspend fun scheduleRuns(id: String, before: String? = null, limit: Int = 20): ScheduleRuns =
|
||||
get("/schedules/${segment(id)}/runs?limit=$limit" + (before?.let { "&before=${segment(it)}" } ?: ""))
|
||||
|
||||
/** Words to a rule, an instruction and the next runs; nothing is saved. */
|
||||
suspend fun compileSchedule(words: String): SchedulePreview =
|
||||
send<SchedulePreviewEnvelope>("POST", "/schedules/compile", buildJsonObject { put("text", words) }).preview
|
||||
/** One run and its result in full (Markdown a model wrote: untrusted). */
|
||||
suspend fun scheduleRun(id: String, runId: String): RunResult = get("/schedules/${segment(id)}/runs/${segment(runId)}")
|
||||
|
||||
/** Save a preview: a new schedule, or (with [id]) the one being edited. */
|
||||
suspend fun saveSchedule(preview: SchedulePreview, id: String? = null): Schedule {
|
||||
/** Words to a schedule: title, instruction, rule, the rule in words, the next runs. Saves nothing. */
|
||||
suspend fun compileSchedule(words: String, model: String? = null): ScheduleCompiled = send(
|
||||
"POST",
|
||||
"/schedules/compile",
|
||||
buildJsonObject {
|
||||
put("text", words)
|
||||
model?.let { put("model", it) }
|
||||
},
|
||||
)
|
||||
|
||||
/** A rule read back: cleaned, in words, and its next runs. An empty rule cannot run. */
|
||||
suspend fun previewRule(rule: JsonObject): RulePreview = send("POST", "/schedules/preview", buildJsonObject { put("rule", rule) })
|
||||
|
||||
/**
|
||||
* Save what the compile made of [words]: a new schedule (201), or with [id] the one being
|
||||
* edited. The words go along as the schedule's `request`, so editing starts from them.
|
||||
*/
|
||||
suspend fun saveSchedule(compiled: ScheduleCompiled, words: String, id: String? = null): Schedule {
|
||||
val body = buildJsonObject {
|
||||
put("title", preview.title)
|
||||
put("instruction", preview.instruction)
|
||||
preview.rule?.let { put("rule", it) }
|
||||
put("title", compiled.title)
|
||||
put("instruction", compiled.instruction)
|
||||
put("rule", compiled.rule)
|
||||
put("target", compiled.target)
|
||||
if (id == null) put("request", words)
|
||||
}
|
||||
return if (id == null) {
|
||||
send<ScheduleEnvelope>("POST", "/schedules", body).schedule
|
||||
@@ -281,11 +301,21 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
suspend fun pauseSchedule(id: String, paused: Boolean): Schedule =
|
||||
send<ScheduleEnvelope>("POST", "/schedules/${segment(id)}/" + if (paused) "pause" else "resume", null).schedule
|
||||
|
||||
suspend fun runScheduleNow(id: String) {
|
||||
send<JsonObject>("POST", "/schedules/${segment(id)}/run", null)
|
||||
}
|
||||
/** Run it now (202); the next scheduled run is not used up by this one. */
|
||||
suspend fun runScheduleNow(id: String): ScheduleRun = send<RunEnvelope>("POST", "/schedules/${segment(id)}/run", null).run
|
||||
|
||||
suspend fun deleteSchedule(id: String) = empty(authed("$v2/schedules/${segment(id)}").delete().build())
|
||||
/** Delete it; [keepChat] keeps the chat its results went to. */
|
||||
suspend fun deleteSchedule(id: String, keepChat: Boolean = true) = empty(authed("$v2/schedules/${segment(id)}?keep_chat=$keepChat").delete().build())
|
||||
|
||||
/** The models scheduled work may run on, in the order they are tried, and which are free. */
|
||||
suspend fun schedulingModels(): SchedulingModels = get("/schedules/models")
|
||||
|
||||
/** The person's narrowing of that list ([ids] empty: all of them). */
|
||||
suspend fun chooseSchedulingModels(ids: List<String>): SchedulingModels =
|
||||
send("PUT", "/schedules/models", buildJsonObject { put("models", JsonArray(ids.map { JsonPrimitive(it) })) })
|
||||
|
||||
/** The person's events route: a `schedules` frame with the whole list whenever it changes. */
|
||||
fun events(): Request = authed("$v2/events").header("Accept", "text/event-stream").build()
|
||||
|
||||
// --- Model pictures --------------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -486,9 +486,17 @@ data class PushPayload(
|
||||
@SerialName("message_id") val messageId: String? = null,
|
||||
@SerialName("interaction_id") val interactionId: String? = null,
|
||||
val ask: String? = null,
|
||||
/** A scheduled task's result or failure (`kind` `schedule` or `schedule_failed`). */
|
||||
/**
|
||||
* A scheduled run's result or failure (`kind` `schedule` or `schedule_failed`,
|
||||
* services/schedule/notify.py): the ids, the run's [status], `private` [visibility] (the
|
||||
* text stays off the lock screen), the [actions] the notification may offer (`open`,
|
||||
* `pause`), and [ask] `pause` when it failed so often that it asks whether to pause it.
|
||||
*/
|
||||
@SerialName("schedule_id") val scheduleId: String? = null,
|
||||
@SerialName("run_id") val runId: String? = null,
|
||||
val status: String? = null,
|
||||
val visibility: String? = null,
|
||||
val actions: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
// --- The activity panel (`GET /chats/{chat}/activity`) -------------------------------------
|
||||
|
||||
@@ -6,56 +6,100 @@ import kotlinx.serialization.json.JsonObject
|
||||
|
||||
// --- Scheduled tasks (`/api/v2/schedules`) ------------------------------------------------
|
||||
//
|
||||
// Provisional: written against the server's scheduling plan before its routes and contract
|
||||
// fixtures landed. Every field has a default, so a server that says less still parses; the
|
||||
// contract re-pin is where these meet the server's real shapes (and `ContractTest` holds them).
|
||||
// The server's shapes, as its contract fixtures pin them (`contract/schedule*.json`,
|
||||
// `event_schedules.json`; `ContractTest` reads every one). Every field has a default, so a
|
||||
// server that says less still parses.
|
||||
|
||||
/** The model a run used: [reason] `switched` when it stood in for [switchedFrom], which was busy. */
|
||||
@Serializable
|
||||
data class RunModel(
|
||||
val id: String? = null,
|
||||
val name: String? = null,
|
||||
val reason: String? = null,
|
||||
@SerialName("switched_from") val switchedFrom: String? = null,
|
||||
) {
|
||||
/** What to call it: its name, else its id. */
|
||||
val label: String? get() = name ?: id
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class RunTokens(val prompt: Long = 0, val completion: Long = 0)
|
||||
|
||||
@Serializable
|
||||
data class RunCost(val micro: Long = 0, val currency: String = "")
|
||||
|
||||
/** Why a run failed or waits: [kind] a class the app may read, [text] the server's own sentence. */
|
||||
@Serializable
|
||||
data class RunError(@SerialName("class") val kind: String = "", val text: String = "")
|
||||
|
||||
/**
|
||||
* One run of a schedule: when it was due and how it went. [status] is `ok`, `silent` (nothing
|
||||
* worth saying), `failed`, `missed`, `skipped`, `waiting` (no model free yet) or `running`;
|
||||
* [timing] `on_time`, `late` or `catch_up`. [error] is the server's sentence, never a model's.
|
||||
* One run of a schedule: when it was due and how it went. [status] is `running`, `waiting` (no
|
||||
* model free yet, or a retry: [waitingFor], [retryAt]), `ok`, `silent` (nothing worth saying),
|
||||
* `failed`, `skipped` or `missed`; [timing] `on_time`, `late`, `catch_up` or `manual`.
|
||||
* [preview] is the result's first lines -- model output, shown as plain text and never as markup.
|
||||
*/
|
||||
@Serializable
|
||||
data class ScheduleRun(
|
||||
val id: String = "",
|
||||
@SerialName("schedule_id") val scheduleId: String = "",
|
||||
val status: String = "",
|
||||
val timing: String = "",
|
||||
/** How many runs were missed before this one (`missed ×N`). */
|
||||
val missed: Int = 0,
|
||||
@SerialName("due_at") val dueAt: String? = null,
|
||||
@SerialName("started_at") val startedAt: String? = null,
|
||||
@SerialName("finished_at") val finishedAt: String? = null,
|
||||
val status: String = "",
|
||||
val timing: String = "",
|
||||
val model: String = "",
|
||||
/** `pinned`, or the reason another model ran it (`switched: <from> busy`). */
|
||||
@SerialName("model_reason") val modelReason: String = "",
|
||||
@SerialName("waiting_for") val waitingFor: String? = null,
|
||||
@SerialName("retry_at") val retryAt: String? = null,
|
||||
val attempts: Int = 0,
|
||||
val model: RunModel = RunModel(),
|
||||
val tokens: RunTokens = RunTokens(),
|
||||
val cost: RunCost? = null,
|
||||
@SerialName("chat_id") val chatId: String? = null,
|
||||
@SerialName("message_id") val messageId: String? = null,
|
||||
@SerialName("report_path") val reportPath: String? = null,
|
||||
val error: String = "",
|
||||
/** How many runs were missed before this one (`missed ×N`). */
|
||||
val missed: Int = 0,
|
||||
val preview: String = "",
|
||||
val error: RunError? = null,
|
||||
val notified: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* A scheduled task. [rule] is the recurrence in words, as the server says it ("Every weekday at
|
||||
* 08:00"); [instruction] what the model is asked each time. [notify] is `always`, `matters` or
|
||||
* `never`; [mode] `fresh` (a chat per run) or `continue` (one growing chat).
|
||||
* A scheduled task. [description] is the rule in words, as the server says it ("On the second
|
||||
* Monday of each month at 07:30"), in [timezone]; [rule] the server's own form of it; [request]
|
||||
* the person's words it was made from; [instruction] what the model is asked each time.
|
||||
* [notify] is `always`, `matters` or `never`; [mode] `fresh` (a chat per run) or `continue`.
|
||||
*/
|
||||
@Serializable
|
||||
data class Schedule(
|
||||
val id: String,
|
||||
val title: String = "",
|
||||
val instruction: String = "",
|
||||
val rule: String = "",
|
||||
val paused: Boolean = false,
|
||||
val request: String = "",
|
||||
val rule: JsonObject = JsonObject(emptyMap()),
|
||||
val description: String? = null,
|
||||
val timezone: String = "",
|
||||
val enabled: Boolean = true,
|
||||
@SerialName("next_run") val nextRun: String? = null,
|
||||
@SerialName("next_runs") val nextRuns: List<String> = emptyList(),
|
||||
@SerialName("last_run") val lastRun: ScheduleRun? = null,
|
||||
val model: String = "",
|
||||
val notify: String = "",
|
||||
val target: String = "chat",
|
||||
val mode: String = "",
|
||||
@SerialName("failure_streak") val failureStreak: Int = 0,
|
||||
val notify: String = "",
|
||||
@SerialName("catch_up") val catchUp: String = "",
|
||||
@SerialName("grace_minutes") val graceMinutes: Int? = null,
|
||||
val model: String? = null,
|
||||
val effort: String? = null,
|
||||
val agents: Int? = null,
|
||||
val tools: List<String> = emptyList(),
|
||||
val origin: String = "",
|
||||
@SerialName("chat_id") val chatId: String? = null,
|
||||
@SerialName("fired_count") val firedCount: Int = 0,
|
||||
@SerialName("failure_streak") val failureStreak: Int = 0,
|
||||
@SerialName("last_error") val lastError: String? = null,
|
||||
@SerialName("last_run") val lastRun: ScheduleRun? = null,
|
||||
val running: Boolean = false,
|
||||
@SerialName("created_at") val createdAt: String? = null,
|
||||
) {
|
||||
val nextRun: String? get() = nextRuns.firstOrNull()
|
||||
val paused: Boolean get() = !enabled
|
||||
}
|
||||
|
||||
@Serializable
|
||||
@@ -64,22 +108,64 @@ data class ScheduleList(val schedules: List<Schedule> = emptyList())
|
||||
@Serializable
|
||||
data class ScheduleEnvelope(val schedule: Schedule)
|
||||
|
||||
@Serializable
|
||||
data class RunEnvelope(val run: ScheduleRun)
|
||||
|
||||
@Serializable
|
||||
data class ScheduleRuns(val runs: List<ScheduleRun> = emptyList(), val more: Boolean = false)
|
||||
|
||||
/** One run and its result in full: Markdown a model wrote, rendered as untrusted. Null: none. */
|
||||
@Serializable
|
||||
data class RunResult(val run: ScheduleRun, val text: String? = null)
|
||||
|
||||
/** `GET /events`, frame `schedules`: the whole list whenever [version] moves. */
|
||||
@Serializable
|
||||
data class SchedulesFrame(val version: String = "", val schedules: List<Schedule> = emptyList())
|
||||
|
||||
/**
|
||||
* What the server made of a person's words: a title, the rule in words, the instruction the
|
||||
* model will be given, and the next five runs -- shown before anything is saved. [rule] is the
|
||||
* server's own form of the rule, handed back unchanged when the preview is saved.
|
||||
* What the server made of a person's words (`POST /schedules/compile`): a title, the
|
||||
* instruction, the rule and the rule in words, and the next runs -- shown before anything is
|
||||
* saved. [ok] false: the rest is filled as far as it went, and [reason] says why. An empty
|
||||
* [rule] cannot run, so it cannot be saved.
|
||||
*/
|
||||
@Serializable
|
||||
data class SchedulePreview(
|
||||
data class ScheduleCompiled(
|
||||
val ok: Boolean = false,
|
||||
val reason: String? = null,
|
||||
val title: String = "",
|
||||
@SerialName("rule_text") val ruleText: String = "",
|
||||
val instruction: String = "",
|
||||
val target: String = "chat",
|
||||
val rule: JsonObject = JsonObject(emptyMap()),
|
||||
val description: String? = null,
|
||||
@SerialName("next_runs") val nextRuns: List<String> = emptyList(),
|
||||
val rule: JsonObject? = null,
|
||||
val timezone: String = "",
|
||||
) {
|
||||
val savable: Boolean get() = rule.isNotEmpty() && instruction.isNotBlank()
|
||||
}
|
||||
|
||||
/** A rule read back (`POST /schedules/preview`): cleaned, in words, and its next runs. */
|
||||
@Serializable
|
||||
data class RulePreview(
|
||||
val rule: JsonObject = JsonObject(emptyMap()),
|
||||
val description: String? = null,
|
||||
@SerialName("next_runs") val nextRuns: List<String> = emptyList(),
|
||||
val timezone: String = "",
|
||||
)
|
||||
|
||||
/**
|
||||
* A model scheduled work may run on, in the order they are tried: [free] now or [busy] (the
|
||||
* server's words), and [chosen] when it is in the person's narrowing (all are, without one).
|
||||
*/
|
||||
@Serializable
|
||||
data class SchedulePreviewEnvelope(val preview: SchedulePreview)
|
||||
data class SchedulingModel(
|
||||
val id: String,
|
||||
val name: String = "",
|
||||
val image: String? = null,
|
||||
val free: Boolean = false,
|
||||
val busy: String? = null,
|
||||
val chosen: Boolean = true,
|
||||
)
|
||||
|
||||
/** `GET`/`PUT /schedules/models`: the models, the instance's order, and the person's narrowing. */
|
||||
@Serializable
|
||||
data class SchedulingModels(val models: List<SchedulingModel> = emptyList(), val instance: List<String> = emptyList(), val mine: List<String> = emptyList())
|
||||
@@ -99,6 +99,7 @@ object Notifications {
|
||||
const val EXTRA_INSTANCE = "eu.llembas.android.INSTANCE"
|
||||
|
||||
const val EXTRA_SCHEDULE = "eu.llembas.android.SCHEDULE"
|
||||
const val EXTRA_RUN = "eu.llembas.android.RUN"
|
||||
|
||||
fun show(context: Context, instance: String, payload: PushPayload) {
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return
|
||||
@@ -130,48 +131,50 @@ object Notifications {
|
||||
}
|
||||
|
||||
/**
|
||||
* A scheduled task's result or failure, on its own channel. The result's first lines are
|
||||
* the account's, so the lock screen gets the public version instead: the app's name and
|
||||
* "a scheduled task finished" (or failed), nothing of what it said. Open goes to the run's
|
||||
* result (its chat) or else the schedule; Pause pauses the schedule from here.
|
||||
* A scheduled run's result or failure, on its own channel, built from the server's payload
|
||||
* alone ([ScheduledNotice]): the payload carries ids and one of the server's own fixed
|
||||
* sentences, never the result. Unlocked: the instance's name and that sentence. On the lock
|
||||
* screen the public version: the app's name and "a scheduled task has a result" (or failed).
|
||||
* A tap and Open go to the run; Pause is there when the server offers it.
|
||||
*/
|
||||
private fun scheduled(context: Context, instance: String, payload: PushPayload) {
|
||||
val failed = payload.kind == "schedule_failed"
|
||||
val id = (payload.runId ?: payload.scheduleId ?: payload.url).hashCode()
|
||||
val channel = if (failed) LembasApp.CHANNEL_SCHEDULED_FAILURES else LembasApp.CHANNEL_SCHEDULED
|
||||
val open = opener(context, instance, id, chatId = payload.chatId, scheduleId = payload.scheduleId.takeIf { payload.chatId == null })
|
||||
val notice = ScheduledNotice.from(payload) ?: return
|
||||
val channel = if (notice.failed) LembasApp.CHANNEL_SCHEDULED_FAILURES else LembasApp.CHANNEL_SCHEDULED
|
||||
val fixed = context.getString(if (notice.failed) R.string.scheduled_failed_public else R.string.scheduled_result_public)
|
||||
val open = opener(context, instance, notice.id, chatId = null, scheduleId = notice.scheduleId, runId = notice.runId)
|
||||
val public = NotificationCompat.Builder(context, channel)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.app_name))
|
||||
.setContentText(context.getString(if (failed) R.string.scheduled_failed_public else R.string.scheduled_result_public))
|
||||
.setContentText(fixed)
|
||||
.build()
|
||||
val body = payload.body.ifBlank { fixed }
|
||||
val builder = NotificationCompat.Builder(context, channel)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(payload.title)
|
||||
.setContentText(payload.body)
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(payload.body))
|
||||
.setContentTitle(payload.title.ifBlank { context.getString(R.string.scheduled) })
|
||||
.setContentText(body)
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(body))
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(open)
|
||||
.setCategory(if (failed) Notification.CATEGORY_ERROR else Notification.CATEGORY_STATUS)
|
||||
.setCategory(if (notice.failed) Notification.CATEGORY_ERROR else Notification.CATEGORY_STATUS)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
|
||||
.setPublicVersion(public)
|
||||
.addAction(0, context.getString(R.string.viewer_open), open)
|
||||
payload.scheduleId?.let { schedule ->
|
||||
builder.addAction(0, context.getString(R.string.schedule_pause), pause(context, instance, schedule, id))
|
||||
}
|
||||
NotificationManagerCompat.from(context).notify(id, builder.build())
|
||||
if (notice.open) builder.addAction(0, context.getString(R.string.viewer_open), open)
|
||||
if (notice.pause) builder.addAction(0, context.getString(R.string.schedule_pause), pause(context, instance, notice.scheduleId, notice.id))
|
||||
NotificationManagerCompat.from(context).notify(notice.id, builder.build())
|
||||
}
|
||||
|
||||
private fun opener(context: Context, instance: String, id: Int, chatId: String?, scheduleId: String? = null): PendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
id,
|
||||
Intent(context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.putExtra(EXTRA_CHAT, chatId)
|
||||
.putExtra(EXTRA_SCHEDULE, scheduleId)
|
||||
.putExtra(EXTRA_INSTANCE, instance),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
private fun opener(context: Context, instance: String, id: Int, chatId: String?, scheduleId: String? = null, runId: String? = null): PendingIntent =
|
||||
PendingIntent.getActivity(
|
||||
context,
|
||||
id,
|
||||
Intent(context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.putExtra(EXTRA_CHAT, chatId)
|
||||
.putExtra(EXTRA_SCHEDULE, scheduleId)
|
||||
.putExtra(EXTRA_RUN, runId)
|
||||
.putExtra(EXTRA_INSTANCE, instance),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
private fun pause(context: Context, instance: String, schedule: String, notification: Int): PendingIntent = PendingIntent.getBroadcast(
|
||||
context,
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package eu.llembas.android.push
|
||||
|
||||
import eu.llembas.android.api.PushPayload
|
||||
|
||||
/**
|
||||
* What a scheduled run's push asks the app to show, read from the server's payload alone
|
||||
* (services/schedule/notify.py `payload`): the schedule and the run it is about, whether it
|
||||
* failed, and the actions the server offers. A payload without ids falls back to its `url`
|
||||
* (`/scheduled/{schedule}?run={run}`), as a browser would open it.
|
||||
*/
|
||||
data class ScheduledNotice(
|
||||
val scheduleId: String,
|
||||
val runId: String?,
|
||||
val failed: Boolean,
|
||||
/** The server asks whether to pause it (it failed several times in a row). */
|
||||
val askPause: Boolean,
|
||||
val open: Boolean,
|
||||
val pause: Boolean,
|
||||
) {
|
||||
/** One notification per run: a later push about the same run replaces it. */
|
||||
val id: Int get() = "scheduled:${runId ?: scheduleId}".hashCode()
|
||||
|
||||
companion object {
|
||||
const val KIND_RESULT = "schedule"
|
||||
const val KIND_FAILED = "schedule_failed"
|
||||
|
||||
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
|
||||
val failed = payload.kind == KIND_FAILED
|
||||
val askPause = payload.ask == "pause"
|
||||
// An older payload named no actions: Open always, Pause for a failure.
|
||||
val actions = payload.actions.ifEmpty { if (failed) listOf("open", "pause") else listOf("open") }
|
||||
return ScheduledNotice(
|
||||
scheduleId = schedule,
|
||||
runId = run,
|
||||
failed = failed,
|
||||
askPause = askPause,
|
||||
open = "open" in actions,
|
||||
pause = "pause" in actions || askPause,
|
||||
)
|
||||
}
|
||||
|
||||
/** `/scheduled/{schedule}?run={run}` → the two ids; nulls for anything else. */
|
||||
fun fromUrl(url: String): Pair<String?, String?> {
|
||||
if (!url.startsWith("/scheduled/")) return null to null
|
||||
val rest = url.removePrefix("/scheduled/")
|
||||
val schedule = rest.substringBefore('?').substringBefore('/').takeIf { it.isNotBlank() }
|
||||
val run = rest.substringAfter('?', "").split('&').firstOrNull { it.startsWith("run=") }?.removePrefix("run=")?.takeIf { it.isNotBlank() }
|
||||
return schedule to run
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package eu.llembas.android.ui.scheduled
|
||||
|
||||
import android.app.Application
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
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.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.RunResult
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.chat.LocalCopy
|
||||
import eu.llembas.android.ui.chat.RichMarkdown
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
data class RunState(val title: String = "", val result: RunResult? = null, val loading: Boolean = false, val error: String? = null)
|
||||
|
||||
class RunViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(RunState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
/** The run and its result; the schedule's title too, for the bar (without it, "Scheduled"). */
|
||||
fun open(schedule: String, run: String) {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: throw ApiException(401, "Not signed in.")
|
||||
val result = api.scheduleRun(schedule, run)
|
||||
val title = runCatching { api.schedule(schedule).title }.getOrDefault("")
|
||||
_state.update { it.copy(result = result, title = title, loading = false) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun RunScreen(
|
||||
scheduleId: String,
|
||||
runId: String,
|
||||
onBack: () -> Unit,
|
||||
onOpenChat: (String) -> Unit,
|
||||
model: RunViewModel = viewModel(key = "run-$scheduleId-$runId"),
|
||||
) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LifecycleResumeEffect(runId) {
|
||||
model.open(scheduleId, runId)
|
||||
onPauseOrDispose { }
|
||||
}
|
||||
RunContent(state, onBack = onBack, onOpenChat = onOpenChat)
|
||||
}
|
||||
|
||||
/**
|
||||
* One run, where a notification's tap lands: its status and when, the model and why, and the
|
||||
* result in full -- Markdown a model wrote, drawn by the app's Markwon (no images, no HTML,
|
||||
* links only outside) -- or why there is none. Open its chat goes on from there.
|
||||
*/
|
||||
@Composable
|
||||
fun RunContent(state: RunState, onBack: () -> Unit = {}, onOpenChat: (String) -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
val copy: (String) -> Unit = remember(context) {
|
||||
{ text -> context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText("LLeMbas", text)) }
|
||||
}
|
||||
val result = state.result
|
||||
CompositionLocalProvider(LocalCopy provides copy) {
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
topBar = { BackBar(state.title.ifBlank { stringResource(R.string.scheduled) }, onBack) },
|
||||
) { padding ->
|
||||
if (result == null) {
|
||||
Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {
|
||||
if (state.loading) CircularProgressIndicator() else state.error?.let { Message(it) }
|
||||
}
|
||||
return@Scaffold
|
||||
}
|
||||
val run = result.run
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
StatusChip(run.status, run.missed)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
ScheduleLogic.moment(run.finishedAt ?: run.startedAt ?: run.dueAt) ?: "—",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
RunFacts(run, withPreview = false)
|
||||
}
|
||||
}
|
||||
Header(stringResource(R.string.run_result))
|
||||
val text = result.text
|
||||
if (text.isNullOrBlank()) {
|
||||
Text(stringResource(R.string.run_no_text), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
} else {
|
||||
RichMarkdown(text)
|
||||
}
|
||||
run.chatId?.let { chat ->
|
||||
FilledTonalButton(onClick = { onOpenChat(chat) }, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(top = 8.dp)) {
|
||||
Text(stringResource(R.string.run_open_chat))
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.heightIn(min = 24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.Pause
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Schedule
|
||||
import androidx.compose.material.icons.filled.Tune
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
@@ -73,13 +74,18 @@ import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.Schedule
|
||||
import eu.llembas.android.api.SchedulePreview
|
||||
import eu.llembas.android.api.ScheduleCompiled
|
||||
import eu.llembas.android.api.ScheduleRun
|
||||
import eu.llembas.android.api.SchedulesFrame
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.theme.Palette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
@@ -103,11 +109,14 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ScheduledState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
private var live: Job? = null
|
||||
|
||||
fun load() {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
_state.value = ScheduledState(schedules = getApplication<Application>().api().schedules())
|
||||
watch()
|
||||
} catch (e: Exception) {
|
||||
_state.update {
|
||||
if (e.unsupported()) {
|
||||
@@ -123,9 +132,37 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The person's events route while the list is on screen: the whole list again whenever it
|
||||
* changes (a run starting, waiting or finishing, a schedule made or paused elsewhere).
|
||||
* Without it the list is what the last read said, and a pull reads it again.
|
||||
*/
|
||||
private fun watch() {
|
||||
if (live?.isActive == true) return
|
||||
live = viewModelScope.launch {
|
||||
val client = runCatching { getApplication<Application>().api() }.getOrNull() ?: return@launch
|
||||
try {
|
||||
StreamClient(client).watch { client.events() }.collect { frame ->
|
||||
if (frame.event != "schedules") return@collect
|
||||
val read = runCatching { LembasJson.decodeFromString(SchedulesFrame.serializer(), frame.data) }.getOrNull() ?: return@collect
|
||||
_state.update { it.copy(schedules = read.schedules) }
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// An older server, or the stream refused: the list stays as last read.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
live?.cancel()
|
||||
live = null
|
||||
}
|
||||
|
||||
/** Pause or resume; the switch moves at once and comes back if the server says no. */
|
||||
fun pause(schedule: Schedule, paused: Boolean) {
|
||||
_state.update { s -> s.copy(schedules = s.schedules.map { if (it.id == schedule.id) it.copy(paused = paused) else it }) }
|
||||
_state.update { s -> s.copy(schedules = s.schedules.map { if (it.id == schedule.id) it.copy(enabled = !paused) else it }) }
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val saved = getApplication<Application>().api().pauseSchedule(schedule.id, paused)
|
||||
@@ -143,13 +180,13 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ScheduledScreen(onBack: () -> Unit, onOpen: (String) -> Unit, onNew: () -> Unit, model: ScheduledViewModel = viewModel()) {
|
||||
fun ScheduledScreen(onBack: () -> Unit, onOpen: (String) -> Unit, onNew: () -> Unit, onModels: () -> Unit, model: ScheduledViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LifecycleResumeEffect(Unit) {
|
||||
model.load()
|
||||
onPauseOrDispose { }
|
||||
onPauseOrDispose { model.stop() }
|
||||
}
|
||||
ScheduledContent(state, onBack = onBack, onOpen = onOpen, onNew = onNew, onPause = model::pause, onRetry = model::load)
|
||||
ScheduledContent(state, onBack = onBack, onOpen = onOpen, onNew = onNew, onModels = onModels, onPause = model::pause, onRetry = model::load)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -162,13 +199,20 @@ fun ScheduledContent(
|
||||
onBack: () -> Unit = {},
|
||||
onOpen: (String) -> Unit = {},
|
||||
onNew: () -> Unit = {},
|
||||
onModels: () -> Unit = {},
|
||||
onPause: (Schedule, Boolean) -> Unit = { _, _ -> },
|
||||
onRetry: () -> Unit = {},
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
topBar = { BackBar(stringResource(R.string.scheduled), onBack) },
|
||||
topBar = {
|
||||
BackBar(stringResource(R.string.scheduled), onBack) {
|
||||
if (!state.unsupported) {
|
||||
IconButton(onClick = onModels) { Icon(Icons.Filled.Tune, contentDescription = stringResource(R.string.schedule_models)) }
|
||||
}
|
||||
}
|
||||
},
|
||||
floatingActionButton = {
|
||||
if (!state.unsupported) {
|
||||
ExtendedFloatingActionButton(
|
||||
@@ -220,11 +264,12 @@ private fun ScheduleCard(schedule: Schedule, onOpen: () -> Unit, onPause: (Boole
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (schedule.rule.isNotBlank()) {
|
||||
Text(schedule.rule, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
schedule.description?.takeIf { it.isNotBlank() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 4.dp)) {
|
||||
schedule.lastRun?.let { StatusChip(it.status, it.missed) }
|
||||
val shown = if (schedule.running) "running" else schedule.lastRun?.status
|
||||
shown?.let { StatusChip(it, schedule.lastRun?.missed ?: 0) }
|
||||
val next = when {
|
||||
schedule.paused -> stringResource(R.string.schedule_paused)
|
||||
else -> ScheduleLogic.moment(schedule.nextRun)?.let { stringResource(R.string.schedule_next, it) }
|
||||
@@ -236,7 +281,7 @@ private fun ScheduleCard(schedule: Schedule, onOpen: () -> Unit, onPause: (Boole
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.padding(start = if (schedule.lastRun != null) 8.dp else 0.dp),
|
||||
modifier = Modifier.padding(start = if (shown != null) 8.dp else 0.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -275,7 +320,7 @@ private fun toneColours(palette: Palette, tone: Tone): Pair<Color, Color> = when
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BackBar(title: String, onBack: () -> Unit, actions: @Composable () -> Unit = {}) {
|
||||
internal fun BackBar(title: String, onBack: () -> Unit, actions: @Composable () -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
TopAppBar(
|
||||
colors = TopAppBarDefaults.topAppBarColors(containerColor = palette.bg, scrolledContainerColor = palette.bg),
|
||||
@@ -286,7 +331,7 @@ private fun BackBar(title: String, onBack: () -> Unit, actions: @Composable () -
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Message(text: String, retry: (() -> Unit)? = null) {
|
||||
internal fun Message(text: String, retry: (() -> Unit)? = null) {
|
||||
val palette = LocalPalette.current
|
||||
Column(
|
||||
Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(32.dp),
|
||||
@@ -341,9 +386,10 @@ class ScheduleViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
|
||||
fun runNow() = act { api, s ->
|
||||
api.runScheduleNow(s.id)
|
||||
_state.update { it.copy(notice = getApplication<Application>().getString(R.string.schedule_started)) }
|
||||
id?.let(::open)
|
||||
val run = api.runScheduleNow(s.id)
|
||||
_state.update { st ->
|
||||
st.copy(runs = listOf(run) + st.runs.filter { it.id != run.id }, notice = getApplication<Application>().getString(R.string.schedule_started))
|
||||
}
|
||||
}
|
||||
|
||||
fun pause(paused: Boolean) = act { api, s -> _state.update { it.copy(schedule = api.pauseSchedule(s.id, paused)) } }
|
||||
@@ -372,7 +418,7 @@ fun ScheduleScreen(
|
||||
id: String,
|
||||
onBack: () -> Unit,
|
||||
onEdit: (String) -> Unit,
|
||||
onOpenChat: (String) -> Unit,
|
||||
onOpenRun: (String) -> Unit,
|
||||
model: ScheduleViewModel = viewModel(key = "schedule-$id"),
|
||||
) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
@@ -395,15 +441,15 @@ fun ScheduleScreen(
|
||||
onDelete = { model.delete(onBack) },
|
||||
onRunNow = model::runNow,
|
||||
onPause = model::pause,
|
||||
onOpenRun = { run -> run.chatId?.let(onOpenChat) },
|
||||
onOpenRun = { run -> onOpenRun(run.id) },
|
||||
onMore = model::more,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* One schedule: what it does and when, Run now and Pause side by side (equal halves), the next
|
||||
* runs, and its history -- each run's status, when, the model that ran it and why, and Open for
|
||||
* its result.
|
||||
* runs, and its history -- each run's status, when, the model that ran it and why, the first
|
||||
* lines of its result; a run opens its result in full.
|
||||
*/
|
||||
@Composable
|
||||
fun ScheduleContent(
|
||||
@@ -477,11 +523,12 @@ private fun ScheduleBody(
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Schedule, contentDescription = null, tint = palette.accent, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(schedule.rule, style = MaterialTheme.typography.titleMedium, modifier = Modifier.weight(1f))
|
||||
Text(schedule.description.orEmpty(), style = MaterialTheme.typography.titleMedium, modifier = Modifier.weight(1f))
|
||||
}
|
||||
Text(schedule.instruction, style = MaterialTheme.typography.bodyMedium)
|
||||
val facts = listOfNotNull(
|
||||
schedule.model.ifBlank { null }?.let { stringResource(R.string.schedule_model, it) },
|
||||
schedule.model?.takeIf { it.isNotBlank() }?.let { stringResource(R.string.schedule_model, it) },
|
||||
modeWords(schedule.mode),
|
||||
notifyWords(schedule.notify),
|
||||
)
|
||||
if (facts.isNotEmpty()) {
|
||||
@@ -540,13 +587,20 @@ private fun ScheduleBody(
|
||||
@Composable
|
||||
private fun notifyWords(notify: String): String? = when (notify) {
|
||||
"always" -> stringResource(R.string.notify_always)
|
||||
"matters", "when_matters" -> stringResource(R.string.notify_matters)
|
||||
"matters" -> stringResource(R.string.notify_matters)
|
||||
"never" -> stringResource(R.string.notify_never)
|
||||
else -> null
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Header(text: String) {
|
||||
private fun modeWords(mode: String): String? = when (mode) {
|
||||
"fresh" -> stringResource(R.string.mode_fresh)
|
||||
"continue" -> stringResource(R.string.mode_continue)
|
||||
else -> null
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun Header(text: String) {
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
@@ -555,35 +609,62 @@ private fun Header(text: String) {
|
||||
)
|
||||
}
|
||||
|
||||
/** A run: its status (a fixed column, so the times line up), when, the model, and Open. */
|
||||
/**
|
||||
* A run: its status (a fixed column, so the times line up), when, the model, and the first
|
||||
* lines of its result (model output: plain text, never markup) or why it failed or waits. The
|
||||
* whole row opens the run.
|
||||
*/
|
||||
@Composable
|
||||
private fun RunRow(run: ScheduleRun, onOpen: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(shape = RoundedCornerShape(16.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Row(Modifier.heightIn(min = 64.dp).padding(start = 12.dp, end = 4.dp, top = 8.dp, bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Surface(
|
||||
onClick = onOpen,
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = palette.surfaceRaised,
|
||||
contentColor = palette.ink,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row(Modifier.heightIn(min = 64.dp).padding(horizontal = 12.dp, vertical = 10.dp), verticalAlignment = Alignment.Top) {
|
||||
Box(Modifier.width(112.dp)) { StatusChip(run.status, run.missed) }
|
||||
Column(Modifier.weight(1f)) {
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(ScheduleLogic.moment(run.startedAt ?: run.dueAt) ?: "—", style = MaterialTheme.typography.bodyMedium)
|
||||
val model = when {
|
||||
run.model.isBlank() -> null
|
||||
run.modelReason.startsWith("switched") -> stringResource(R.string.run_model_switched, run.model)
|
||||
else -> run.model
|
||||
}
|
||||
model?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) }
|
||||
if (run.error.isNotBlank()) {
|
||||
Text(run.error, style = MaterialTheme.typography.bodySmall, color = palette.danger, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
RunFacts(run, maxLines = 2)
|
||||
}
|
||||
if (run.chatId != null) TextButton(onClick = onOpen) { Text(stringResource(R.string.viewer_open)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Under a run's time: the model and why, then the result's first lines, or the trouble. */
|
||||
@Composable
|
||||
internal fun RunFacts(run: ScheduleRun, maxLines: Int = Int.MAX_VALUE, withPreview: Boolean = true) {
|
||||
val palette = LocalPalette.current
|
||||
val name = run.model.label
|
||||
val from = run.model.switchedFrom
|
||||
val model = when {
|
||||
name == null -> null
|
||||
run.model.reason == "switched" && from != null -> stringResource(R.string.run_model_instead, name, from)
|
||||
else -> name
|
||||
}
|
||||
model?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) }
|
||||
if (run.status == "waiting") {
|
||||
ScheduleLogic.moment(run.retryAt)?.let {
|
||||
Text(stringResource(R.string.run_retry_at, it), style = MaterialTheme.typography.bodySmall, color = palette.warning, maxLines = 1)
|
||||
}
|
||||
}
|
||||
run.error?.text?.takeIf { it.isNotBlank() }?.let {
|
||||
val tone = if (run.status == "waiting") palette.inkMuted else palette.danger
|
||||
Text(it, style = MaterialTheme.typography.bodySmall, color = tone, maxLines = maxLines, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
if (withPreview && run.preview.isNotBlank()) {
|
||||
Text(run.preview, style = MaterialTheme.typography.bodySmall, color = palette.ink, maxLines = maxLines, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Create and edit ------------------------------------------------------------------------
|
||||
|
||||
data class EditState(
|
||||
val words: String = "",
|
||||
val preview: SchedulePreview? = null,
|
||||
val compiled: ScheduleCompiled? = null,
|
||||
val compiling: Boolean = false,
|
||||
val saving: Boolean = false,
|
||||
val error: String? = null,
|
||||
@@ -596,7 +677,7 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private var editing: String? = null
|
||||
private var started = false
|
||||
|
||||
/** Begin: empty for a new schedule, the schedule's own words for one being edited. */
|
||||
/** Begin: empty for a new schedule, the words a schedule was made from for one being edited. */
|
||||
fun start(id: String?) {
|
||||
if (started) return
|
||||
started = true
|
||||
@@ -604,22 +685,22 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
|
||||
if (id == null) return
|
||||
viewModelScope.launch {
|
||||
runCatching { getApplication<Application>().api().schedule(id) }.onSuccess { s ->
|
||||
_state.update { it.copy(words = listOf(s.rule, s.instruction).filter { w -> w.isNotBlank() }.joinToString(": ")) }
|
||||
_state.update { it.copy(words = s.request.ifBlank { s.instruction }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun words(text: String) = _state.update { it.copy(words = text, preview = null) }
|
||||
fun words(text: String) = _state.update { it.copy(words = text, compiled = null) }
|
||||
|
||||
/** The server reads the words: the rule, the instruction and the next runs come back. */
|
||||
/** The server reads the words: the title, the instruction, the rule and the next runs. */
|
||||
fun preview() {
|
||||
val words = _state.value.words.trim()
|
||||
if (words.isEmpty()) return
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(compiling = true, error = null) }
|
||||
try {
|
||||
val preview = getApplication<Application>().api().compileSchedule(words)
|
||||
_state.update { it.copy(preview = preview, compiling = false) }
|
||||
val compiled = getApplication<Application>().api().compileSchedule(words)
|
||||
_state.update { it.copy(compiled = compiled, compiling = false) }
|
||||
} catch (e: Exception) {
|
||||
_state.update {
|
||||
it.copy(compiling = false, unsupported = e.unsupported(), error = if (e.unsupported()) null else getApplication<Application>().explain(e))
|
||||
@@ -629,11 +710,11 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
|
||||
fun save(then: (String) -> Unit) {
|
||||
val preview = _state.value.preview ?: return
|
||||
val compiled = _state.value.compiled?.takeIf { it.savable } ?: return
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(saving = true, error = null) }
|
||||
try {
|
||||
val saved = getApplication<Application>().api().saveSchedule(preview, editing)
|
||||
val saved = getApplication<Application>().api().saveSchedule(compiled, _state.value.words.trim(), editing)
|
||||
then(saved.id)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(saving = false, error = getApplication<Application>().explain(e)) }
|
||||
@@ -656,8 +737,9 @@ fun ScheduleEditScreen(
|
||||
|
||||
/**
|
||||
* A schedule in words: the person says when and what, the server reads it, and the preview
|
||||
* shows what it understood -- the rule in words, the instruction, the next five runs -- before
|
||||
* anything is saved. Save stays at the foot, out of the way of the keyboard.
|
||||
* shows what it understood -- the title, the rule in words, the instruction, the next five runs
|
||||
* -- before anything is saved. When it could not make out all of it, it says why, and Save
|
||||
* waits for words it can. Save stays at the foot, out of the way of the keyboard.
|
||||
*/
|
||||
@Composable
|
||||
fun ScheduleEditContent(
|
||||
@@ -676,7 +758,7 @@ fun ScheduleEditContent(
|
||||
Box(Modifier.background(palette.bg).navigationBarsPadding().imePadding().padding(16.dp)) {
|
||||
Button(
|
||||
onClick = onSave,
|
||||
enabled = state.preview != null && !state.saving,
|
||||
enabled = state.compiled?.savable == true && !state.saving,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
|
||||
) { Text(stringResource(R.string.save)) }
|
||||
}
|
||||
@@ -708,30 +790,38 @@ fun ScheduleEditContent(
|
||||
}
|
||||
if (state.unsupported) Text(stringResource(R.string.scheduled_unsupported), color = palette.inkMuted)
|
||||
state.error?.let { Text(it, color = palette.danger, style = MaterialTheme.typography.bodyMedium) }
|
||||
state.preview?.let { p ->
|
||||
Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(stringResource(R.string.schedule_understood), style = MaterialTheme.typography.labelLarge, color = palette.accent)
|
||||
if (p.title.isNotBlank()) Text(p.title, style = MaterialTheme.typography.titleMedium)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Schedule, contentDescription = null, tint = palette.inkMuted, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(p.ruleText, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f))
|
||||
}
|
||||
Text(p.instruction, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
val next = ScheduleLogic.upcoming(p.nextRuns)
|
||||
if (next.isNotEmpty()) {
|
||||
Text(
|
||||
stringResource(R.string.schedule_next_runs),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
modifier = Modifier.padding(top = 8.dp),
|
||||
)
|
||||
next.forEach { Text(it, style = MaterialTheme.typography.bodyMedium) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
state.compiled?.let { Understood(it) }
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What the server made of the words. The title and instruction are a model's: plain text. */
|
||||
@Composable
|
||||
private fun Understood(c: ScheduleCompiled) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(stringResource(R.string.schedule_understood), style = MaterialTheme.typography.labelLarge, color = palette.accent)
|
||||
c.reason?.takeIf { it.isNotBlank() }?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.warning) }
|
||||
if (c.title.isNotBlank()) Text(c.title, style = MaterialTheme.typography.titleMedium)
|
||||
c.description?.takeIf { it.isNotBlank() }?.let { words ->
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Schedule, contentDescription = null, tint = palette.inkMuted, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(words, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
if (c.instruction.isNotBlank()) Text(c.instruction, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
val next = ScheduleLogic.upcoming(c.nextRuns)
|
||||
if (next.isNotEmpty()) {
|
||||
Text(
|
||||
stringResource(R.string.schedule_next_runs),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
modifier = Modifier.padding(top = 8.dp),
|
||||
)
|
||||
next.forEach { Text(it, style = MaterialTheme.typography.bodyMedium) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package eu.llembas.android.ui.scheduled
|
||||
|
||||
import android.app.Application
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.CheckboxDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.SchedulingModel
|
||||
import eu.llembas.android.api.SchedulingModels
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
data class ModelsState(val models: SchedulingModels? = null, val loading: Boolean = false, val error: String? = null)
|
||||
|
||||
class SchedulingModelsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ModelsState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
private suspend fun api() = getApplication<Application>().lembas.instances.client() ?: throw ApiException(401, "Not signed in.")
|
||||
|
||||
fun load() {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val models = api().schedulingModels()
|
||||
_state.update { it.copy(models = models, loading = false) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Tick or untick one; the server keeps the person's narrowing and answers the whole list. */
|
||||
fun toggle(model: SchedulingModel) {
|
||||
val now = _state.value.models ?: return
|
||||
val chosen = SchedulingLogic.toggled(now.models, model.id) ?: return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val saved = api().chooseSchedulingModels(chosen)
|
||||
_state.update { it.copy(models = saved, error = null) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The narrowing a tick makes, pure so it can be tested. */
|
||||
object SchedulingLogic {
|
||||
/**
|
||||
* The ids to send after ticking or unticking [id]: in the list's order; empty when every
|
||||
* one is ticked (the server's "no narrowing"). Null when it would untick the last one --
|
||||
* scheduled work needs at least one model.
|
||||
*/
|
||||
fun toggled(models: List<SchedulingModel>, id: String): List<String>? {
|
||||
val chosen = models.filter { if (it.id == id) !it.chosen else it.chosen }.map { it.id }
|
||||
return when {
|
||||
chosen.isEmpty() -> null
|
||||
chosen.size == models.size -> emptyList()
|
||||
else -> chosen
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SchedulingModelsScreen(onBack: () -> Unit, model: SchedulingModelsViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LifecycleResumeEffect(Unit) {
|
||||
model.load()
|
||||
onPauseOrDispose { }
|
||||
}
|
||||
SchedulingModelsContent(state, onBack = onBack, onToggle = model::toggle, onRetry = model::load)
|
||||
}
|
||||
|
||||
/**
|
||||
* The models scheduled tasks run on, in the order they are tried -- each with whether it is free
|
||||
* now or busy (the server's words) -- and a tick for the person's own narrowing of the list.
|
||||
*/
|
||||
@Composable
|
||||
fun SchedulingModelsContent(state: ModelsState, onBack: () -> Unit = {}, onToggle: (SchedulingModel) -> Unit = {}, onRetry: () -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
val models = state.models?.models.orEmpty()
|
||||
Scaffold(containerColor = palette.bg, topBar = { BackBar(stringResource(R.string.schedule_models), onBack) }) { padding ->
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = onRetry, modifier = Modifier.fillMaxSize().padding(padding)) {
|
||||
if (models.isEmpty() && state.error != null) {
|
||||
Message(state.error, retry = onRetry)
|
||||
return@PullToRefreshBox
|
||||
}
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 32.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(R.string.schedule_models_hint),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(start = 4.dp, end = 4.dp, bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
state.error?.let { item { Text(it, color = palette.danger, style = MaterialTheme.typography.bodyMedium) } }
|
||||
items(models, key = { it.id }) { m -> ModelRow(m, onToggle = { onToggle(m) }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ModelRow(model: SchedulingModel, onToggle: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(
|
||||
onClick = onToggle,
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = palette.surfaceRaised,
|
||||
contentColor = palette.ink,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row(Modifier.heightIn(min = 64.dp).padding(start = 4.dp, end = 16.dp, top = 8.dp, bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Checkbox(
|
||||
checked = model.chosen,
|
||||
onCheckedChange = { onToggle() },
|
||||
colors = CheckboxDefaults.colors(checkedColor = palette.accent, checkmarkColor = palette.accentInk, uncheckedColor = palette.inkMuted),
|
||||
)
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(model.name.ifBlank { model.id }, style = MaterialTheme.typography.titleMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
val (line, tone) = if (model.free) {
|
||||
stringResource(R.string.model_free) to palette.success
|
||||
} else {
|
||||
stringResource(R.string.model_busy, model.busy.orEmpty()).trimEnd(' ', ':') to palette.inkMuted
|
||||
}
|
||||
Text(line, style = MaterialTheme.typography.bodySmall, color = tone, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user