Skip to content
Merged
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,7 @@ The **Zendr app for Android** shows every session on your computers, says which
- **When an agent asks a question** (allow this command? 1. Yes 2. No), its choices are buttons.
- **The key bar** has **Esc**, **Tab**, the arrows, **Enter** and **Ctrl+C**. Send with an empty box presses Enter.
- **At a shell prompt**, the same command suggestions as on your computer show as you type. Tap one, or press → or Tab on a keyboard.
- **The bell** at the top keeps a list of what happened: agents that needed you or finished, and new versions. A dot marks the ones you haven't seen. Tap one to open that session, swipe it away to remove it.
- **Light or dark**: the moon and sun at the top left switch it, and **About** (ⓘ) can also follow your phone's setting.
- **New versions** pop up by themselves with what's new and a **Download** button. **About** shows your version, checks for updates and links to the source, the releases and the issue tracker.

Expand Down
10 changes: 10 additions & 0 deletions mobile/android/app/src/main/java/dev/zendr/companion/Api.kt
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,16 @@ class Store(context: Context) {
get() = prefs.getLong("updateCheckedAt", 0L)
set(v) = prefs.edit().putLong("updateCheckedAt", v).apply()

/** The notifications list, newest first (see [Feed]). */
var notesJson: String
get() = prefs.getString("notes", null) ?: "[]"
set(v) = prefs.edit().putString("notes", v).apply()

/** The newest version already in the notifications list. */
var notedVersion: String?
get() = prefs.getString("notedVersion", null)
set(v) = prefs.edit().putString("notedVersion", v).apply()

/** A version you chose to skip: no popup for it. */
var skipVersion: String?
get() = prefs.getString("skipVersion", null)
Expand Down
124 changes: 124 additions & 0 deletions mobile/android/app/src/main/java/dev/zendr/companion/Feed.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package dev.zendr.companion

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.setValue
import org.json.JSONArray
import org.json.JSONObject

/**
* One thing that happened: an agent started needing you ("blocked"), one finished ("done"), or a
* new version of the app came out ("update").
*/
data class Note(
val id: Long,
val at: Long,
val kind: String,
val title: String,
val text: String,
val computer: String? = null,
val terminal: String? = null,
val app: String? = null,
/** The session's own name, for opening it. */
val session: String? = null,
val read: Boolean = false,
) {
fun toJson(): JSONObject = JSONObject()
.put("id", id).put("at", at).put("kind", kind).put("title", title).put("text", text)
.put("computer", computer).put("terminal", terminal).put("app", app).put("session", session).put("read", read)

companion object {
fun fromJson(j: JSONObject) = Note(
id = j.optLong("id"),
at = j.optLong("at"),
kind = j.optString("kind"),
title = j.optString("title"),
text = j.optString("text"),
computer = j.optString("computer").takeIf { it.isNotEmpty() && it != "null" },
terminal = j.optString("terminal").takeIf { it.isNotEmpty() && it != "null" },
app = j.optString("app").takeIf { it.isNotEmpty() && it != "null" },
session = j.optString("session").takeIf { it.isNotEmpty() && it != "null" },
read = j.optBoolean("read"),
)
}
}

/**
* The notifications list: everything the app saw happen, whether it saw it in the open app or in
* Alert me's watch. Kept on the phone, newest first, the last [MOST].
*/
object Feed {
const val MOST = 100

/** Bumps whenever the list changes, so the bell and the list redraw. */
var version by mutableIntStateOf(0)
private set

// computer id + terminal -> the status last seen, shared by the app's screens and the watch,
// so one change is noted once.
private val last = HashMap<String, String?>()
private val known = HashSet<String>()

/** What a change of status is worth noting as, if anything. */
fun change(before: String?, now: String?): String? = when {
before == now -> null
now == "blocked" -> "blocked"
now == "done" && before == "working" -> "done"
else -> null
}

/** Notes what changed on [c] since it was last looked at (the first look only learns). */
@Synchronized
fun observe(store: Store, c: Computer, spaces: List<Space>) {
val first = known.add(c.id)
val now = System.currentTimeMillis()
val fresh = mutableListOf<Note>()
for (s in spaces.flatMap { it.sessions }) {
val key = "${c.id}/${s.terminal}"
val before = last[key]
last[key] = s.status
if (first) continue
when (change(before, s.status)) {
"blocked" -> fresh += Note(now + fresh.size, now, "blocked", "${s.title} needs you", "On ${c.name}", c.id, s.terminal, s.app, s.title)
"done" -> fresh += Note(now + fresh.size, now, "done", "${s.title} finished", "On ${c.name}", c.id, s.terminal, s.app, s.title)
}
}
if (fresh.isNotEmpty()) save(store, fresh + list(store))
}

/** A new version, noted once. */
@Synchronized
fun noteUpdate(store: Store, r: Release) {
if (store.notedVersion == r.version) return
store.notedVersion = r.version
val now = System.currentTimeMillis()
val text = Updates.summary(r.notes).lineSequence().firstOrNull { it.isNotBlank() } ?: "Tap to see what's new."
save(store, listOf(Note(now, now, "update", "Zendr ${r.version} is out", text)) + list(store))
}

fun list(store: Store): List<Note> = parse(store.notesJson)

fun unread(store: Store) = list(store).count { !it.read }

@Synchronized
fun markRead(store: Store, id: Long? = null) =
save(store, list(store).map { if (id == null || it.id == id) it.copy(read = true) else it })

@Synchronized
fun remove(store: Store, id: Long) = save(store, list(store).filterNot { it.id == id })

@Synchronized
fun clear(store: Store) = save(store, emptyList())

fun parse(raw: String): List<Note> = runCatching {
val a = JSONArray(raw)
(0 until a.length()).map { Note.fromJson(a.getJSONObject(it)) }
}.getOrDefault(emptyList())

fun encode(notes: List<Note>): String = JSONArray(notes.take(MOST).map { it.toJson() }).toString()

private fun save(store: Store, notes: List<Note>) {
store.notesJson = encode(notes)
version++
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,13 @@ sealed class Screen {
val status: String? = null,
) : Screen()
data class About(val from: Screen) : Screen()
data class Notifications(val from: Screen) : Screen()
}

class MainActivity : ComponentActivity() {
private var screen by mutableStateOf<Screen>(Screen.Home)
private var pendingLink by mutableStateOf<String?>(null)
private var pendingUpdate by mutableStateOf(false)

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Expand Down Expand Up @@ -128,6 +130,7 @@ class MainActivity : ComponentActivity() {
private fun handle(intent: Intent?) {
intent ?: return
intent.data?.toString()?.takeIf { it.startsWith("zendr://") }?.let { pendingLink = it; screen = Screen.Pair }
if (intent.getBooleanExtra(EXTRA_UPDATE, false)) pendingUpdate = true
val c = intent.getStringExtra(EXTRA_COMPUTER)
val t = intent.getStringExtra(EXTRA_TERMINAL)
if (c != null && t != null) {
Expand All @@ -139,15 +142,16 @@ class MainActivity : ComponentActivity() {
private fun App() {
val store = remember { Store(this) }
val about = { screen = Screen.About(screen) }
val bell = { screen = Screen.Notifications(screen) }
when (val s = screen) {
Screen.Home -> HomeScreen(store, onOpen = { screen = Screen.Sessions(it.id) }, onAdd = { screen = Screen.Pair }, onAbout = about)
Screen.Home -> HomeScreen(store, onOpen = { screen = Screen.Sessions(it.id) }, onAdd = { screen = Screen.Pair }, onAbout = about, onBell = bell)
Screen.Pair -> {
BackHandler { screen = Screen.Home }
PairScreen(store, pendingLink, onDone = { pendingLink = null; screen = if (it != null) Screen.Sessions(it.id) else Screen.Home })
}
is Screen.Sessions -> {
BackHandler { screen = Screen.Home }
SessionsScreen(store, s.computer, onBack = { screen = Screen.Home }, onAbout = about, onOpen = {
SessionsScreen(store, s.computer, onBack = { screen = Screen.Home }, onAbout = about, onBell = bell, onOpen = {
screen = Screen.Terminal(s.computer, it.terminal, it.title, it.app, it.status)
})
}
Expand All @@ -159,6 +163,25 @@ class MainActivity : ComponentActivity() {
BackHandler { screen = s.from }
AboutScreen(store, onBack = { screen = s.from })
}
is Screen.Notifications -> {
BackHandler { screen = s.from }
NotificationsScreen(store, onBack = { screen = s.from }, onOpen = { n ->
val c = store.computers().firstOrNull { it.id == n.computer }
when {
n.kind == "update" -> Updates.latest?.let { Updates.offer = it } ?: run { pendingUpdate = true }
c != null && n.terminal != null -> screen = Screen.Terminal(c.id, n.terminal, n.session ?: "Session", n.app)
c != null -> screen = Screen.Sessions(c.id)
}
})
}
}

// From the "new version" notification: look now, and offer it.
LaunchedEffect(pendingUpdate) {
if (pendingUpdate) {
pendingUpdate = false
Updates.check(this@MainActivity, store, manual = true)
}
}

// A new version: offered in a popup when the app opens, and every few hours while it's open.
Expand Down Expand Up @@ -186,6 +209,7 @@ class MainActivity : ComponentActivity() {
const val EXTRA_TITLE = "title"
const val EXTRA_APP = "app"
const val EXTRA_STATUS = "status"
const val EXTRA_UPDATE = "update"

// What enableEdgeToEdge() puts behind three-button navigation.
private val LIGHT_SCRIM = android.graphics.Color.argb(0xe6, 0xFF, 0xFF, 0xFF)
Expand All @@ -210,7 +234,7 @@ private fun summarize(spaces: List<Space>): String {

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(store: Store, onOpen: (Computer) -> Unit, onAdd: () -> Unit, onAbout: () -> Unit) {
fun HomeScreen(store: Store, onOpen: (Computer) -> Unit, onAdd: () -> Unit, onAbout: () -> Unit, onBell: () -> Unit) {
val context = LocalContext.current
var computers by remember { mutableStateOf(store.computers()) }
var summary by remember { mutableStateOf<Map<String, Pair<String, Boolean>>>(emptyMap()) }
Expand All @@ -223,7 +247,8 @@ fun HomeScreen(store: Store, onOpen: (Computer) -> Unit, onAdd: () -> Unit, onAb
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
while (true) {
summary = computers.associate { c ->
c.id to runCatching { summarize(Api.state(store, c)) to true }.getOrElse { "Offline: ${it.message}" to false }
c.id to runCatching { Api.state(store, c).also { Feed.observe(store, c, it) }.let(::summarize) to true }
.getOrElse { "Offline: ${it.message}" to false }
}
delay(5000)
}
Expand All @@ -234,7 +259,10 @@ fun HomeScreen(store: Store, onOpen: (Computer) -> Unit, onAdd: () -> Unit, onAb
topBar = {
ZendrTopBar(
navigationIcon = { ThemeButton(store) },
actions = { IconButton(onClick = onAbout) { Icon(Icons.Default.Info, "About") } },
actions = {
BellButton(store, onBell)
IconButton(onClick = onAbout) { Icon(Icons.Default.Info, "About") }
},
)
},
floatingActionButton = {
Expand Down Expand Up @@ -393,7 +421,7 @@ private enum class Filter(val label: String) { All("All"), Need("Needs you"), Wo

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SessionsScreen(store: Store, computerId: String, onBack: () -> Unit, onAbout: () -> Unit, onOpen: (Session) -> Unit) {
fun SessionsScreen(store: Store, computerId: String, onBack: () -> Unit, onAbout: () -> Unit, onBell: () -> Unit, onOpen: (Session) -> Unit) {
val scope = rememberCoroutineScope()
val computer = store.computers().firstOrNull { it.id == computerId }
var spaces by remember { mutableStateOf<List<Space>?>(null) }
Expand All @@ -406,7 +434,7 @@ fun SessionsScreen(store: Store, computerId: String, onBack: () -> Unit, onAbout
suspend fun load() {
val c = store.computers().firstOrNull { it.id == computerId } ?: return
runCatching { Api.state(store, c) }
.onSuccess { spaces = it; error = null }
.onSuccess { spaces = it; error = null; Feed.observe(store, c, it) }
.onFailure { error = it.message }
}

Expand Down Expand Up @@ -436,7 +464,10 @@ fun SessionsScreen(store: Store, computerId: String, onBack: () -> Unit, onAbout
Scaffold(topBar = {
ZendrTopBar(
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } },
actions = { IconButton(onClick = onAbout) { Icon(Icons.Default.Info, "About") } },
actions = {
BellButton(store, onBell)
IconButton(onClick = onAbout) { Icon(Icons.Default.Info, "About") }
},
)
}) { pad ->
PullToRefreshBox(
Expand Down
Loading
Loading