Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat(android): bring chat, composer, settings, notifications and widgets to iPhone parity (#154)

leepokai1b96899301be
diff --git a/.githooks/pre-commit b/.githooks/pre-commit
index 367f8be4..780ee1fd 100755
--- a/.githooks/pre-commit
+++ b/.githooks/pre-commit
@@ -68,9 +68,9 @@ if touches '^apps/(android/|project\.yml)'; then
jdk=$( (/usr/libexec/java_home -v 21 2>/dev/null) || printf '%s' "${JAVA_HOME:-}")
if [ -n "$jdk" ]; then
staged_copy
- echo "Checking the Android app (unit tests, compile)..."
+ echo "Checking the Android app (unit tests, compile, instrumentation tests compile)..."
(cd "$snapshot/apps/android" && JAVA_HOME="$jdk" ./gradlew --console=plain -q --build-cache \
- :core:test :app:testDebugUnitTest :app:compileDebugKotlin)
+ :core:test :app:testDebugUnitTest :app:compileDebugKotlin :app:compileDebugAndroidTestKotlin)
else
echo "Skipping the Android checks (needs JDK 21)."
fi
diff --git a/apps/android/README.md b/apps/android/README.md
index afddf46b..408e6c00 100644
--- a/apps/android/README.md
+++ b/apps/android/README.md
@@ -78,8 +78,7 @@ conversation.
Text and private attachment drafts survive process death separately for each bot
and thread. Sends retain their nonce through durable queue commit and retry.
Uncertain sends require explicit retry with the same ID. Text can wait in the
-encrypted relay mailbox; files require a live computer and are unavailable in
-groups. Files are capped at 100 MiB each and uploaded in 384 KiB chunks. Sharing
+encrypted relay mailbox; files require a live computer. Files are capped at 100 MiB each and uploaded in 384 KiB chunks. Sharing
uses a temporary copy rather than exposing the private cache.
## Ownership and storage
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/AlertNotificationTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/AlertNotificationTest.kt
new file mode 100644
index 00000000..e3b1fec5
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/AlertNotificationTest.kt
@@ -0,0 +1,100 @@
+package com.codync.android
+
+import android.Manifest
+import android.accessibilityservice.AccessibilityService
+import android.app.Notification
+import android.app.NotificationManager
+import android.content.pm.PackageManager
+import android.graphics.Bitmap
+import android.os.Build
+import android.os.SystemClock
+import androidx.core.app.NotificationCompat
+import androidx.core.content.pm.ShortcutManagerCompat
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.PushAlert
+import org.junit.After
+import org.junit.Assert.*
+import org.junit.Before
+import org.junit.Test
+import java.io.File
+import java.util.UUID
+
+/** Alerts as the push service shows them once their sealed text is open; never touches the saved account. */
+class AlertNotificationTest {
+ private val instrumentation = InstrumentationRegistry.getInstrumentation()
+ private val context = instrumentation.targetContext
+ private val manager = context.getSystemService(NotificationManager::class.java)
+ private val scope = "alert-test-${UUID.randomUUID()}"
+ private val computer = "computer"
+ private val posted = mutableListOf<String>()
+
+ private fun face(id: String, name: String, shape: String, color: String, kind: String = "agent", members: List<String> = emptyList()) =
+ """{"id":"$id","kind":"$kind","members":${members.joinToString(",", "[", "]") { "\"$it\"" }},"name":"$name","avatarColor":"$color","avatarShape":"$shape"}"""
+
+ private fun show(bot: String, alert: String): Notification {
+ val tag = "$scope/$computer/$bot"
+ posted += tag
+ NotificationDisplay.alert(context, scope, computer, bot, PushAlert.decode(alert))
+ val deadline = SystemClock.elapsedRealtime() + 3000
+ while (manager.activeNotifications.none { it.tag == tag } && SystemClock.elapsedRealtime() < deadline) SystemClock.sleep(10)
+ return manager.activeNotifications.single { it.tag == tag }.notification
+ }
+
+ @Before fun allowNotifications() {
+ if (Build.VERSION.SDK_INT >= 33 && context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED)
+ instrumentation.uiAutomation.grantRuntimePermission(context.packageName, Manifest.permission.POST_NOTIFICATIONS)
+ }
+
+ @After fun clear() {
+ posted.forEach { manager.cancel(it, 1) }
+ ShortcutManagerCompat.removeLongLivedShortcuts(context, posted)
+ }
+
+ @Test fun aBotsAlertIsAConversationFromTheBotSayingWhatHappened() {
+ val notification = show("reviewer", """{"title":"Reviewer needs you","subtitle":"Response needed","body":"Run cargo test --all?",
+ "faces":[${face("reviewer", "Reviewer", "hex", "green")}]}""")
+ assertEquals("Response needed", notification.extras.getCharSequence(Notification.EXTRA_SUB_TEXT))
+ assertEquals("$scope/$computer/reviewer", notification.shortcutId)
+ val style = requireNotNull(NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(notification))
+ assertFalse(style.isGroupConversation)
+ val message = style.messages.single()
+ assertEquals("Reviewer", message.person?.name)
+ assertEquals("Run cargo test --all?", message.text)
+ assertNotNull(message.person?.icon)
+ assertTrue(ShortcutManagerCompat.getDynamicShortcuts(context).any { it.id == "$scope/$computer/reviewer" })
+ snapshot("bot")
+ }
+
+ @Test fun aGroupsAlertNamesTheGroupAndTheMemberSpeaking() {
+ val notification = show("crew", """{"title":"Builder in Crew","subtitle":"Task complete","body":"The release build passed.","from":"builder",
+ "faces":[${face("crew", "Crew", "blob", "gray", "group", listOf("reviewer", "builder"))},
+ ${face("reviewer", "Reviewer", "hex", "green")},${face("builder", "Builder", "squircle", "orange")}]}""")
+ val style = requireNotNull(NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(notification))
+ assertTrue(style.isGroupConversation)
+ assertEquals("Crew", style.conversationTitle)
+ assertEquals("Builder", style.messages.single().person?.name)
+ assertEquals("Task complete", notification.extras.getCharSequence(Notification.EXTRA_SUB_TEXT))
+ snapshot("group")
+ }
+
+ @Test fun anAlertWithoutItsChatsFaceStaysPlain() {
+ val notification = show("unknown", """{"title":"Docs","subtitle":"Task failed","body":"The docs build stopped."}""")
+ assertNull(NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(notification))
+ assertEquals("Docs", notification.extras.getCharSequence(Notification.EXTRA_TITLE))
+ assertEquals("Task failed", notification.extras.getCharSequence(Notification.EXTRA_SUB_TEXT))
+ assertNull(notification.shortcutId)
+ snapshot("plain")
+ }
+
+ /** `-e notificationSnapshots true`: the shade with the alert, saved in the app's cache. */
+ private fun snapshot(name: String) {
+ if (InstrumentationRegistry.getArguments().getString("notificationSnapshots") != "true") return
+ val automation = instrumentation.uiAutomation
+ automation.performGlobalAction(AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS)
+ SystemClock.sleep(3000)
+ val shot = requireNotNull(automation.takeScreenshot())
+ File(context.cacheDir, "notification-$name.png").outputStream().use { shot.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ if (Build.VERSION.SDK_INT >= 31) automation.performGlobalAction(AccessibilityService.GLOBAL_ACTION_DISMISS_NOTIFICATION_SHADE)
+ SystemClock.sleep(500)
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionUiTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionUiTest.kt
index 043c45ae..cb332c10 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionUiTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionUiTest.kt
@@ -18,10 +18,10 @@ class ConnectionUiTest {
@Test fun theComputerRowNamesTheActualConnectionState() {
val state = mutableStateOf(fixture(LinkState.Failed("Your access was revoked.", 403)))
compose.setContent { Hosted { SettingsView(state.value, viewModel(), null, {}, {}, {}) } }
- compose.onNodeWithText("Access denied").assertIsDisplayed()
+ compose.onNodeWithText("Your access was revoked.").assertIsDisplayed()
compose.onNodeWithContentDescription("Extensions").assertDoesNotExist()
compose.runOnUiThread { state.value = fixture(LinkState.ComputerOffline(null)) }
- compose.onNodeWithText("Computer offline").assertIsDisplayed()
+ compose.onNodeWithText("Offline").assertIsDisplayed()
compose.runOnUiThread { state.value = fixture(LinkState.Ready(HostRoute.Direct)).copy(bots = listOf(Bot("bot", "Saved bot"))) }
compose.onNodeWithText("1 bot · Wi-Fi/Tailscale").assertIsDisplayed()
compose.onNodeWithContentDescription("Extensions").assertIsDisplayed()
@@ -32,7 +32,7 @@ class ConnectionUiTest {
var created = false
compose.setContent { Hosted { BotListView(state.value, viewModel(), {}, {}, { created = true }, {}, {}, 0.dp) } }
compose.onNodeWithText("Saved bot").assertIsDisplayed()
- compose.onNodeWithText("Offline").assertIsDisplayed()
+ compose.onNodeWithText("1 offline").assertIsDisplayed()
compose.onNodeWithText("No bots yet").assertDoesNotExist()
compose.runOnUiThread { state.value = fixture(LinkState.Ready(HostRoute.Direct)) }
compose.onNodeWithText("1 connected").assertIsDisplayed()
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.kt
index bfe0af5d..0c1dbfe6 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.kt
@@ -22,7 +22,7 @@ class UsageScreenTest {
val refreshes = mutableListOf<Boolean>()
var closed = false
compose.setContent { Hosted { CompositionLocalProvider(LocalDismissModal provides { closed = true }) {
- UsageScreen(state.value) { refreshes.add(it) }
+ UsageScreen(state.value, { refreshes.add(it) }, { refreshes.add(true) })
} } }
compose.onNodeWithText("Future provider").assertIsDisplayed()
compose.onNodeWithText("Monthly").assertIsDisplayed()
@@ -45,7 +45,7 @@ class UsageScreenTest {
@Test fun usageExplainsWhenThereIsNoComputerOrNoReportYet() {
val state = mutableStateOf(AppState(loading = false))
- compose.setContent { Hosted { UsageScreen(state.value) {} } }
+ compose.setContent { Hosted { UsageScreen(state.value, {}, {}) } }
compose.onNodeWithText("No computer yet").assertIsDisplayed()
compose.onNodeWithText("Usage shows up once a computer is connected.").assertIsDisplayed()
compose.runOnUiThread { state.value = state.value.copy(computers = listOf(Computer("fixture", "Acceptance computer", "fixture"))) }
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetSystemTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetSystemTest.kt
index 900aa84a..30d4d153 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetSystemTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetSystemTest.kt
@@ -131,7 +131,7 @@ class WidgetSystemTest {
assertTrue(feed.botsAt > System.currentTimeMillis() - 30_000)
val link = requireNotNull(widgetIntent(context, feed, usage = true).data)
compose.runOnUiThread { store.openLink(link) }
- compose.waitUntil(10_000) { store.state.value.navigationUsage && store.state.value.selectedBot == null }
+ compose.waitUntil(10_000) { store.state.value.navigationPage == LinkPage.Usage && store.state.value.selectedBot == null }
// The usage sheet's title (it refreshes on its own and on pull).
val refresh = hasText("Usage") and isHeading()
compose.waitUntil(10_000) { compose.onAllNodes(refresh).fetchSemanticsNodes().size == 1 }
diff --git a/apps/android/app/src/main/AndroidManifest.xml b/apps/android/app/src/main/AndroidManifest.xml
index 70aa32ea..89cec805 100644
--- a/apps/android/app/src/main/AndroidManifest.xml
+++ b/apps/android/app/src/main/AndroidManifest.xml
@@ -49,6 +49,14 @@
<intent-filter><action android:name="android.appwidget.action.APPWIDGET_UPDATE" /></intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_provider" />
</receiver>
+ <receiver android:name=".UsageWidgetReceiver" android:exported="true" android:label="Usage limits">
+ <intent-filter><action android:name="android.appwidget.action.APPWIDGET_UPDATE" /></intent-filter>
+ <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_usage" />
+ </receiver>
+ <service android:name=".LeadBotTile" android:exported="true" android:label="Bots"
+ android:icon="@drawable/sf_ellipsis_bubble_fill" android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
+ <intent-filter><action android:name="android.service.quicksettings.action.QS_TILE" /></intent-filter>
+ </service>
<activity android:name=".WidgetConfigurationActivity" android:exported="true">
<intent-filter><action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" /></intent-filter>
</activity>
@@ -91,6 +99,13 @@
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="${urlScheme}" android:host="screen" />
</intent-filter>
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <data android:scheme="${urlScheme}" android:host="computers" />
+ <data android:scheme="${urlScheme}" android:host="plugins" />
+ </intent-filter>
</activity>
</application>
</manifest>
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AlertNotification.kt b/apps/android/app/src/main/kotlin/com/codync/android/AlertNotification.kt
new file mode 100644
index 00000000..c1b8c595
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AlertNotification.kt
@@ -0,0 +1,88 @@
+package com.codync.android
+
+import android.content.Context
+import android.content.Intent
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Paint
+import androidx.core.app.NotificationCompat
+import androidx.core.app.Person
+import androidx.core.content.ContextCompat
+import androidx.core.content.pm.ShortcutInfoCompat
+import androidx.core.content.pm.ShortcutManagerCompat
+import androidx.core.graphics.drawable.IconCompat
+import com.codync.android.core.AlertConversation
+import com.codync.android.core.Bot
+import com.codync.android.design.characterAvatarBitmap
+import com.codync.android.design.symbolRes
+
+/**
+ * A bot's alert as a conversation (iOS `NotificationService.fromBot`): the bot's face and name in
+ * place of the app icon, kept in the conversation section by a long-lived shortcut; in a group,
+ * the group's face with the member speaking as the sender.
+ */
+internal object AlertConversations {
+ /** [id] names the conversation: the alert's notification tag, one per account, computer and chat. */
+ fun style(context: Context, builder: NotificationCompat.Builder, id: String, computer: String, open: Intent, body: String,
+ conversation: AlertConversation) {
+ val chat = conversation.chat
+ val chatFace = IconCompat.createWithBitmap(notificationFace(context, chat, conversation.members))
+ val speaker = conversation.speaker
+ val sender = if (speaker == null) person(computer, chat, chatFace)
+ else person(computer, speaker, IconCompat.createWithBitmap(notificationFace(context, speaker, emptyList())))
+ val style = NotificationCompat.MessagingStyle(Person.Builder().setName("You").setKey("me").build())
+ .addMessage(body, System.currentTimeMillis(), sender)
+ if (speaker != null) style.setConversationTitle(chat.name).setGroupConversation(true)
+ val shortcut = ShortcutInfoCompat.Builder(context, id).setShortLabel(chat.name.ifBlank { context.getString(R.string.app_name) })
+ .setIcon(chatFace).setIntent(open).setLongLived(true).setIsConversation()
+ .apply { if (speaker == null) setPerson(sender) }.build()
+ ShortcutManagerCompat.pushDynamicShortcut(context, shortcut)
+ builder.setStyle(style).setShortcutInfo(shortcut)
+ }
+
+ /** An account's conversations leave with it: bot names and faces never outlive the account on this phone. */
+ fun forget(context: Context) {
+ val kept = ShortcutManagerCompat.getShortcuts(context, ShortcutManagerCompat.FLAG_MATCH_DYNAMIC or ShortcutManagerCompat.FLAG_MATCH_CACHED)
+ ShortcutManagerCompat.removeLongLivedShortcuts(context, kept.map { it.id })
+ }
+
+ private fun person(computer: String, bot: Bot, face: IconCompat) =
+ Person.Builder().setKey("$computer/${bot.id}").setName(bot.name).setIcon(face).build()
+}
+
+// iOS draws the alert face at 88 pt with 20 pt around it on the dark background, at 2x.
+private const val FACE_CANVAS = 256
+private const val FACE = FACE_CANVAS * 88 / 128
+private const val DARK_GROUND = 0xFF0A0A0A.toInt()
+private const val DARK_INK = 0xFFF2F2F2.toInt()
+private const val DARK_SECONDARY = 0xFF9A9A9A.toInt()
+
+/** The bot's face, or a group's members' faces, on a dark disc like iOS's alert avatars (iOS `GroupAvatar` layouts). */
+internal fun notificationFace(context: Context, bot: Bot, members: List<Bot>): Bitmap {
+ val bitmap = Bitmap.createBitmap(FACE_CANVAS, FACE_CANVAS, Bitmap.Config.ARGB_8888)
+ val canvas = Canvas(bitmap).apply {
+ drawCircle(FACE_CANVAS / 2f, FACE_CANVAS / 2f, FACE_CANVAS / 2f, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = DARK_GROUND })
+ }
+ val start = (FACE_CANVAS - FACE) / 2f
+ val end = start + FACE
+ fun place(member: Bot, fraction: Float, x: Float, y: Float) {
+ val pixels = (FACE * fraction).toInt()
+ canvas.drawBitmap(characterAvatarBitmap(member.avatarShape, member.avatarColor, pixels, DARK_INK, cells = 13), x, y, null)
+ }
+ if (bot.kind != "group") { place(bot, 1f, start, start); return bitmap }
+ // An alert carries at most three members' faces: the first two and the speaker.
+ when (members.size) {
+ 0 -> ContextCompat.getDrawable(context, requireNotNull(symbolRes("person.2")))?.mutate()?.run {
+ val side = (FACE * 0.4f).toInt()
+ val inset = ((FACE_CANVAS - side) / 2f).toInt()
+ setBounds(inset, inset, inset + side, inset + side); setTint(DARK_SECONDARY); draw(canvas)
+ }
+ 1 -> place(members[0], 1f, start, start)
+ 2 -> { place(members[1], .66f, end - FACE * .66f, start); place(members[0], .66f, start, end - FACE * .66f) }
+ else -> {
+ place(members[0], .55f, start + FACE * (1 - .55f) / 2, start)
+ place(members[1], .55f, start, end - FACE * .55f); place(members[2], .55f, end - FACE * .55f, end - FACE * .55f)
+ }
+ }
+ return bitmap
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt
index cf5236f0..209cc3d2 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt
@@ -5,6 +5,9 @@ import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.longOrNull
+/** Where a link lands once everything open is closed: the roster, or a sheet over it. */
+enum class LinkPage { Bots, Usage, Computers, Extensions }
+
/** Everything the UI renders for the active account and its computer; `AppStore` owns the only writer. */
data class AppState(
val contextId: String = "local",
@@ -25,13 +28,15 @@ data class AppState(
val pending: List<PendingSend> = emptyList(),
val drafts: Map<String, ComposerDraft> = emptyMap(),
val uploadProgress: Map<String, Int> = emptyMap(),
+ /** Files bots shared that this phone is downloading, has downloaded or couldn't, by file ID. */
+ val fileDownloads: Map<String, FileDownloadState> = emptyMap(),
val usage: JsonObject = JsonObject(emptyMap()),
val hello: JsonObject? = null,
val connection: LinkState = LinkState.Connecting,
val actualConnection: LinkState = LinkState.Connecting,
val selectedBot: String? = null,
val navigationRequest: Int = 0,
- val navigationUsage: Boolean = false,
+ val navigationPage: LinkPage = LinkPage.Bots,
val thread: String? = null,
val trace: Boolean = false,
val busy: Set<String> = emptySet(),
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt
index 42d6c0fe..1f253034 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt
@@ -39,11 +39,16 @@ fun AppStore.refreshCloud() = action("cloud") {
client.registerDevice(Build.MODEL.take(100))
val computers = client.computers()
mutableState.update { it.copy(cloudComputers = computers) }
- val target = computers.firstOrNull { remote -> state.value.computers.isEmpty() && remote.computerId !in asked }
+ // Online computers this phone has no grant on yet; a granted one needs Revoke before asking again.
+ val target = computers.firstOrNull { remote -> state.value.computers.isEmpty() && remote.online == true &&
+ remote.access != "granted" && remote.computerId !in asked }
if (target != null) requestAccess(target)
} catch (error: CloudError) { if (!error.isTransient) throw error }
}
+/** A pull to refresh: the account's computers, joining a refresh already under way. */
+suspend fun AppStore.refreshComputers() { refreshCloud(); actions["cloud"]?.join() }
+
fun AppStore.requestAccess(target: CloudComputer) = action("access") {
val client = requireNotNull(cloud) { "Sign in to reach your account." }
require(state.value.computers.isEmpty() || state.value.computers.first().id == target.computerId) { "Forget the current computer before connecting a different one." }
@@ -84,6 +89,29 @@ fun AppStore.cancelAccess() {
}
}
+/**
+ * Takes back this phone's account access to a computer (its grants) and forgets the computer here.
+ * Also the way out when an earlier install was approved but this one never checked the code.
+ */
+fun AppStore.revokeAccess(computerId: String) = action("revoke") {
+ requireNotNull(cloud) { "Sign in to reach your account." }.revokeAccess(computerId)
+ if (state.value.computers.firstOrNull()?.id == computerId) forgetComputer() else refreshCloud()
+}
+
+/** Takes an older copy of a computer out of the account (its grants and pending requests go with it). */
+fun AppStore.removeFromAccount(computerId: String) = action("removeFromAccount") {
+ requireNotNull(cloud) { "Sign in to reach your account." }.removeComputer(computerId)
+ refreshCloud()
+}
+
+/** The computer's badge color, picked on this phone (an `AvatarPalette` id). */
+fun AppStore.setColor(color: String) = action("color") {
+ val computer = state.value.computers.firstOrNull() ?: return@action
+ val changed = computer.copy(color = color)
+ withContext(Dispatchers.IO) { local.saveComputers(listOf(changed)) }
+ mutableState.update { it.copy(computers = listOf(changed)) }
+}
+
fun AppStore.forgetComputer() = sessionAction {
transitions.withLock {
val userId = state.value.account.userId
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt
index 3c9bbafb..37e7f3c6 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt
@@ -90,6 +90,8 @@ suspend fun AppStore.agentModels(backend: String): AgentModels {
val response = hostQuery("agentModels", body("backend" to backend), timeoutMillis = 300_000)
return WireJson.decodeFromJsonElement(response)
}
+/** A forced usage read that returns when it's done, for pull to refresh. */
+suspend fun AppStore.reloadUsage() { refreshUsage(true); actions["usage"]?.join() }
fun AppStore.refreshUsage(force: Boolean = true) = action("usage") {
val active = ready()
// The existing host can spend up to a minute reading an installed provider.
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt
index 2a3e6256..82667476 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt
@@ -23,13 +23,34 @@ fun AppStore.openBot(id: String?, thread: String? = null) {
}
fun AppStore.showTrace(show: Boolean) { mutableState.update { it.copy(trace = show) } }
-internal fun AppStore.acknowledgeVisible() {
- val current = state.value
- val id = current.selectedBot ?: return
- if (!foreground || current.trace || channel?.state?.value !is LinkState.Ready) return
- action("read:" + id + ":" + current.thread) {
- val response = body("botId" to id, "threadId" to current.thread)
- channel?.call("markRead", response)
+/** A conversation on screen: a bot's main chat (`thread` null) or one of its threads. */
+internal data class ReadingScope(val botId: String, val thread: String?)
+
+/**
+ * What's being read (iOS `ReadingConversation`): the open chat, still on screen under its thread
+ * or Full conversation, and the open thread.
+ */
+internal val AppState.readingScopes: List<ReadingScope> get() {
+ val id = selectedBot ?: return emptyList()
+ return listOfNotNull(ReadingScope(id, null), thread?.let { ReadingScope(id, it) })
+}
+
+/** The scopes events make unread while they're on screen: a message in one, or its bot counting unread. */
+internal fun readAfter(events: List<MirrorEvent>, scopes: List<ReadingScope>): List<ReadingScope> = scopes.filter { scope ->
+ events.any { event ->
+ when (event) {
+ is MirrorEvent.EntryChanged -> event.entry.isChat && event.entry.botId == scope.botId && event.entry.threadId == scope.thread
+ is MirrorEvent.BotChanged -> event.bot.id == scope.botId && event.bot.unread > 0
+ else -> false
+ }
+ }
+}
+
+/** Marks the conversations on screen read (`scopes`: only these); the host ignores it when nothing there is unread. */
+internal fun AppStore.acknowledgeVisible(scopes: List<ReadingScope> = state.value.readingScopes) {
+ if (!foreground || channel?.state?.value !is LinkState.Ready) return
+ for (scope in scopes) action("read:" + scope.botId + ":" + scope.thread) {
+ channel?.call("markRead", body("botId" to scope.botId, "threadId" to scope.thread))
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
index 216c20cb..c699f335 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
@@ -14,7 +14,19 @@ fun AppStore.setRoute(route: ConnectionRoute) = action("route") {
val changed = computer.copy(route = route)
withContext(Dispatchers.IO) { local.saveComputers(listOf(changed)) }
mutableState.update { it.copy(computers = listOf(changed)) }
- connectionJob?.cancelAndJoin(); connect()
+ reconnect().join()
+}
+
+/**
+ * Drop the link and dial again at once (iOS `restartStream`), not after the backoff. It runs in the
+ * account's scope, so a caller that goes away can't leave the link down.
+ */
+fun AppStore.reconnect(): Job = contextScope.launch { connectionJob?.cancelAndJoin(); connect() }
+
+/** A pull to refresh in a chat: reconnect, and hold until the link is back or has failed (the header says why). */
+suspend fun AppStore.refreshConnection() {
+ reconnect().join()
+ withTimeoutOrNull(20_000) { state.first { it.actualConnection !is LinkState.Connecting } }
}
fun AppStore.setForeground(active: Boolean) {
@@ -47,7 +59,7 @@ fun AppStore.pair(text: String) {
require(old == null || old.id == pairing.computer.id) { "Use Start over to pair a different computer." }
require(old == null || old.signKey == pairing.computer.signKey) { "This computer's identity changed. Start over before pairing again." }
val identity = withContext(Dispatchers.IO) { local.identity() }
- val computer = HostConnector.pair(pairing, identity, Build.MODEL.take(100))
+ val computer = HostConnector.pair(pairing, identity, Build.MODEL.take(100)).copy(color = old?.color)
withContext(Dispatchers.IO) { local.saveComputers(listOf(computer)); local.completeSetup() }
mutableState.update { it.copy(computers = listOf(computer), setupComplete = true) }
if (database == null) openMirror()
@@ -90,7 +102,8 @@ fun AppStore.connect() {
reconcileMailbox(active)
}
if (link is LinkState.Ready) {
- val updated = HostClient.hello(active, target)
+ // The latest saved copy: its color may have changed since this link opened.
+ val updated = HostClient.hello(active, state.value.computers.firstOrNull { it.id == target.id } ?: target)
val hello = active.call("hello").jsonObject
withContext(Dispatchers.IO) {
local.saveComputers(listOf(updated))
@@ -161,7 +174,7 @@ private suspend fun AppStore.consumeEvents(active: EncryptedChannel, cursor: Lon
}
withContext(Dispatchers.IO) { requireNotNull(database).apply(batch) }
refresh()
- if (batch.any { it is MirrorEvent.EntryChanged && it.entry.isChat }) acknowledgeVisible()
+ acknowledgeVisible(readAfter(batch, state.value.readingScopes))
if (resync) throw Resync()
}
} finally { source.cancel() }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreDrafts.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreDrafts.kt
index 9126494b..a5b39f88 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreDrafts.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreDrafts.kt
@@ -107,7 +107,3 @@ suspend fun AppStore.attachment(botId: String, file: Attachment): File {
} }
try { return request.await() } finally { request.cancel() }
}
-fun AppStore.shareAttachment(botId: String, file: Attachment) = action("share:" + file.id) {
- val source = attachment(botId, file)
- attachments.share(file, source)
-}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreFiles.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreFiles.kt
new file mode 100644
index 00000000..7c8f1e9e
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreFiles.kt
@@ -0,0 +1,55 @@
+package com.codync.android
+
+import com.codync.android.core.*
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.*
+
+// Files a bot shares in a chat (iOS `FileDownloads`): one download at a time, checked against its
+// SHA-256, then handed to the system share sheet.
+
+/** Where a shared file's download is, as iOS `FileDownloads.State`. */
+sealed interface FileDownloadState {
+ data class Downloading(val received: Long) : FileDownloadState
+ data object Saved : FileDownloadState
+ data class Failed(val message: String) : FileDownloadState
+}
+
+private fun downloadKey(fileId: String) = "file:$fileId"
+
+/** Downloads `file` and opens the share sheet, if its conversation is still on screen by then. */
+fun AppStore.saveFile(entry: Entry, file: SharedFile) {
+ val running = state.value.busy.filter { it.startsWith("file:") }
+ if (running.isNotEmpty()) {
+ if (downloadKey(file.id) !in running) setDownload(file.id, FileDownloadState.Failed("Finish the current download first."))
+ return
+ }
+ action(downloadKey(file.id)) {
+ try {
+ setDownload(file.id, FileDownloadState.Downloading(0))
+ val folder = withContext(Dispatchers.IO) { attachments.shareFolder() }
+ val saved = HostFiles(ready()).downloadShared(entry.id, file, folder) { setDownload(file.id, FileDownloadState.Downloading(it)) }
+ setDownload(file.id, FileDownloadState.Saved)
+ if (showing(entry)) attachments.open(saved, file.name)
+ } catch (cancelled: CancellationException) {
+ setDownload(file.id, null)
+ throw cancelled
+ } catch (error: Exception) {
+ setDownload(file.id, FileDownloadState.Failed(error.message ?: "Couldn't download the file."))
+ }
+ }
+}
+
+fun AppStore.cancelFile(fileId: String) {
+ actions[downloadKey(fileId)]?.cancel()
+ setDownload(fileId, null)
+}
+
+private fun AppStore.setDownload(fileId: String, download: FileDownloadState?) = mutableState.update {
+ it.copy(fileDownloads = if (download == null) it.fileDownloads - fileId else it.fileDownloads + (fileId to download))
+}
+
+/** The chat or thread the message is in (a thread's first message too) is the one open. */
+private fun AppStore.showing(entry: Entry): Boolean {
+ val current = state.value
+ return foreground && current.selectedBot == entry.botId && (current.thread == entry.threadId || current.thread == entry.id)
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNotifications.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNotifications.kt
index aa3da0dd..dac28b4f 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNotifications.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNotifications.kt
@@ -56,7 +56,7 @@ fun AppStore.openLink(uri: Uri) {
if (usage) {
if (state.value.generation == generation) {
openBot(null)
- mutableState.update { it.copy(error = null, navigationRequest = it.navigationRequest + 1, navigationUsage = true) }
+ mutableState.update { it.copy(error = null, navigationRequest = it.navigationRequest + 1, navigationPage = LinkPage.Usage) }
}
return@withTimeoutOrNull true
}
@@ -78,7 +78,7 @@ fun AppStore.openLink(uri: Uri) {
}
if (state.value.generation != generation || state.value.contextId != destination.scope) return@withTimeoutOrNull true
if (state.value.bots.any { it.id == destination.botId && !it.deleted }) {
- mutableState.update { it.copy(error = null, navigationRequest = it.navigationRequest + 1, navigationUsage = false) }
+ mutableState.update { it.copy(error = null, navigationRequest = it.navigationRequest + 1, navigationPage = LinkPage.Bots) }
openBot(destination.botId)
}
else mutableState.update { it.copy(error = "This notification's bot is no longer available on the computer.") }
@@ -87,3 +87,14 @@ fun AppStore.openLink(uri: Uri) {
if (completed == null) mutableState.update { it.copy(error = "Couldn't open this notification yet. Reconnect and try again.") }
}
}
+
+/** `codync://computers` and `codync://plugins`: Computers & settings, or the paired computer's extensions, over the roster. */
+fun AppStore.openPage(page: LinkPage) {
+ linkJob?.cancel()
+ linkJob = viewModelScope.launch {
+ val ready = withTimeoutOrNull(30_000) { activated() } ?: return@launch
+ if (page == LinkPage.Extensions && ready.computers.isEmpty()) return@launch
+ openBot(null)
+ mutableState.update { it.copy(navigationRequest = it.navigationRequest + 1, navigationPage = page) }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AttachmentFiles.kt b/apps/android/app/src/main/kotlin/com/codync/android/AttachmentFiles.kt
index 95f94396..4a133e11 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AttachmentFiles.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AttachmentFiles.kt
@@ -87,19 +87,23 @@ class AttachmentFiles(private val context: Context, private val directory: File)
var bytes = files.sumOf { it.length() }
for (file in files) if (bytes > 512L * 1024 * 1024) { bytes -= file.length(); file.delete() }
}
- suspend fun share(file: Attachment, source: File) {
- val chooser = withContext(Dispatchers.IO) {
+
+ /**
+ * A new folder for one file the share sheet hands out. The receiving app reads it after the sheet
+ * closes, so folders are cleared only once they're a day old.
+ */
+ fun shareFolder(): File {
val root = File(context.cacheDir, "shared-attachments").apply { mkdirs() }
root.listFiles().orEmpty().filter { System.currentTimeMillis() - it.lastModified() > 24 * 60 * 60 * 1000 }.forEach { it.deleteRecursively() }
- val folder = File(root, UUID.randomUUID().toString()).apply { mkdirs() }
- val shared = source.copyTo(File(folder, cleanName(file.name)))
+ return File(root, UUID.randomUUID().toString())
+ }
+
+ /** The system share sheet for a file in a `shareFolder`. */
+ fun open(shared: File, name: String) {
val uri = FileProvider.getUriForFile(context, context.packageName + ".files", shared)
val type = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(shared.extension.lowercase()) ?: "application/octet-stream"
- val intent = Intent(Intent.ACTION_SEND).setType(type).putExtra(Intent.EXTRA_STREAM, uri)
- .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
- Intent.createChooser(intent, "Share " + file.name).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- }
- context.startActivity(chooser)
+ val intent = Intent(Intent.ACTION_SEND).setType(type).putExtra(Intent.EXTRA_STREAM, uri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ context.startActivity(Intent.createChooser(intent, "Share $name").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
companion object {
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AttachmentList.kt b/apps/android/app/src/main/kotlin/com/codync/android/AttachmentList.kt
new file mode 100644
index 00000000..1bbac319
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AttachmentList.kt
@@ -0,0 +1,97 @@
+package com.codync.android
+
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.sizeIn
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.ImageBitmap
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.*
+import com.codync.android.design.*
+import com.kyant.shapes.RoundedRectangle
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+
+/** Files sent with a message, on the sender's side (iOS `AttachmentList`): images as pictures (tap for full size), other files as cards. */
+@Composable internal fun AttachmentList(attachments: List<Attachment>, botId: String, state: AppState, store: AppStore) {
+ var viewing by remember { mutableStateOf<Attachment?>(null) }
+ Column(horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ for (file in attachments) {
+ if (file.isImage) AttachmentImage(file, botId, 720, state, store, Modifier.sizeIn(maxWidth = 220.dp, maxHeight = 280.dp)
+ .clip(RoundedRectangle(16.dp)).plainButton { viewing = file }.semantics { contentDescription = file.name })
+ else AttachmentCard(file)
+ }
+ }
+ CodyncSheet(viewing, { viewing = null }) { file ->
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader(file.name)
+ Box(Modifier.weight(1f).padding(12.dp), contentAlignment = Alignment.Center) {
+ AttachmentImage(file, botId, 4096, state, store, Modifier.fillMaxSize())
+ }
+ }
+ }
+}
+
+@Composable private fun AttachmentCard(file: Attachment) {
+ Row(Modifier.clip(RoundedRectangle(16.dp)).background(Palette.bubbleUser).semantics(mergeDescendants = true) { }
+ .padding(horizontal = 12.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Symbol(AttachmentIcon.symbol(file.name), size = 19.dp, tint = Palette.secondary)
+ Column(verticalArrangement = Arrangement.spacedBy(1.dp)) {
+ Text(file.name, style = Type.subheadline, color = Palette.text, maxLines = 1, overflow = TextOverflow.MiddleEllipsis)
+ Text(formatBytes(file.size), style = Type.caption2, color = Palette.tertiary)
+ }
+ }
+}
+
+/** A sent image, fetched from the computer once and then read from the cache; a placeholder until then. */
+@Composable private fun AttachmentImage(file: Attachment, botId: String, maxPixels: Int, state: AppState, store: AppStore, modifier: Modifier) {
+ var image by remember(file.id, maxPixels) { mutableStateOf<ImageBitmap?>(null) }
+ // Retried whenever the link changes: an image the computer couldn't send stays a placeholder, as on iOS.
+ LaunchedEffect(file.id, maxPixels, state.actualConnection) {
+ if (image != null) return@LaunchedEffect
+ try {
+ val source = store.attachment(botId, file)
+ image = withContext(Dispatchers.IO) { AttachmentFiles.thumbnail(source, maxPixels).asImageBitmap() }
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (_: Exception) { /* The placeholder stays; the next link change tries again. */ }
+ }
+ val bitmap = image
+ if (bitmap != null) Image(bitmap, contentDescription = null, modifier = modifier, contentScale = ContentScale.Fit)
+ else Box(modifier.size(160.dp, 120.dp).clip(RoundedRectangle(16.dp)).background(Palette.bubbleUser), contentAlignment = Alignment.Center) {
+ Symbol("photo", size = 20.dp, tint = Palette.tertiary)
+ }
+}
+
+/** The symbol for a file by its extension. */
+internal object AttachmentIcon {
+ fun symbol(name: String): String = when (name.substringAfterLast('.', "").lowercase()) {
+ "png", "jpg", "jpeg", "heic", "gif", "webp", "tiff", "bmp" -> "photo"
+ "pdf" -> "doc.richtext"
+ "zip", "gz", "tar", "7z" -> "doc.zipper"
+ "mov", "mp4", "m4v" -> "film"
+ "mp3", "m4a", "wav", "aac" -> "waveform"
+ else -> "doc"
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AttachmentRow.kt b/apps/android/app/src/main/kotlin/com/codync/android/AttachmentRow.kt
deleted file mode 100644
index ea02a112..00000000
--- a/apps/android/app/src/main/kotlin/com/codync/android/AttachmentRow.kt
+++ /dev/null
@@ -1,40 +0,0 @@
-package com.codync.android
-
-import androidx.compose.foundation.Image
-import androidx.compose.foundation.clickable
-import androidx.compose.foundation.layout.*
-import androidx.compose.material3.*
-import androidx.compose.runtime.*
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.graphics.ImageBitmap
-import androidx.compose.ui.graphics.asImageBitmap
-import androidx.compose.ui.unit.dp
-import com.codync.android.core.*
-import kotlinx.coroutines.CancellationException
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.withContext
-
-@Composable fun AttachmentRow(botId: String, file: Attachment, state: AppState, store: AppStore) {
- var full by remember(file.id) { mutableStateOf(false) }
- var attempt by remember(file.id) { mutableIntStateOf(0) }
- var image by remember(file.id) { mutableStateOf<ImageBitmap?>(null) }
- var error by remember(file.id) { mutableStateOf<String?>(null) }
- LaunchedEffect(file.id, full, attempt, state.actualConnection) {
- if (file.isImage) try {
- error = null
- val source = store.attachment(botId, file)
- image = withContext(Dispatchers.IO) { AttachmentFiles.thumbnail(source, if (full) 4096 else 720).asImageBitmap() }
- } catch (cancelled: CancellationException) { throw cancelled }
- catch (failure: Exception) { error = failure.message ?: "Couldn't load this image." }
- }
- Column {
- Text(file.name + " · " + formatBytes(file.size))
- image?.let { bitmap -> Image(bitmap, contentDescription = file.name,
- modifier = Modifier.fillMaxWidth().heightIn(max = if (full) 800.dp else 260.dp).clickable { full = !full }) }
- if (file.isImage && image == null && error == null) Text("Loading image…", style = MaterialTheme.typography.bodySmall)
- error?.let { Text(it, style = MaterialTheme.typography.bodySmall); TextButton(onClick = { attempt++ }) { Text("Retry") } }
- TextButton(enabled = "share:" + file.id !in state.busy, onClick = { store.shareAttachment(botId, file) }) {
- Text(if ("share:" + file.id in state.busy) "Downloading…" else "Download / share")
- }
- }
-}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotAvatar.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotAvatar.kt
index 51c91694..25cdf8f7 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/BotAvatar.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotAvatar.kt
@@ -3,27 +3,41 @@ package com.codync.android
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.codync.android.core.Bot
import com.codync.android.design.*
+/** A bot's character, or a group's members. */
@Composable internal fun BotAvatar(bot: Bot, bots: List<Bot>, size: Dp = 44.dp) {
+ if (bot.kind == "group") GroupAvatar(bot.members.mapNotNull { id -> bots.firstOrNull { it.id == id } }
+ .map { AvatarFace(it.avatarShape, it.avatarColor, it.status) }, size)
+ else CharacterAvatar(bot.avatarShape, bot.avatarColor, size, bot.status)
+}
+
+/** The roster's avatar, with its status dot (iOS `AvatarWithStatus`): amber needs you, the accent dot is unread. */
+@Composable internal fun AvatarWithStatus(bot: Bot, bots: List<Bot>, size: Dp = 44.dp) {
Box(Modifier.size(size).clearAndSetSemantics { }) {
- if (bot.kind == "group") GroupAvatar(bot.members.mapNotNull { id -> bots.firstOrNull { it.id == id } }
- .map { AvatarFace(it.avatarShape, it.avatarColor, it.status) }, size)
- else CharacterAvatar(bot.avatarShape, bot.avatarColor, size, bot.status)
- if (bot.status == "needsInput") Box(Modifier.size(size * .36f).align(Alignment.BottomEnd)
- .background(Color(0xFFF0A030), CircleShape), contentAlignment = Alignment.Center) {
- Text("!", color = Color.White, style = MaterialTheme.typography.labelSmall)
- } else if (bot.unread > 0) Box(Modifier.size(size * .28f).align(Alignment.BottomEnd)
- .background(MaterialTheme.colorScheme.primary, CircleShape))
+ BotAvatar(bot, bots, size)
+ if (bot.status == "needsInput") Box(Modifier.size(size * .36f).align(Alignment.BottomEnd).ring()
+ .background(Palette.warning, CircleShape), contentAlignment = Alignment.Center) {
+ Symbol("exclamationmark", size = size * .24f, tint = Color.White)
+ } else if (bot.unread > 0) Box(Modifier.size(size * .28f).align(Alignment.BottomEnd).ring().background(Palette.accentFill, CircleShape))
+ }
+}
+
+/** A 2 dp ring in the background color around the dot, centered on its edge as iOS strokes it. */
+@Composable private fun Modifier.ring(): Modifier {
+ val color = Palette.background
+ return drawWithContent {
+ drawContent()
+ drawCircle(color, size.minDimension / 2, style = Stroke(2.dp.toPx()))
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotEditor.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotEditor.kt
index e74a1e9f..f5b72c85 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/BotEditor.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotEditor.kt
@@ -36,6 +36,7 @@ import kotlinx.serialization.json.jsonPrimitive
@Composable fun BotEditor(state: AppState, initial: BotDraft, store: AppStore) {
var draft by remember(initial.id) { mutableStateOf(initial) }
var folders by remember { mutableStateOf(false) }
+ var viewingSkill by remember { mutableStateOf<SkillRef?>(null) }
val online = state.actualConnection is LinkState.Ready
val saving = "editor" in state.busy
val dismiss = LocalDismissModal.current
@@ -50,13 +51,14 @@ import kotlinx.serialization.json.jsonPrimitive
store.saveBot(draft) { dismiss() }
}
}
- BotSettingsForm(state, store, draft, { draft = it }) { folders = true }
+ BotSettingsForm(state, store, draft, { draft = it }, { viewingSkill = it }) { folders = true }
}
CodyncSheet(folders, { folders = false }) {
FolderPicker(draft.cwd.ifEmpty { state.hello?.get("home")?.jsonPrimitive?.contentOrNull }, online, store::listDirs) {
draft = draft.copy(cwd = it); folders = false
}
}
+ CodyncSheet(viewingSkill, { viewingSkill = null }) { SkillSheet(it, state, store) }
}
/** Picks an installed agent we know; connectors and skills start on once the computer has listed them. */
@@ -76,7 +78,8 @@ private val JsonObject.available get() = this["available"]?.jsonPrimitive?.boole
private val JsonObject.curated get() = this["curated"]?.jsonPrimitive?.booleanOrNull != false
/** Bot settings: a big avatar, then sections in the Settings style (`CardSection`). */
-@Composable private fun BotSettingsForm(state: AppState, store: AppStore, draft: BotDraft, change: (BotDraft) -> Unit, chooseFolder: () -> Unit) {
+@Composable private fun BotSettingsForm(state: AppState, store: AppStore, draft: BotDraft, change: (BotDraft) -> Unit, viewSkill: (SkillRef) -> Unit,
+ chooseFolder: () -> Unit) {
val online = state.actualConnection is LinkState.Ready
val screen = state.screen
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(20.dp), verticalArrangement = Arrangement.spacedBy(30.dp)) {
@@ -164,10 +167,12 @@ private val JsonObject.curated get() = this["curated"]?.jsonPrimitive?.booleanOr
}
val plugins = state.plugins
PluginToggles("Connectors", "No connectors yet. Add GitHub, Linear, Notion and more from Extensions.",
- plugins?.connectors.orEmpty().map { Triple(it.id, it.name, if (it.needsSignIn) "Sign-in needed" else it.command ?: it.url.orEmpty()) },
+ plugins?.connectors.orEmpty().map { Triple(it.id, it.name, it.command ?: it.url.orEmpty()) },
draft.connectors ?: plugins?.connectors.orEmpty().map { it.id }, { change(draft.copy(connectors = it)) })
PluginToggles("Skills", "No skills yet. Get some from Extensions, or write your own.",
- plugins?.skills.orEmpty().map { Triple(it.id, it.name, it.description) }, draft.skills, { change(draft.copy(skills = it)) })
+ plugins?.skills.orEmpty().map { Triple(it.id, it.name, it.description) }, draft.skills, { change(draft.copy(skills = it)) }) { id ->
+ plugins?.skills?.firstOrNull { it.id == id }?.let { viewSkill(SkillRef(it.id, it.name, it.description)) }
+ }
draft.id?.let { MemoryCard(it, store) }
state.error?.let { Text(it, style = Type.footnote, color = Palette.danger) }
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt
index 22cd6225..40d2225f 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt
@@ -37,7 +37,9 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.semantics.CustomAccessibilityAction
import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.customActions
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
@@ -74,6 +76,8 @@ import kotlinx.serialization.json.putJsonArray
NewMenuButton(enabled = state.computers.isNotEmpty(), groupEnabled = online, newBot, newGroup)
}
}) {
+ // Pull to refresh reconnects and asks the account for its computers again (iOS `refreshable`).
+ PullToRefresh({ store.reconnect(); store.refreshComputers() }, Modifier.fillMaxSize(), indicatorTop = top + 50.dp) {
LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = top + 56.dp, bottom = bottomInset)) {
// A computer waiting for an update has its card instead; its bots may not be readable yet.
state.mismatch?.let { mismatch -> item("update") { UpdateNeededCard(state, mismatch, Modifier.padding(vertical = 8.dp)) } }
@@ -89,6 +93,7 @@ import kotlinx.serialization.json.putJsonArray
}
}
}
+ }
}
val deleting = confirmDelete
CodyncDialog("Delete ${deleting?.name ?: "bot"}?", deleting != null, { confirmDelete = null },
@@ -142,6 +147,14 @@ private class RosterReorder {
internal fun roster(bots: List<Bot>): List<Bot> = bots.filter { !it.deleted && !it.hidden }
.sortedWith(compareByDescending<Bot> { it.pinned }.thenBy { it.position }.thenByDescending { it.lastAt })
+/** The roster order with a bot one place up (-1) or down (+1) among bots with its pin state, or null when it can't move. */
+internal fun moved(roster: List<Bot>, id: String, offset: Int): List<String>? {
+ val at = roster.indexOfFirst { it.id == id }
+ val neighbor = roster.getOrNull(at + offset)
+ if (at < 0 || neighbor == null || neighbor.pinned != roster[at].pinned) return null
+ return roster.map(Bot::id).toMutableList().apply { this[at] = neighbor.id; this[at + offset] = id }
+}
+
@Composable private fun BotRowItem(bot: Bot, state: AppState, store: AppStore, drag: ContextDrag, edit: () -> Unit, delete: () -> Unit) {
Box(Modifier.fillMaxWidth().contextActions(onClick = { store.openBot(bot.id) }, reorder = drag, preview = {
Box(Modifier.padding(horizontal = 8.dp)) { BotRow(bot, state) }
@@ -160,7 +173,13 @@ internal fun roster(bots: List<Bot>): List<Bot> = bots.filter { !it.deleted && !
},
MenuItem("Delete", icon = "trash", destructive = true, divider = true, action = delete),
)
- }.semantics { contentDescription = bot.name }) {
+ }.semantics {
+ contentDescription = bot.name
+ // TalkBack's way to reorder (the drag needs a touch and hold, then a move).
+ customActions = listOf(-1 to "Move up", 1 to "Move down").map { (offset, title) ->
+ CustomAccessibilityAction(title) { moved(roster(state.bots), bot.id, offset)?.let(store::reorder) != null }
+ }
+ }) {
BotRow(bot, state)
}
}
@@ -169,7 +188,7 @@ internal fun roster(bots: List<Bot>): List<Bot> = bots.filter { !it.deleted && !
@Composable internal fun BotRow(bot: Bot, state: AppState) {
Row(Modifier.fillMaxWidth().padding(vertical = 10.dp), verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)) {
- BotAvatar(bot, state.bots, 46.dp)
+ AvatarWithStatus(bot, state.bots, 46.dp)
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
@@ -250,7 +269,7 @@ internal fun messagePreview(text: String): String {
listOf(
MenuItem("All computers", icon = "checkmark"),
*state.computers.map { MenuItem("${it.name} · ${connectionLabel(state)}", icon = "checkmark") }.toTypedArray(),
- MenuItem("Reconnect", icon = "arrow.clockwise", divider = true, enabled = state.computers.isNotEmpty()) { store.connect() },
+ MenuItem("Reconnect", icon = "arrow.clockwise", divider = true, enabled = state.computers.isNotEmpty()) { store.reconnect() },
MenuItem("Manage computers", icon = "desktopcomputer", action = manage),
)
}, label = "Computers, $summary. Filter conversations") {
@@ -261,20 +280,6 @@ internal fun messagePreview(text: String): String {
}
}
-/** "2 connected", "Connecting…", "Offline": what the roster says about its computers. */
-internal fun connectionSummary(state: AppState): String = when {
- state.computers.isEmpty() -> "No computers"
- state.connection is LinkState.Ready -> "${state.computers.size} connected"
- state.connection is LinkState.Connecting -> "Connecting…"
- else -> "Offline"
-}
-
-internal fun connectionLabel(state: AppState): String = when (state.connection) {
- is LinkState.Ready -> "Connected"
- is LinkState.Connecting -> "Connecting…"
- else -> "Offline"
-}
-
@Composable private fun NewMenuButton(enabled: Boolean, groupEnabled: Boolean, newBot: () -> Unit, newGroup: () -> Unit) {
DropdownMenu({
listOf(MenuItem("New bot", icon = "plus", action = newBot),
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
index 3754f40a..dd4e55db 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
@@ -163,7 +163,7 @@ private fun messageMenu(context: android.content.Context, entry: Entry, reply: (
if (trace != null) add(MenuItem("Show what it did", icon = "list.bullet", action = trace))
}
-internal val quickReactions = listOf("👍", "❤️", "😂", "🎉", "👀", "🙏")
+internal val quickReactions = listOf("👍", "❤️", "😂", "🎉", "👀", "✅")
private fun reactionPick(entry: Entry, store: AppStore) = ReactionPick(quickReactions, entry.reactions) { emoji ->
store.command("react", body("entryId" to entry.id, "emoji" to emoji), "react:" + entry.id)
@@ -175,9 +175,9 @@ internal val Entry.reactions: List<String> get() = (data["reactions"] as? JsonAr
val context = LocalContext.current
val attachments = entry.data["attachments"]?.jsonArray?.map { WireJson.decodeFromJsonElement<Attachment>(it) }.orEmpty()
Column(Modifier.fillMaxWidth().padding(start = 56.dp), horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(4.dp)) {
- for (file in attachments) AttachmentRow(entry.botId, file, state, store)
+ if (attachments.isNotEmpty()) AttachmentList(attachments, entry.botId, state, store)
if (entry.text.isNotEmpty()) Box(Modifier.clip(RoundedRectangle(18.dp)).background(Palette.bubbleUser)
- .contextActions(reactions = reactionPick(entry, store), preview = { UserText(entry.text) }) {
+ .contextActions(reactions = reactionPick(entry, store), preview = { SelectionContainer { UserText(entry.text) } }) {
messageMenu(context, entry, reply, null)
}) { UserText(entry.text) }
SendStatusLine(entry.status, state.bots.firstOrNull { it.id == entry.botId }?.status == "working")
@@ -231,18 +231,25 @@ internal val Entry.reactions: List<String> get() = (data["reactions"] as? JsonAr
@Composable private fun AgentBubble(entry: Entry, state: AppState, store: AppStore, openTrace: () -> Unit, reply: (() -> Unit)?) {
val context = LocalContext.current
- val attachments = entry.data["attachments"]?.jsonArray?.map { WireJson.decodeFromJsonElement<Attachment>(it) }.orEmpty()
+ val files = entry.files
Column(Modifier.fillMaxWidth().padding(end = 40.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
- for (file in attachments) AttachmentRow(entry.botId, file, state, store)
- if (entry.text.isNotEmpty()) Box(Modifier.clip(RoundedRectangle(18.dp)).background(Palette.bubbleAgent)
- .contextActions(reactions = reactionPick(entry, store), preview = { AgentText(entry.text) }) {
+ // A message with files is its files: the text is only the computer's fallback.
+ if (files.isNotEmpty()) Column(Modifier.contextActions(reactions = reactionPick(entry, store)) { messageMenu(context, entry, reply, openTrace) },
+ verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ for (file in files) FileDownloadCard(entry, file, state, store)
+ } else if (entry.text.isNotEmpty()) Box(Modifier.clip(RoundedRectangle(18.dp)).background(Palette.bubbleAgent)
+ .contextActions(reactions = reactionPick(entry, store), preview = { AgentText(entry.text, selectable = true) }) {
messageMenu(context, entry, reply, openTrace)
- }) { AgentText(entry.text) }
+ }) { AgentText(entry.text, selectable = false) }
}
}
-@Composable private fun AgentText(text: String) {
- Box(Modifier.background(Palette.bubbleAgent).padding(horizontal = 16.dp, vertical = 10.dp)) { MarkdownText(text, selectable = false) }
+/**
+ * A reply. Holding it opens its menu over a lifted copy, as on iOS, so only that copy is `selectable`:
+ * text selection takes the same long press.
+ */
+@Composable private fun AgentText(text: String, selectable: Boolean) {
+ Box(Modifier.background(Palette.bubbleAgent).padding(horizontal = 16.dp, vertical = 10.dp)) { MarkdownText(text, selectable) }
}
/** Under a message with a thread (Slack's): how many replied, how recently. */
@@ -283,6 +290,15 @@ internal val Entry.reactions: List<String> get() = (data["reactions"] as? JsonAr
}
}
+/** A routine's run in the main chat: tapping it opens Routines on that routine. */
+@Composable internal fun RoutineNotice(entry: Entry, open: () -> Unit) {
+ Row(Modifier.plainButton(action = open).padding(vertical = 10.dp), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Symbol("clock.arrow.circlepath", size = 15.dp, tint = Palette.secondary)
+ Text(entry.text.ifEmpty { "Routine" }, style = Type.footnote, color = Palette.secondary)
+ }
+}
+
@Composable private fun NoticeRow(entry: Entry) {
val text = entry.text
val seconds = entry.data["callSeconds"]?.jsonPrimitive?.longOrNull
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt
index 3b132caa..0ca57fe4 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt
@@ -31,11 +31,7 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
-import androidx.compose.foundation.lazy.LazyColumn
-import androidx.compose.foundation.interaction.DragInteraction
-import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
-import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
@@ -44,23 +40,18 @@ import androidx.compose.runtime.key
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
-import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
-import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
-import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
-import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
-import androidx.compose.ui.input.nestedscroll.NestedScrollSource
-import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextOverflow
@@ -69,8 +60,6 @@ import androidx.compose.ui.unit.dp
import com.codync.android.core.*
import com.codync.android.design.*
import com.kyant.shapes.Capsule
-import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.launch
/**
* One endless conversation with a bot or a group, as iOS `ThreadView`: only deliberate messages
@@ -86,6 +75,9 @@ import kotlinx.coroutines.launch
var confirmNewSession by remember { mutableStateOf(false) }
var confirmDelete by remember { mutableStateOf(false) }
var routines by remember { mutableStateOf(false) }
+ // The routine the sheet opens on (a run's notice), or none for the list.
+ var routineId by remember { mutableStateOf<String?>(null) }
+ val openRoutine = { id: String? -> routineId = id; routines = true }
// The bot whose conversation with this one is open.
var peer by remember(bot.id) { mutableStateOf<String?>(null) }
var micDenied by remember { mutableStateOf(false) }
@@ -102,7 +94,7 @@ import kotlinx.coroutines.launch
GlassStage(Modifier.fillMaxSize().background(Palette.background), chrome = {
Box(Modifier.fillMaxWidth().height(top + 64.dp).background(Brush.verticalGradient(
0f to Palette.background, 0.55f to Palette.background.copy(alpha = 0.85f), 1f to Color.Transparent)))
- ThreadHeader(bot, state, store, edit, { store.showTrace(true) }, { routines = true }, { confirmNewSession = true }, { confirmDelete = true })
+ ThreadHeader(bot, state, store, edit, { store.showTrace(true) }, { openRoutine(null) }, { confirmNewSession = true }, { confirmDelete = true })
// The call floats over the chat under the header, as on iOS; the chat stays readable and usable.
AnimatedVisibility(state.voice != null, Modifier.padding(top = top + 54.dp),
enter = fadeIn(Motion.fade()) + slideInVertically(Motion.layoutOffset) { -it }, exit = fadeOut(Motion.fade()) + slideOutVertically(Motion.layoutOffset) { -it }) {
@@ -114,11 +106,12 @@ import kotlinx.coroutines.launch
// Nothing sent now could be read on the other side.
val mismatch = state.mismatch
if (mismatch != null) UpdateNeededCard(state, mismatch, Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp))
- else MessageComposer(bot, null, chatState, store, onCall = if (state.voice == null && state.actualConnection is LinkState.Ready) startCall else null)
+ else MessageComposer(bot, null, chatState, store, onCall = if (state.voice == null && state.actualConnection is LinkState.Ready) startCall else null,
+ onInterrupt = if (state.voice?.botId == bot.id && state.voice.state.phase == VoicePhase.Speaking) store::interruptVoice else null)
}
}) {
Transcript(bot, chatState, store, connect, PaddingValues(start = 16.dp, end = 16.dp, top = top + 60.dp,
- bottom = with(density) { composerHeight.toDp() } + 8.dp)) { peer = it }
+ bottom = with(density) { composerHeight.toDp() } + 8.dp), indicatorTop = top + 50.dp, openRoutine = openRoutine) { peer = it }
}
CodyncDialog("Start a new session?", confirmNewSession, { confirmNewSession = false },
message = "The conversation stays here, but the agent starts with a fresh context.") {
@@ -137,7 +130,7 @@ import kotlinx.coroutines.launch
// A thread over the chat, and "Full conversation" over either.
CodyncSheet(state.thread, { store.openBot(bot.id) }) { root -> RepliesView(bot, root, state, store, connect) }
CodyncSheet(state.trace, { store.showTrace(false) }) { TraceView(bot, state.thread, state) }
- CodyncSheet(routines, { routines = false }) { RoutinesScreen(bot, state, store) }
+ CodyncSheet(routines, { routines = false }) { RoutinesScreen(bot, state, store, routineId) }
CodyncSheet(peer, { peer = null }) { BotConversationView(bot, it, state, store) }
CodyncSheet(app, { app = null; setupEntry = null }) { ComposioConnectSheet(it, state, store, setupEntry) { store.refreshPlugins() } }
CodyncSheet(connector, { connector = null; setupEntry = null }) { InstallConnectorSheet(it, state, store, setupEntry) }
@@ -155,7 +148,7 @@ import kotlinx.coroutines.launch
val host = state.computers.firstOrNull()?.name.orEmpty()
DropdownMenu({ buildList {
add(MenuItem("$host · ${connectionLabel(state)}", enabled = false))
- add(MenuItem("Reconnect", icon = "arrow.clockwise") { store.connect() })
+ add(MenuItem("Reconnect", icon = "arrow.clockwise") { store.reconnect() })
add(MenuItem("Details", icon = "info.circle", divider = true) { edit(bot) })
add(MenuItem("Full conversation", icon = "list.bullet.rectangle", action = trace))
val pin = MenuItem(if (bot.pinned) "Unpin" else "Pin", icon = "pin") {
@@ -203,7 +196,7 @@ import kotlinx.coroutines.launch
/** The link to the computer: route icon (or a spinner) and a word. */
@Composable private fun ConnectionSubtitle(state: AppState) {
- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Row(Modifier.clearAndSetSemantics { contentDescription = "${state.hostName}, ${connectionDescription(state)}" }, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Box(Modifier.width(12.dp), contentAlignment = Alignment.Center) {
when (val link = state.connection) {
LinkState.Connecting -> Spinner(8.dp)
@@ -217,17 +210,17 @@ import kotlinx.coroutines.launch
/** The messages: all this phone has, earlier ones from the computer near the top, following the newest. */
@Composable private fun Transcript(bot: Bot, state: AppState, store: AppStore, connect: ConnectionRequestActions, padding: PaddingValues,
- openPeer: (String) -> Unit) {
+ indicatorTop: Dp, openRoutine: (String) -> Unit, openPeer: (String) -> Unit) {
val entries = state.entries.filter { it.botId == bot.id && it.threadId == null && it.isChat }
val pending = state.pending.filter { it.botId == bot.id && it.threadId == null }
val items = chatItems(entries, pending)
- val working = bot.status in listOf("working", "needsInput") && bot.workingThread == null && state.connection is LinkState.Ready
- val list = rememberLazyListState()
+ val working = bot.isWorking(bot.id, null) && state.connection is LinkState.Ready
val more = bot.id !in state.historyComplete
- Follow(list, items.lastOrNull()?.id, entries.lastOrNull()?.rev, working, padding.calculateBottomPadding())
- LazyColumn(Modifier.fillMaxSize(), state = list, contentPadding = padding) {
+ // Pull to refresh reconnects, like Reconnect in the title menu, until the link is back.
+ ConversationList(items.lastOrNull()?.id, entries.lastOrNull()?.rev, working, padding, store::refreshConnection, indicatorTop) {
if (more) item("earlier") {
- Box(Modifier.fillMaxWidth().padding(vertical = 14.dp), contentAlignment = Alignment.Center) { Spinner(14.dp) }
+ Box(Modifier.fillMaxWidth().padding(vertical = 14.dp).clearAndSetSemantics { contentDescription = "Loading earlier messages" },
+ contentAlignment = Alignment.Center) { Spinner(14.dp) }
// A chat shorter than the screen never scrolls, so showing the row is the trigger.
LaunchedEffect(Unit) { if ("history" !in state.busy) store.loadHistory() }
}
@@ -235,8 +228,12 @@ import kotlinx.coroutines.launch
items(items, key = { it.id }) { item ->
when (item) {
is ChatItem.Separator -> TimeSeparator(item.at)
- is ChatItem.Message -> ChatRow(item.entry, item.groupStart, bot, state, store, openTrace = { store.showTrace(true) },
- reply = { store.openBot(bot.id, item.entry.id) }, connect = connect)
+ is ChatItem.Message -> {
+ val routine = item.entry.data.text("routineId").takeIf { item.entry.kind == "notice" }
+ if (routine != null) RoutineNotice(item.entry) { openRoutine(routine) }
+ else ChatRow(item.entry, item.groupStart, bot, state, store, openTrace = { store.showTrace(true) },
+ reply = { store.openBot(bot.id, item.entry.id) }, connect = connect)
+ }
is ChatItem.Pending -> PendingBubble(item.send, item.groupStart, state, store)
is ChatItem.Exchanges -> BotMessageRow(item.group, state) { openPeer(item.group.peerId) }
}
@@ -245,36 +242,12 @@ import kotlinx.coroutines.launch
}
}
-/** Stays on the newest message until the reader scrolls away; scrolling back down follows again. */
-@Composable private fun Follow(list: LazyListState, last: String?, rev: Long?, working: Boolean, bottom: Dp = 0.dp) {
- var following by remember { mutableStateOf(true) }
- LaunchedEffect(list) {
- // Only the reader's own scroll decides: new content arriving (even while Codync is in the background) keeps the follow.
- var touched = false
- launch { list.interactionSource.interactions.collect { if (it is DragInteraction.Start) touched = true } }
- snapshotFlow { list.isScrollInProgress }.collect { scrolling ->
- if (!scrolling && touched) { touched = false; following = !list.canScrollForward }
- }
- }
- LaunchedEffect(Unit) {
- val count = snapshotFlow { list.layoutInfo.totalItemsCount }.first { it > 0 }
- list.scrollToItem(count - 1, Int.MAX_VALUE)
- }
- // A new message, or the box growing (keyboard, more lines): stay on the newest.
- LaunchedEffect(last, rev, working, bottom) {
- val count = list.layoutInfo.totalItemsCount
- if (!following || count == 0) return@LaunchedEffect
- list.animateScrollToItem(count - 1)
- list.scrollToItem(count - 1, Int.MAX_VALUE)
- }
-}
-
/** A thread: the message it started on, its replies, and a box to continue there. */
@Composable private fun RepliesView(bot: Bot, rootId: String, state: AppState, store: AppStore, connect: ConnectionRequestActions) {
val root = state.entries.firstOrNull { it.botId == bot.id && it.id == rootId }
val replies = state.entries.filter { it.botId == bot.id && it.threadId == rootId && it.isChat }
val pending = state.pending.filter { it.botId == bot.id && it.threadId == rootId }
- val working = bot.status in listOf("working", "needsInput") && bot.workingThread == rootId && state.connection is LinkState.Ready
+ val working = bot.isWorking(bot.id, rootId) && state.connection is LinkState.Ready
var composerHeight by remember { mutableIntStateOf(0) }
val density = LocalDensity.current
val dismiss = LocalDismissModal.current
@@ -288,11 +261,9 @@ import kotlinx.coroutines.launch
IconButton("Close thread", "xmark", action = dismiss)
}
Box(Modifier.fillMaxWidth().height(0.5.dp).background(Palette.border))
- val list = rememberLazyListState()
val items = chatItems(replies, pending)
- Follow(list, items.lastOrNull()?.id, replies.lastOrNull()?.rev, working)
- LazyColumn(Modifier.weight(1f), state = list, contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp,
- bottom = with(density) { composerHeight.toDp() } + 8.dp)) {
+ Box(Modifier.weight(1f)) { ConversationList(items.lastOrNull()?.id, replies.lastOrNull()?.rev, working,
+ PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp, bottom = with(density) { composerHeight.toDp() } + 8.dp)) {
if (root != null) {
item("root") { ChatRow(root, true, bot, state, store, openTrace = { store.showTrace(true) }, reply = null, connect = connect) }
item("count") {
@@ -312,10 +283,12 @@ import kotlinx.coroutines.launch
}
}
if (working) item("working") { WorkingIndicator(bot, currentThinking(state.entries, bot.id, rootId)) }
- }
+ } }
}
Box(Modifier.align(Alignment.BottomCenter).fillMaxWidth().onSizeChanged { composerHeight = it.height }) {
- MessageComposer(bot, rootId, state, store, onCall = null)
+ val mismatch = state.mismatch
+ if (mismatch != null) UpdateNeededCard(state, mismatch, Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp))
+ else MessageComposer(bot, rootId, state, store, onCall = null)
}
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
index e91db962..1b235dba 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
@@ -50,9 +50,15 @@ private enum class Root { Loading, Welcome, Pairing, Tabs }
}
// A new account or a fresh start drops whatever was open for the old one.
LaunchedEffect(state.generation) { if (handledGeneration != state.generation) { closeAll(); showUsage = false; handledGeneration = state.generation } }
- // A notification, widget or link: close everything, then maybe show usage.
+ // A notification, widget or link: close everything, then maybe show usage, the computers or extensions.
LaunchedEffect(state.navigationRequest) {
- if (handledNavigation != state.navigationRequest) { closeAll(); showUsage = state.navigationUsage; handledNavigation = state.navigationRequest }
+ if (handledNavigation != state.navigationRequest) {
+ closeAll()
+ showUsage = state.navigationPage == LinkPage.Usage
+ showComputers = state.navigationPage == LinkPage.Computers
+ showMarketplace = state.navigationPage == LinkPage.Extensions
+ handledNavigation = state.navigationRequest
+ }
}
val signedIn = state.account.userId != null
AnalyticsMilestones(state)
@@ -105,7 +111,7 @@ private enum class Root { Loading, Welcome, Pairing, Tabs }
}
CodyncSheet(access, { access = null }) { AccessRequestView(state, store, it) }
CodyncSheet(showPairing && !state.loading, { showPairing = false }) { PairingView(state, store, inModal = true) }
- CodyncSheet(showUsage && !state.loading, { showUsage = false }) { UsageScreen(state) { store.refreshUsage(it) } }
+ CodyncSheet(showUsage && !state.loading, { showUsage = false }) { UsageScreen(state, store::refreshUsage, store::reloadUsage) }
CodyncSheet(showMarketplace && root == Root.Tabs, { showMarketplace = false }) { MarketplaceView(state, store) }
CodyncSheet(groupEditor.takeIf { !state.loading }, { groupEditor = null }) { draft ->
key(state.contextId, state.generation, draft.id) { GroupEditor(state, draft, store) }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CodyncWidgets.kt b/apps/android/app/src/main/kotlin/com/codync/android/CodyncWidgets.kt
index f02f8531..9a3f6ce0 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/CodyncWidgets.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/CodyncWidgets.kt
@@ -9,6 +9,7 @@ import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.net.Uri
+import android.os.Build
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
@@ -56,19 +57,22 @@ import androidx.glance.text.Text
import androidx.glance.text.TextAlign
import androidx.glance.text.TextStyle
import androidx.glance.unit.ColorProvider as Ink
+import com.codync.android.core.ProviderLimit
import com.codync.android.core.UsageProvider
import com.codync.android.core.UsageWindow
import com.codync.android.core.WidgetBot
import com.codync.android.core.WidgetFeed
import com.codync.android.core.WidgetKind
import com.codync.android.core.teamSlots
+import com.codync.android.core.usageLimits
import com.codync.android.design.characterAvatarBitmap
import kotlin.math.roundToInt
// The Home Screen widgets, drawn like the iOS widgets (CodyncKit `WidgetCards.swift`) and the
-// State tab's previews: Provider usage, Bots and Team.
+// State tab's previews: Provider usage, Usage limits, Bots and Team.
class ProviderWidget : CodyncWidget(WidgetKind.Provider)
+class UsageWidget : CodyncWidget(WidgetKind.Usage)
class BotsWidget : CodyncWidget(WidgetKind.Bots)
class TeamWidget : CodyncWidget(WidgetKind.Team)
@@ -98,6 +102,7 @@ abstract class CodyncWidget(private val kind: WidgetKind) : GlanceAppWidget() {
private val ink = ColorProvider(day = Color(0xFF141414), night = Color(0xFFF2F2F2))
private val secondary = ColorProvider(day = Color(0xFF6B6B6B), night = Color(0xFF9A9A9A))
+private val tertiary = ColorProvider(day = Color(0xFF767676), night = Color(0xFF929292))
private val attention = ColorProvider(day = Color(0xFF936000), night = Color(0xFFECAF52))
private val danger = ColorProvider(day = Color(0xFFC23A2B), night = Color(0xFFF0A7A7))
private val tile = ColorProvider(day = Color(0xFFF0F0F0), night = Color(0xFF1C1C1C))
@@ -110,10 +115,12 @@ private fun style(size: Float, color: Ink, weight: FontWeight = FontWeight.Norma
val context = LocalContext.current
val size = LocalSize.current
val layout = if (size.height >= 230.dp) ProviderLayout.Large else if (size.width >= 230.dp) ProviderLayout.Medium else ProviderLayout.Small
+ // Usage limits opens the app as it is, as on iOS.
val open = widgetIntent(context, feed, usage = kind == WidgetKind.Provider)
Box(GlanceModifier.fillMaxSize().appWidgetBackground().background(ground).cornerRadius(22.dp)
.then(if (sample) GlanceModifier else GlanceModifier.clickable(actionStartActivity(open))).padding(14.dp)) {
when {
+ kind == WidgetKind.Usage -> UsageCard(context, feed, wide = layout != ProviderLayout.Small, sample)
feed.computerId == null && !sample -> Empty("Codync", "Connect a computer in Codync.")
kind == WidgetKind.Provider -> {
val provider = feed.usage.providers.firstOrNull { it.id == providerId }
@@ -197,6 +204,63 @@ private fun dark(context: Context) = context.resources.configuration.uiMode and
}
}
+/** Every provider's limits: the tightest is the headline, the rest thin bars that take color near the limit (iOS `UsageWidgetView`). */
+@Composable private fun UsageCard(context: Context, feed: WidgetFeed, wide: Boolean, sample: Boolean) {
+ val limits = usageLimits(feed.usage)
+ val top = limits.firstOrNull()
+ if (top == null) {
+ Column(GlanceModifier.fillMaxSize()) {
+ Face(context, "blob", "gray", 26.dp)
+ Spacer(GlanceModifier.defaultWeight())
+ Text(if (feed.computerId == null && !sample) "Open Codync to pair with your computer." else "No usage reported yet.",
+ style = style(12f, secondary), maxLines = 3)
+ }
+ return
+ }
+ val rest = limits.drop(1)
+ if (wide) Row(GlanceModifier.fillMaxSize()) {
+ Box(GlanceModifier.width(118.dp)) { LimitHero(top) }
+ Spacer(GlanceModifier.width(18.dp))
+ Column(GlanceModifier.defaultWeight()) {
+ for ((index, limit) in rest.take(4).withIndex()) {
+ if (index > 0) Spacer(GlanceModifier.height(9.dp))
+ LimitBar(context, limit)
+ }
+ }
+ } else Column(GlanceModifier.fillMaxSize()) {
+ LimitHero(top)
+ Spacer(GlanceModifier.defaultWeight())
+ for ((index, limit) in rest.take(2).withIndex()) {
+ if (index > 0) Spacer(GlanceModifier.height(7.dp))
+ LimitBar(context, limit)
+ }
+ }
+}
+
+@Composable private fun LimitHero(limit: ProviderLimit) {
+ val percent = limit.window.percent ?: 0.0
+ Column {
+ Text("${limit.provider} · ${limit.window.label}", style = style(12f, secondary), maxLines = 1)
+ Text("${percent.roundToInt()}%", style = style(34f, if (percent >= 90) danger else ink, FontWeight.Medium), maxLines = 1)
+ Text(limit.window.resetsShort() ?: " ", style = style(11f, tertiary), maxLines = 1)
+ }
+}
+
+@Composable private fun LimitBar(context: Context, limit: ProviderLimit) {
+ val percent = limit.window.percent ?: 0.0
+ Column(GlanceModifier.fillMaxWidth()) {
+ Row(GlanceModifier.fillMaxWidth()) {
+ Text("${limit.provider} ${limit.window.label}", GlanceModifier.defaultWeight(), style = style(11f, secondary), maxLines = 1)
+ Text("${percent.roundToInt()}%", style = style(11f, secondary))
+ }
+ Spacer(GlanceModifier.height(4.dp))
+ // Grey until 70%, then amber (iOS `Palette.usageTint`); the ticks turn red from 90%.
+ Ticks(context, percent, if (percent >= 70) WARNING else ink.getColor(context).toArgb(), 10.dp)
+ }
+}
+
+private const val WARNING = 0xFFF0A030.toInt()
+
/** Fine, separated ticks (iOS `UsageTicks`), as a bitmap: widgets can't draw. */
@Composable private fun Ticks(context: Context, percent: Double, tint: Int, height: Dp) {
val red = danger.getColor(context).toArgb()
@@ -338,6 +402,7 @@ internal fun sampleFeed(): WidgetFeed = WidgetFeed(computerId = "sample", comput
botsAt = System.currentTimeMillis(), usage = WidgetPreview.usage, usageAt = System.currentTimeMillis())
class ProviderWidgetReceiver : CodyncWidgetReceiver() { override val glanceAppWidget = ProviderWidget() }
+class UsageWidgetReceiver : CodyncWidgetReceiver() { override val glanceAppWidget = UsageWidget() }
class BotsWidgetReceiver : CodyncWidgetReceiver() { override val glanceAppWidget = BotsWidget() }
class TeamWidgetReceiver : CodyncWidgetReceiver() { override val glanceAppWidget = TeamWidget() }
@@ -351,17 +416,27 @@ abstract class CodyncWidgetReceiver : GlanceAppWidgetReceiver() {
}
internal object CodyncWidgets {
- val receivers = listOf(ProviderWidgetReceiver::class.java, BotsWidgetReceiver::class.java, TeamWidgetReceiver::class.java)
+ val receivers = listOf(ProviderWidgetReceiver::class.java, UsageWidgetReceiver::class.java, BotsWidgetReceiver::class.java,
+ TeamWidgetReceiver::class.java)
fun installed(context: Context): Int = receivers.sumOf { AppWidgetManager.getInstance(context).getAppWidgetIds(ComponentName(context, it)).size }
suspend fun update(context: Context) {
if (installed(context) == 0) return
- ProviderWidget().updateAll(context); BotsWidget().updateAll(context); TeamWidget().updateAll(context)
+ ProviderWidget().updateAll(context); UsageWidget().updateAll(context); BotsWidget().updateAll(context); TeamWidget().updateAll(context)
+ }
+ /** The launcher's widget picker shows each widget drawn from sample data (Android 15+); the system rate-limits it. */
+ suspend fun publishPreviews(context: Context) {
+ if (Build.VERSION.SDK_INT < 35) return
+ val manager = GlanceAppWidgetManager(context)
+ // A preview that can't be drawn leaves the launcher's placeholder, never a crash at launch.
+ try { for (receiver in receivers) manager.setWidgetPreviews(receiver.kotlin) }
+ catch (cancelled: kotlinx.coroutines.CancellationException) { throw cancelled }
+ catch (error: Exception) { android.util.Log.w("Codync", "Widget previews unavailable", error) }
}
fun pin(context: Context, kind: WidgetKind): Boolean {
val manager = AppWidgetManager.getInstance(context)
if (!manager.isRequestPinAppWidgetSupported) return false
- val receiver = when (kind) { WidgetKind.Provider -> ProviderWidgetReceiver::class.java; WidgetKind.Bots -> BotsWidgetReceiver::class.java
- WidgetKind.Team -> TeamWidgetReceiver::class.java }
+ val receiver = when (kind) { WidgetKind.Provider -> ProviderWidgetReceiver::class.java; WidgetKind.Usage -> UsageWidgetReceiver::class.java
+ WidgetKind.Bots -> BotsWidgetReceiver::class.java; WidgetKind.Team -> TeamWidgetReceiver::class.java }
return manager.requestPinAppWidget(ComponentName(context, receiver), null, null)
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ComposerAttachment.kt b/apps/android/app/src/main/kotlin/com/codync/android/ComposerAttachment.kt
new file mode 100644
index 00000000..0f4ac014
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ComposerAttachment.kt
@@ -0,0 +1,85 @@
+package com.codync.android
+
+import android.webkit.MimeTypeMap
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.ImageBitmap
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.OutgoingFile
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+import java.io.File
+import java.io.IOException
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+
+private val THUMBNAIL = 112.dp
+
+/** A file going out with the next message, removable before it's sent (iOS `ComposerAttachment`): an image as a thumbnail, any other file as a chip. */
+@Composable internal fun ComposerAttachment(file: OutgoingFile, remove: () -> Unit) {
+ val expectsImage = remember(file.name) {
+ MimeTypeMap.getSingleton().getMimeTypeFromExtension(file.name.substringAfterLast('.', "").lowercase())?.startsWith("image/") == true
+ }
+ val pixels = with(LocalDensity.current) { THUMBNAIL.roundToPx() }
+ var image by remember(file.path) { mutableStateOf<ImageBitmap?>(null) }
+ var loaded by remember(file.path) { mutableStateOf(false) }
+ LaunchedEffect(file.path, pixels) {
+ image = thumbnail(file, pixels)
+ loaded = true
+ }
+ val shown = image
+ if (shown != null || expectsImage && !loaded) Box(Modifier.size(THUMBNAIL)) {
+ Box(Modifier.fillMaxSize().clip(RoundedRectangle(16.dp)).background(Palette.surface)
+ .semantics { contentDescription = "Image attachment: ${file.name}" }, contentAlignment = Alignment.Center) {
+ if (shown != null) Image(shown, null, Modifier.fillMaxSize(), contentScale = ContentScale.Fit)
+ else Symbol("photo", size = 20.dp, tint = Palette.secondary)
+ }
+ RemoveButton(file.name, Color.White, Modifier.align(Alignment.TopEnd).padding(4.dp).clip(Capsule()).background(Color.Black.copy(alpha = 0.75f)), remove)
+ } else Row(Modifier.clip(Capsule()).background(Palette.surface).padding(start = 10.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Symbol(AttachmentIcon.symbol(file.name), size = 18.dp, tint = Palette.secondary)
+ Text(file.name, Modifier.widthIn(max = 160.dp), style = Type.footnote, color = Palette.text, maxLines = 1, overflow = TextOverflow.MiddleEllipsis)
+ RemoveButton(file.name, Palette.secondary, action = remove)
+ }
+}
+
+@Composable private fun RemoveButton(name: String, tint: Color, modifier: Modifier = Modifier, action: () -> Unit) {
+ val (source, pressed) = rememberPress()
+ Box(modifier.size(28.dp).pressScale(pressed).clickable(source, null, role = Role.Button, onClick = action)
+ .semantics { contentDescription = "Remove $name" }, contentAlignment = Alignment.Center) {
+ Symbol("xmark", size = 15.dp, tint = tint)
+ }
+}
+
+/** The file as a downsampled picture, off the main thread; null when it isn't one Android can decode. */
+private suspend fun thumbnail(file: OutgoingFile, pixels: Int): ImageBitmap? = withContext(Dispatchers.IO) {
+ // Not a picture (or one Android can't read): it shows as a file chip instead.
+ try { AttachmentFiles.thumbnail(File(file.path), pixels).asImageBitmap() } catch (_: IOException) { null }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt
index 68ce713a..4c0f73a4 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt
@@ -1,27 +1,82 @@
package com.codync.android
+import com.codync.android.core.CloudComputer
+import com.codync.android.core.HostRoute
import com.codync.android.core.LinkState
-/** Cached bots remain readable while the connection reports its actual state. */
-internal fun connectionLabel(link: LinkState): String = when (link) {
- is LinkState.Ready -> "Connected"
+// What the roster header, Computers & settings and the chat header say about the computer's link
+// (iOS `ComputerStatus`, `ConnectionSummary`, `BotStore.connectionLabel`).
+
+/** Turned away by the computer: access revoked, or its identity changed. */
+private val LinkState.unauthorized get() = this is LinkState.Failed && status == 403
+
+/** One short line for the computer's connection, next to its name (iOS `BotStore.statusText`). */
+internal fun statusText(state: AppState): String = if (state.computers.isEmpty()) "Not paired" else when (val link = state.connection) {
+ is LinkState.Ready -> if (state.mismatch != null) "Needs update" else "Online"
LinkState.Connecting -> "Connecting…"
- is LinkState.ComputerOffline -> "Computer offline"
- is LinkState.Failed -> if (link.status == 403) "Access denied" else if (link.status == 426) "Update required" else "Disconnected"
+ is LinkState.ComputerOffline -> link.lastSeenAt?.let { "Offline · seen ${RelativeTime.day(it)}" } ?: "Offline"
+ is LinkState.Failed -> if (link.unauthorized) link.message else "Can't reach"
}
-internal data class EmptyRoster(val title: String, val detail: String? = null, val canCreate: Boolean = false)
-
-internal fun emptyRoster(state: AppState, query: String, hidden: Boolean): EmptyRoster = when {
- state.computers.isEmpty() -> EmptyRoster("No computer yet")
- query.isNotBlank() -> EmptyRoster("No matching bots")
- state.connection !is LinkState.Ready -> EmptyRoster(connectionLabel(state.connection),
- when (val link = state.connection) {
- is LinkState.Failed -> link.message
- is LinkState.ComputerOffline -> "Your bots and chats will appear when the computer reconnects."
- else -> "Waiting for your computer’s bot list."
- })
- !state.rosterLoaded -> EmptyRoster("Syncing bots…")
- hidden -> EmptyRoster("No hidden bots")
- else -> EmptyRoster("No bots yet", canCreate = state.actualConnection is LinkState.Ready)
+/** The status line in Computers & settings: one that's offline while its new identity is around says so. */
+internal fun computerStatusText(state: AppState): String =
+ if (state.isStale && !state.connection.unauthorized) "Older copy of this computer · ${statusText(state)}" else statusText(state)
+
+/** A word for the link: the computer filter's rows and the chat header. */
+internal fun connectionLabel(state: AppState): String = if (state.computers.isEmpty()) "Not paired" else when (val link = state.connection) {
+ is LinkState.Ready -> if (state.mismatch != null) "Needs update" else "Connected"
+ LinkState.Connecting -> "Connecting…"
+ is LinkState.ComputerOffline -> "Offline"
+ is LinkState.Failed -> if (link.unauthorized) "No access" else "Offline"
+}
+
+/** What TalkBack says for the chat header's connection: the route too, when there is one. */
+internal fun connectionDescription(state: AppState): String {
+ val link = state.connection
+ return when {
+ state.computers.isEmpty() -> "Not paired"
+ link == LinkState.Connecting -> "Connecting"
+ link !is LinkState.Ready -> connectionLabel(state)
+ state.mismatch != null -> "Needs update"
+ link.route == HostRoute.Relay -> "Connected through Cloudflare"
+ else -> "Connected over Wi-Fi or Tailscale"
+ }
+}
+
+/** "1 connected", "Connecting…", "No access": the roster header's summary of its computers. */
+internal fun connectionSummary(state: AppState): String = when {
+ state.computers.isEmpty() -> "Computers"
+ state.connection is LinkState.Ready -> "${state.computers.size} connected"
+ state.connection is LinkState.Connecting -> "Connecting…"
+ state.connection.unauthorized -> "No access"
+ else -> "${state.computers.size} offline"
+}
+
+/**
+ * The computer this phone uses won't come back as it is: it turned this phone away, or it's offline
+ * while an account computer with its name is online, the same machine under a new identity
+ * (iOS `AccountStore.isStale`). Removing it is the fix.
+ */
+internal val AppState.isStale: Boolean get() {
+ val computer = computers.firstOrNull() ?: return false
+ return when (val link = connection) {
+ is LinkState.Failed -> link.unauthorized || renamedCopyOnline(computer.id, computer.name)
+ is LinkState.ComputerOffline -> renamedCopyOnline(computer.id, computer.name)
+ else -> false
+ }
+}
+
+private fun AppState.renamedCopyOnline(id: String, name: String) =
+ cloudComputers.any { it.computerId != id && it.name == name && it.online == true }
+
+/**
+ * An offline account computer named like one this phone uses or sees online: most likely the same
+ * machine under an earlier identity (its host keys were reset), left behind in the account.
+ */
+internal fun AppState.isOlderCopy(computer: CloudComputer): Boolean {
+ if (computer.online == true) return false
+ // The current copy may be paired with its code without being listed in the account.
+ return computers.any { it.id != computer.computerId && it.name == computer.name }
+ || cloudComputers.any { other -> other.computerId != computer.computerId && other.name == computer.name
+ && (computers.any { it.id == other.computerId } || other.online == true) }
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ConversationList.kt b/apps/android/app/src/main/kotlin/com/codync/android/ConversationList.kt
new file mode 100644
index 00000000..df3deeb9
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ConversationList.kt
@@ -0,0 +1,99 @@
+package com.codync.android
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.scaleIn
+import androidx.compose.animation.scaleOut
+import androidx.compose.foundation.background
+import androidx.compose.foundation.interaction.DragInteraction
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.LazyListScope
+import androidx.compose.foundation.lazy.LazyListState
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.MutableState
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.snapshotFlow
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.shadow
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import com.codync.android.design.*
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+
+/**
+ * A conversation's scrolling list (iOS `ConversationList`): it opens at the newest message and follows
+ * it as messages arrive (`last`, `rev`, `working`) until the reader scrolls away; then a round button
+ * leads back down. With `refresh`, a pull past the top runs it, its indicator at `indicatorTop`.
+ */
+@Composable internal fun ConversationList(last: String?, rev: Long?, working: Boolean, padding: PaddingValues,
+ refresh: (suspend () -> Unit)? = null, indicatorTop: Dp = 0.dp, content: LazyListScope.() -> Unit) {
+ val list = rememberLazyListState()
+ val bottom = padding.calculateBottomPadding()
+ val following = rememberFollowing(list, last, rev, working, bottom)
+ val scope = rememberCoroutineScope()
+ Box(Modifier.fillMaxSize()) {
+ if (refresh == null) LazyColumn(Modifier.fillMaxSize(), state = list, contentPadding = padding, content = content)
+ else PullToRefresh(refresh, Modifier.fillMaxSize(), indicatorTop) {
+ LazyColumn(Modifier.fillMaxSize(), state = list, contentPadding = padding, content = content)
+ }
+ // 10 above the composer, as on iOS: the list already keeps 8 under its last row.
+ JumpToLatest(!following.value && last != null, Modifier.align(Alignment.BottomCenter).padding(bottom = bottom + 2.dp)) {
+ following.value = true
+ scope.launch { list.scrollToEnd(animated = true) }
+ }
+ }
+}
+
+/** Stays on the newest message until the reader scrolls away; scrolling back down follows again. */
+@Composable private fun rememberFollowing(list: LazyListState, last: String?, rev: Long?, working: Boolean, bottom: Dp): MutableState<Boolean> {
+ val following = remember { mutableStateOf(true) }
+ LaunchedEffect(list) {
+ // Only the reader's own scroll decides: new content arriving (even while Codync is in the background) keeps the follow.
+ var touched = false
+ launch { list.interactionSource.interactions.collect { if (it is DragInteraction.Start) touched = true } }
+ snapshotFlow { list.isScrollInProgress }.collect { scrolling ->
+ if (!scrolling && touched) { touched = false; following.value = !list.canScrollForward }
+ }
+ }
+ LaunchedEffect(Unit) {
+ snapshotFlow { list.layoutInfo.totalItemsCount }.first { it > 0 }
+ list.scrollToEnd(animated = false)
+ }
+ // A new message, or the box growing (keyboard, more lines): stay on the newest.
+ LaunchedEffect(last, rev, working, bottom) {
+ if (following.value && list.layoutInfo.totalItemsCount > 0) list.scrollToEnd(animated = true)
+ }
+ return following
+}
+
+private suspend fun LazyListState.scrollToEnd(animated: Boolean) {
+ val count = layoutInfo.totalItemsCount
+ if (count == 0) return
+ if (animated) animateScrollToItem(count - 1)
+ scrollToItem(count - 1, Int.MAX_VALUE)
+}
+
+/** Scrolled away from the newest messages: a round button back down to them. */
+@Composable private fun JumpToLatest(visible: Boolean, modifier: Modifier, action: () -> Unit) {
+ AnimatedVisibility(visible, modifier, enter = fadeIn(Motion.layout()) + scaleIn(Motion.layout(), initialScale = 0.8f),
+ exit = fadeOut(Motion.layout()) + scaleOut(Motion.layout(), targetScale = 0.8f)) {
+ // iOS `frosted(in: Circle())`: a near-opaque grey disc lifted by a soft shadow.
+ val frosted = Color(if (LocalDark.current) 0xFF232323 else 0xFFF4F4F4).copy(alpha = 0.82f)
+ Box(Modifier.shadow(8.dp, CircleShape).background(frosted, CircleShape)) {
+ IconButton("Jump to latest", "arrow.down", action = action)
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/FileDownloadCard.kt b/apps/android/app/src/main/kotlin/com/codync/android/FileDownloadCard.kt
new file mode 100644
index 00000000..cd0e2f31
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/FileDownloadCard.kt
@@ -0,0 +1,51 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.Entry
+import com.codync.android.core.SharedFile
+import com.codync.android.design.*
+import com.kyant.shapes.RoundedRectangle
+
+/** A file a bot shared, as iOS `FileDownloadCard`: its name and size, and a button to download (or cancel). */
+@Composable internal fun FileDownloadCard(entry: Entry, file: SharedFile, state: AppState, store: AppStore) {
+ val download = state.fileDownloads[file.id]
+ val busy = download is FileDownloadState.Downloading
+ Row(Modifier.fillMaxWidth().clip(RoundedRectangle(16.dp)).background(Palette.bubbleAgent).padding(14.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Symbol(AttachmentIcon.symbol(file.name), size = 24.dp, tint = Palette.secondary)
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
+ Text(file.name, style = Type.subheadline.semibold, color = Palette.text, maxLines = 2, overflow = TextOverflow.Ellipsis)
+ Text(detail(file, download), style = Type.caption2, color = Palette.secondary)
+ }
+ Box(Modifier.size(36.dp).plainButton { if (busy) store.cancelFile(file.id) else store.saveFile(entry, file) }
+ .semantics { contentDescription = (if (busy) "Cancel download " else "Download ") + file.name }, contentAlignment = Alignment.Center) {
+ Symbol(if (busy) "xmark" else "arrow.down.to.line", size = 20.dp, tint = Palette.text)
+ }
+ }
+}
+
+private fun detail(file: SharedFile, download: FileDownloadState?): String {
+ val size = formatBytes(file.size)
+ return when (download) {
+ is FileDownloadState.Downloading -> "${formatBytes(download.received)} of $size"
+ is FileDownloadState.Failed -> "${download.message} Tap to retry."
+ FileDownloadState.Saved -> "$size · Downloaded"
+ null -> size
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/LeadBotTile.kt b/apps/android/app/src/main/kotlin/com/codync/android/LeadBotTile.kt
new file mode 100644
index 00000000..794e22f3
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/LeadBotTile.kt
@@ -0,0 +1,50 @@
+package com.codync.android
+
+import android.annotation.SuppressLint
+import android.app.PendingIntent
+import android.graphics.drawable.Icon
+import android.net.Uri
+import android.os.Build
+import android.service.quicksettings.Tile
+import android.service.quicksettings.TileService
+import com.codync.android.core.leadBot
+import com.codync.android.design.symbolRes
+
+/**
+ * The Bots tile in Quick Settings (the iOS Control Center control): the bot that needs you most
+ * and its state, from the widgets' report; a tap opens it, or Computers & settings when no bot is at work.
+ */
+class LeadBotTile : TileService() {
+ override fun onStartListening() {
+ val tile = qsTile ?: return
+ val feed = WidgetStore.feed(this)
+ val lead = leadBot(feed.bots)
+ val (label, state, symbol) = when {
+ feed.computerId == null -> Triple("Bots", "Connect a computer", "desktopcomputer")
+ lead == null -> Triple("Bots", "All quiet", "moon.zzz.fill")
+ lead.status == "needsInput" -> Triple(lead.name, "Needs you", "hand.raised.fill")
+ else -> Triple(lead.name, "Working", "ellipsis.bubble.fill")
+ }
+ tile.label = label
+ tile.subtitle = state
+ tile.contentDescription = "$label, $state"
+ tile.icon = Icon.createWithResource(this, requireNotNull(symbolRes(symbol)))
+ tile.state = if (lead != null) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
+ tile.updateTile()
+ }
+
+ // Before Android 14 the Intent form is the only one; it is guarded by version.
+ @SuppressLint("StartActivityAndCollapseDeprecated")
+ override fun onClick() {
+ val feed = WidgetStore.feed(this)
+ // No bot at work: Computers & settings, as the iPhone's control does.
+ val intent = leadBot(feed.bots)?.let { widgetIntent(this, feed, it.id) }
+ ?: widgetIntent(this, feed).setData(Uri.parse("${BuildConfig.URL_SCHEME}://computers"))
+ // A bot's chat is private: the phone unlocks first.
+ unlockAndRun {
+ if (Build.VERSION.SDK_INT >= 34) startActivityAndCollapse(PendingIntent.getActivity(this, 0, intent,
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE))
+ else @Suppress("DEPRECATION") startActivityAndCollapse(intent)
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt b/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt
index be978547..2e078dc1 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt
@@ -15,11 +15,13 @@ import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.key
import androidx.compose.runtime.LaunchedEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.lifecycle.lifecycleScope
import com.codync.android.design.CodyncTheme
import com.codync.android.design.OverlayRoot
import coil3.ImageLoader
import coil3.disk.DiskCache
import java.io.File
+import kotlinx.coroutines.launch
import okio.Path.Companion.toOkioPath
class MainActivity : ComponentActivity() {
@@ -30,6 +32,7 @@ class MainActivity : ComponentActivity() {
Analytics.start(applicationContext)
Analytics.userId = { store.state.value.account.userId }
NotificationDisplay.channels(this)
+ if (savedInstanceState == null) lifecycleScope.launch { CodyncWidgets.publishPreviews(applicationContext) }
enableEdgeToEdge()
setContent {
val state by store.state.collectAsStateWithLifecycle()
@@ -77,6 +80,8 @@ class MainActivity : ComponentActivity() {
if (uri.scheme == BuildConfig.URL_SCHEME && uri.host in setOf("bot", "usage")) store.openLink(uri)
if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "oauth") { intent.data = null; store.finishConnectorSignIn(uri) }
if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "screen") { intent.data = null; store.openScreenLink() }
+ if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "computers") { intent.data = null; store.openPage(LinkPage.Computers) }
+ if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "plugins") { intent.data = null; store.openPage(LinkPage.Extensions) }
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MarketplaceView.kt b/apps/android/app/src/main/kotlin/com/codync/android/MarketplaceView.kt
index f0ecd109..9682e8ff 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/MarketplaceView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MarketplaceView.kt
@@ -236,7 +236,7 @@ private fun Modifier.bleed(amount: Dp) = layout { measurable, constraints ->
val count = connectors.size + state.plugins?.skills.orEmpty().size
Column(modifier.padding(top = 28.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
- ComputerBadge(state.hello?.text("device"), 32.dp)
+ ComputerBadge(state.hello?.text("device"), 32.dp, state.computers.firstOrNull()?.color)
Column {
Text("Extensions", style = Type.title2.semibold, color = Palette.text, maxLines = 1)
Text(state.hostName, style = Type.subheadline, color = Palette.secondary, maxLines = 1)
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt b/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt
index a9250663..d5c93b9c 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt
@@ -1,5 +1,7 @@
package com.codync.android
+import android.content.ClipDescription
+import android.content.ClipboardManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
@@ -33,7 +35,6 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
-import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.input.TextFieldLineLimits
@@ -51,6 +52,7 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalClipboard
+import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
@@ -62,14 +64,16 @@ import com.kyant.shapes.RoundedRectangle
import kotlinx.coroutines.launch
/** What the composer's one trailing button does now; it morphs between them. */
-private enum class Trailing { Stop, Call, Send }
+private enum class Trailing { Interrupt, Stop, Call, Send }
/**
* The message box under a chat or a thread, as iOS `Composer`: a glass + for files, a glass
- * field whose trailing button morphs between call, send and stop.
+ * field whose trailing button morphs between call, send, stop and interrupt. `onInterrupt`
+ * cuts the bot off while it speaks in a voice call.
*/
@OptIn(ExperimentalFoundationApi::class)
-@Composable fun MessageComposer(bot: Bot, thread: String?, state: AppState, store: AppStore, onCall: (() -> Unit)?) {
+@Composable fun MessageComposer(bot: Bot, thread: String?, state: AppState, store: AppStore, onCall: (() -> Unit)?,
+ onInterrupt: (() -> Unit)? = null) {
val lane = ComposerDraft.lane(bot.id, thread)
val draft = state.drafts[lane]
val text = rememberTextFieldState(initialText = draft?.text.orEmpty())
@@ -89,6 +93,7 @@ private enum class Trailing { Stop, Call, Send }
if (external != text.text.toString() && external !in echoes) text.setTextAndPlaceCursorAtEnd(external)
}
val clipboard = LocalClipboard.current
+ val clips = LocalContext.current.getSystemService(ClipboardManager::class.java)
val scope = rememberCoroutineScope()
val photos = rememberLauncherForActivityResult(ActivityResultContracts.PickMultipleVisualMedia(10)) { uris ->
if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(bot.id, thread, it) }
@@ -97,7 +102,7 @@ private enum class Trailing { Stop, Call, Send }
if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(bot.id, thread, it) }
}
val receiver = remember(bot.id, importing, queuing) { ReceiveContentListener { content ->
- if (bot.kind == "group" || importing || queuing) content else {
+ if (importing || queuing) content else {
val uris = mutableListOf<android.net.Uri>()
val remaining = content.consume { item -> item.uri?.takeIf { it.scheme == "content" }?.let { uris.add(it); true } ?: false }
if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(bot.id, thread, it) }
@@ -107,11 +112,13 @@ private enum class Trailing { Stop, Call, Send }
val online = state.actualConnection is LinkState.Ready
val empty = text.text.isBlank() && files.isEmpty()
// Offline computers still take text when the relay can hold it; files need the computer.
- val canSend = !empty && !importing && !queuing && (online || files.isEmpty())
- val working = bot.status in listOf("working", "needsInput") && (thread == null || bot.workingThread == thread)
+ val canSend = !empty && !importing && !queuing && (online || state.actualConnection is LinkState.ComputerOffline && files.isEmpty())
+ val working = bot.isWorking(bot.id, thread)
+ val bare = text.text.isEmpty() && files.isEmpty()
val trailing = when {
- working && empty -> Trailing.Stop
- onCall != null && empty && thread == null -> Trailing.Call
+ onInterrupt != null && bare -> Trailing.Interrupt
+ working && bare -> Trailing.Stop
+ onCall != null && bare -> Trailing.Call
else -> Trailing.Send
}
val placeholder = when {
@@ -122,6 +129,9 @@ private enum class Trailing { Stop, Call, Send }
}
val typed = text.text.toString()
val commands = SlashCommands.query(typed)?.let { SlashCommands.list(bot, it, state.plugins?.skills.orEmpty(), state.hello?.text("version")) }.orEmpty()
+ // Starting a command: list the computer's skills again, once each time the draft becomes "/".
+ val startingCommand = typed == "/" && bot.kind != "group"
+ LaunchedEffect(startingCommand) { if (startingCommand && online) store.refreshPlugins() }
val mentions = if (bot.kind != "group") emptyList() else mentionQuery(typed)?.let { query ->
bot.members.mapNotNull { id -> state.bots.firstOrNull { it.id == id } }.filter { query.isEmpty() || it.name.contains(query, true) }
}.orEmpty()
@@ -144,23 +154,21 @@ private enum class Trailing { Stop, Call, Send }
}
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, top = 6.dp, bottom = 16.dp), verticalAlignment = Alignment.Bottom,
horizontalArrangement = Arrangement.spacedBy(8.dp)) {
- if (bot.kind != "group") {
- val (source, pressed) = rememberPress()
- DropdownMenu({ listOf(
- MenuItem("Photos", icon = "photo.on.rectangle") { photos.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) },
- MenuItem("Files", icon = "folder") { documents.launch(arrayOf("*/*")) },
- MenuItem("Paste", icon = "doc.on.clipboard") { scope.launch {
- val data = clipboard.getClipEntry()?.clipData
- val uris = if (data == null) emptyList() else (0 until data.itemCount).mapNotNull { data.getItemAt(it).uri }
- if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(bot.id, thread, it) }
- } },
- ) }, Modifier.size(FIELD_HEIGHT).glass(Capsule(), pressed = pressed), enabled = !queuing, label = "Add files") {
- Symbol("plus", size = 26.dp, tint = Palette.text)
- }
+ DropdownMenu({ buildList {
+ add(MenuItem("Photos", icon = "photo.on.rectangle") { photos.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) })
+ add(MenuItem("Files", icon = "folder") { documents.launch(arrayOf("*/*")) })
+ // Only the clip's description: reading the clip itself would show Android's paste notice.
+ if (clipOffersFiles(clips.primaryClipDescription?.mimeTypes().orEmpty())) add(MenuItem("Paste", icon = "doc.on.clipboard") { scope.launch {
+ val data = clipboard.getClipEntry()?.clipData
+ val uris = if (data == null) emptyList() else (0 until data.itemCount).mapNotNull { data.getItemAt(it).uri?.takeIf { uri -> uri.scheme == "content" } }
+ if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(bot.id, thread, it) }
+ } })
+ } }, Modifier.size(FIELD_HEIGHT).glass(Capsule()), enabled = !queuing, label = "Add files") {
+ Symbol("plus", size = 26.dp, tint = Palette.text)
}
Column(Modifier.weight(1f).glass(RoundedRectangle(24.dp)).animateContentSize(Motion.layoutSize)) {
if (files.isNotEmpty()) Row(Modifier.horizontalScroll(rememberScrollState()).padding(start = 10.dp, end = 10.dp, top = 8.dp),
- horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
for (file in files) ComposerAttachment(file) { store.removeDraftFile(bot.id, thread, file) }
}
Row(Modifier.padding(start = 18.dp, end = 6.dp, top = 6.dp, bottom = 6.dp), verticalAlignment = Alignment.Bottom,
@@ -171,6 +179,7 @@ private enum class Trailing { Stop, Call, Send }
decorator = { input -> Box { if (text.text.isEmpty()) Text(placeholder, style = Type.body, color = Palette.tertiary, maxLines = 1); input() } })
TrailingButton(trailing, canSend, Modifier.padding(bottom = 4.dp)) {
when (trailing) {
+ Trailing.Interrupt -> onInterrupt?.invoke()
Trailing.Stop -> store.command("stop", body("botId" to bot.id))
Trailing.Call -> onCall?.invoke()
Trailing.Send -> {
@@ -187,21 +196,29 @@ private enum class Trailing { Stop, Call, Send }
private val FIELD_HEIGHT = 54.dp
-/** One button that morphs between call, send and stop: its symbol swaps, its fill crossfades and the capsule narrows. */
+/** One button that morphs between call, send, stop and interrupt: its symbol swaps, its fill crossfades and the capsule narrows. */
@Composable private fun TrailingButton(state: Trailing, canSend: Boolean, modifier: Modifier, action: () -> Unit) {
val enabled = state != Trailing.Send || canSend
- val fill by animateColorAsState(if (state == Trailing.Send && !canSend) Palette.accentDim else Palette.accentFill, Motion.morph(), label = "Fill")
- val ink = if (state == Trailing.Send && !canSend) Palette.tertiary else Palette.onAccent
+ val fill by animateColorAsState(when {
+ state == Trailing.Interrupt -> Palette.danger
+ state == Trailing.Send && !canSend -> Palette.accentDim
+ else -> Palette.accentFill
+ }, Motion.morph(), label = "Fill")
+ val ink by animateColorAsState(when {
+ state == Trailing.Interrupt -> Color.White
+ state == Trailing.Send && !canSend -> Palette.tertiary
+ else -> Palette.onAccent
+ }, Motion.morph(), label = "Ink")
val width by animateDpAsState(if (state == Trailing.Call) 46.dp else 34.dp, Motion.morph(), label = "Width")
val (source, pressed) = rememberPress()
Box(modifier.pressScale(pressed).size(width, 34.dp).clip(Capsule()).background(fill)
.clickable(source, null, enabled = enabled, role = Role.Button, onClick = action)
- .semantics { contentDescription = when (state) { Trailing.Stop -> "Stop"; Trailing.Call -> "Call"; Trailing.Send -> "Send" } },
+ .semantics { contentDescription = when (state) { Trailing.Interrupt -> "Interrupt"; Trailing.Stop -> "Stop"; Trailing.Call -> "Call"; Trailing.Send -> "Send" } },
contentAlignment = Alignment.Center) {
AnimatedContent(state, transitionSpec = { (fadeIn(Motion.morph()) + scaleIn(Motion.morph(), 0.6f)) togetherWith
(fadeOut(Motion.morph()) + scaleOut(Motion.morph(), 0.6f)) }, label = "Symbol") { shown ->
when (shown) {
- Trailing.Stop -> Symbol("stop.fill", size = 16.dp, tint = ink)
+ Trailing.Interrupt, Trailing.Stop -> Symbol("stop.fill", size = 16.dp, tint = ink)
Trailing.Call -> Symbol("waveform", size = 20.dp, tint = ink)
Trailing.Send -> Symbol("arrow.up", size = 19.dp, tint = ink)
}
@@ -209,20 +226,14 @@ private val FIELD_HEIGHT = 54.dp
}
}
-/** A file going out with the next message, removable before it's sent. */
-@Composable private fun ComposerAttachment(file: OutgoingFile, remove: () -> Unit) {
- Row(Modifier.clip(RoundedRectangle(12.dp)).background(Palette.surface).padding(start = 10.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),
- verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
- Symbol(if (file.name.substringAfterLast('.', "").lowercase() in listOf("png", "jpg", "jpeg", "heic", "gif", "webp")) "photo" else "doc",
- size = 16.dp, tint = Palette.secondary)
- Column {
- Text(file.name, Modifier.width(120.dp), style = Type.footnote, color = Palette.text, maxLines = 1)
- Text(formatBytes(file.size), style = Type.caption2, color = Palette.tertiary)
- }
- Box(Modifier.size(28.dp).clickable(role = Role.Button, onClick = remove).semantics { contentDescription = "Remove ${file.name}" },
- contentAlignment = Alignment.Center) { Symbol("xmark.circle.fill", size = 18.dp, tint = Palette.tertiary) }
- }
-}
+/**
+ * Whether the clipboard holds what Paste can attach (iOS: images or URLs), from its MIME types alone.
+ * Text, HTML and intents carry no file; any other type comes from a URI item.
+ */
+internal fun clipOffersFiles(mimeTypes: List<String>): Boolean =
+ mimeTypes.any { it !in listOf(ClipDescription.MIMETYPE_TEXT_PLAIN, ClipDescription.MIMETYPE_TEXT_HTML, ClipDescription.MIMETYPE_TEXT_INTENT) }
+
+private fun ClipDescription.mimeTypes(): List<String> = (0 until mimeTypeCount).map(::getMimeType)
fun formatBytes(size: Long): String = when {
size >= 1024 * 1024 -> "%.1f MB".format(size / (1024.0 * 1024))
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/PushService.kt b/apps/android/app/src/main/kotlin/com/codync/android/PushService.kt
index 4d2b51ac..977a7c8d 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/PushService.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/PushService.kt
@@ -50,7 +50,10 @@ object PushDelivery {
suspend fun retire(context: Context) {
PushPreferences.retire(context)
WorkManager.getInstance(context).cancelUniqueWork(WORK_NAME)
- gate.withLock { context.getSystemService(NotificationManager::class.java).cancelAll() }
+ gate.withLock {
+ context.getSystemService(NotificationManager::class.java).cancelAll()
+ AlertConversations.forget(context)
+ }
}
suspend fun activate(context: Context, user: String?) {
WorkManager.getInstance(context).cancelUniqueWork(WORK_NAME)
@@ -178,18 +181,14 @@ class PushService : FirebaseMessagingService() {
return
}
if (!PushPreferences.enabled(context) || PushDelivery.foreground) return
- var title = context.getString(R.string.app_name)
- var text = "A bot has an update."
+ var alert = PushAlert(title = context.getString(R.string.app_name), body = "A bot has an update.")
try {
if (local.hasIdentity()) {
val sealed = requireNotNull(data["sealed"]).takeIf { it.length <= 8192 } ?: return
- val plain = local.identity().openPush(sealed, computerId)
- val alert = Json.parseToJsonElement(plain.toString(Charsets.UTF_8)).jsonObject
- title = alert.getValue("title").jsonPrimitive.content.take(120)
- text = alert.getValue("body").jsonPrimitive.content.take(400)
+ alert = PushAlert.decode(local.identity().openPush(sealed, computerId).toString(Charsets.UTF_8))
}
} catch (_: Exception) { /* Locked/unavailable key: show only a generic fallback. */ }
- NotificationDisplay.alert(context, scope, computerId, botId, title, text)
+ NotificationDisplay.alert(context, scope, computerId, botId, alert)
} catch (_: Exception) { /* A malformed push cannot crash the Firebase service. */ }
}
}
@@ -204,20 +203,30 @@ internal object NotificationDisplay {
manager.createNotificationChannel(NotificationChannel(ALERTS, "Bot updates", NotificationManager.IMPORTANCE_HIGH))
manager.createNotificationChannel(NotificationChannel(TASKS, "Delegated tasks", NotificationManager.IMPORTANCE_LOW))
}
- private fun builder(context: Context, scope: String, computer: String, bot: String, channel: String): NotificationCompat.Builder {
+ private fun open(context: Context, scope: String, computer: String, bot: String): Intent {
val url = Uri.Builder().scheme(BuildConfig.URL_SCHEME).authority("bot").appendPath(bot).appendQueryParameter("scope", scope).appendQueryParameter("computer", computer).build()
- val intent = Intent(context, MainActivity::class.java).setAction(Intent.ACTION_VIEW).setData(url)
- val pending = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
+ return Intent(context, MainActivity::class.java).setAction(Intent.ACTION_VIEW).setData(url)
+ }
+ private fun builder(context: Context, scope: String, computer: String, bot: String, channel: String): NotificationCompat.Builder {
+ val pending = PendingIntent.getActivity(context, 0, open(context, scope, computer, bot), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
val generic = NotificationCompat.Builder(context, channel).setSmallIcon(R.drawable.ic_notification)
.setContentTitle(context.getString(R.string.app_name)).setContentText("A bot has an update.").build()
return NotificationCompat.Builder(context, channel).setSmallIcon(R.drawable.ic_notification).setContentIntent(pending)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE).setPublicVersion(generic).setGroup("$scope/$computer")
}
- fun alert(context: Context, scope: String, computer: String, bot: String, title: String, text: String) {
+ /** The alert's title, what happened and its text; with the chat's face, a conversation from the bot. */
+ fun alert(context: Context, scope: String, computer: String, bot: String, alert: PushAlert) {
channels(context)
- val notification = builder(context, scope, computer, bot, ALERTS).setContentTitle(title).setContentText(text)
- .setStyle(NotificationCompat.BigTextStyle().bigText(text)).setAutoCancel(true).setCategory(NotificationCompat.CATEGORY_MESSAGE).build()
- try { context.getSystemService(NotificationManager::class.java).notify("$scope/$computer/$bot", 1, notification) } catch (_: SecurityException) { }
+ val tag = "$scope/$computer/$bot"
+ val builder = builder(context, scope, computer, bot, ALERTS).setContentTitle(alert.title).setContentText(alert.body)
+ .setSubText(alert.subtitle).setStyle(NotificationCompat.BigTextStyle().bigText(alert.body))
+ .setAutoCancel(true).setCategory(NotificationCompat.CATEGORY_MESSAGE)
+ alert.conversation(bot)?.let { conversation ->
+ // A system that refuses the conversation still shows the plain alert.
+ try { AlertConversations.style(context, builder, tag, computer, open(context, scope, computer, bot), alert.body, conversation) }
+ catch (error: Exception) { android.util.Log.w("Codync", "Alert shown without its conversation", error) }
+ }
+ try { context.getSystemService(NotificationManager::class.java).notify(tag, 1, builder.build()) } catch (_: SecurityException) { }
}
/**
* A delegated task: on Android 16 a Live update (promoted ongoing notification) with its
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/RoutinesScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/RoutinesScreen.kt
index 23f9d8a1..8f9bf9d2 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/RoutinesScreen.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/RoutinesScreen.kt
@@ -59,14 +59,17 @@ import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
-/** A bot's routines, in a sheet over its chat (iOS `RoutinesView`); a row opens its editor. */
-@Composable fun RoutinesScreen(bot: Bot, state: AppState, store: AppStore) {
+/**
+ * A bot's routines, in a sheet over its chat (iOS `RoutinesView`); a row opens its editor.
+ * `initialId`: open on that routine's editor (a run's notice in the chat was tapped).
+ */
+@Composable fun RoutinesScreen(bot: Bot, state: AppState, store: AppStore, initialId: String?) {
val dismiss = LocalDismissModal.current
val online = state.actualConnection is LinkState.Ready
val listing = state.routines[bot.id]
val busy = "routines:${bot.id}" in state.busy
// The open editor: on a routine (its id), or "" setting up a new one.
- var editing by remember(bot.id) { mutableStateOf<String?>(null) }
+ var editing by remember(bot.id) { mutableStateOf(initialId) }
LaunchedEffect(bot.id, online) { if (online) while (true) { store.loadRoutines(bot.id); delay(3_000) } }
Column(Modifier.fillMaxSize().background(Palette.background).verticalScroll(rememberScrollState()).padding(20.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)) {
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt b/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt
index c41174a8..525ffb6e 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt
@@ -2,15 +2,23 @@ package com.codync.android
import android.Manifest
import android.os.Build
+import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.core.MutableTransitionState
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.interaction.MutableInteractionSource
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Text
@@ -22,11 +30,17 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler
+import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.paneTitle
+import androidx.compose.ui.semantics.selected
import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.codync.android.core.Bot
@@ -35,6 +49,8 @@ import com.codync.android.core.ConnectionRoute
import com.codync.android.core.HostRoute
import com.codync.android.core.LinkState
import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
@@ -48,20 +64,27 @@ import kotlinx.serialization.json.put
val signedIn = state.account.userId != null
val paired = state.computers.firstOrNull()
var confirmForget by remember { mutableStateOf(false) }
+ var confirmRevoke by remember { mutableStateOf<CloudComputer?>(null) }
+ var confirmRemoveCopy by remember { mutableStateOf<CloudComputer?>(null) }
+ var coloring by remember { mutableStateOf(false) }
var confirmStartOver by remember { mutableStateOf(false) }
var voice by remember { mutableStateOf(false) }
var aboutAnalytics by remember { mutableStateOf(false) }
LaunchedEffect(state.contextId) { store.refreshCloud() }
Column(Modifier.fillMaxSize().background(Palette.background)) {
PageHeader("Computers & settings", pop)
- CardForm(Modifier.weight(1f)) {
+ PullToRefresh(store::refreshComputers, Modifier.weight(1f)) { CardForm {
CardSection("Computers", if (signedIn) "Computers in your account need your OK on the computer before this phone can use them."
else "Each bot runs on its own computer. Sign in to see the computers in your account.") {
if (paired != null) row {
- ComputerRow(state, store, state.cloudComputers.any { it.computerId == paired.id }, extensions, store::openScreen) { confirmForget = true }
+ val inAccount = state.cloudComputers.firstOrNull { it.computerId == paired.id }
+ ComputerRow(state, store, inAccount != null, ComputerActions(extensions, store::openScreen, voice = { voice = true }, color = { coloring = true },
+ revoke = inAccount?.takeIf { it.access == "granted" }?.let { c -> { confirmRevoke = c } }) { confirmForget = true })
}
for (computer in state.cloudComputers.filter { it.computerId != paired?.id }) row {
- AccountComputerRow(computer, state.access?.takeIf { it.computerId == computer.computerId }?.code, canAsk = paired == null) { ask(computer) }
+ if (state.isOlderCopy(computer)) OlderCopyRow(computer) { confirmRemoveCopy = computer }
+ else AccountComputerRow(computer, state.access?.takeIf { it.computerId == computer.computerId }?.code, canAsk = paired == null,
+ ask = { ask(computer) }, revoke = { confirmRevoke = computer })
}
row {
Row(Modifier.fillMaxWidth().plainButton(action = pair), verticalAlignment = Alignment.CenterVertically,
@@ -110,9 +133,14 @@ import kotlinx.serialization.json.put
}
}
}
- }
+ } }
}
CodyncSheet(voice, { voice = false }) { VoiceChatSettings(state, store) }
+ SwatchPanel(coloring, paired?.color, { coloring = false }, store::setColor)
+ CodyncDialog("Remove the older ${confirmRemoveCopy?.name ?: "computer"}?", confirmRemoveCopy != null, { confirmRemoveCopy = null },
+ "It's this computer under an earlier identity and can't be reached anymore. Removing it only cleans up your account.") {
+ listOfNotNull(confirmRemoveCopy?.let { copy -> DialogAction("Remove", destructive = true) { store.removeFromAccount(copy.computerId) } })
+ }
CodyncSheet(aboutAnalytics, { aboutAnalytics = false }) { AnalyticsSheet() }
CodyncDialog("Start over?", confirmStartOver, { confirmStartOver = false },
"Signs out of every account and forgets every computer on this phone, then shows the welcome again. Your computers keep their bots and chats; pair again to use them.") {
@@ -122,6 +150,10 @@ import kotlinx.serialization.json.put
"Its bots and conversations stay on that computer. You can pair again any time.") {
listOf(DialogAction("Remove", destructive = true, action = store::forgetComputer))
}
+ CodyncDialog("Revoke this phone's access to ${confirmRevoke?.name ?: "the computer"}?", confirmRevoke != null, { confirmRevoke = null },
+ "You can ask for access again; the computer will show a new code to confirm.") {
+ listOfNotNull(confirmRevoke?.let { target -> DialogAction("Revoke", destructive = true) { store.revokeAccess(target.computerId) } })
+ }
}
/** Push on or off for this phone, and whether Android lets Codync show notifications at all. */
@@ -142,38 +174,47 @@ import kotlinx.serialization.json.put
}
}
+/** What the paired computer's row and its menu open; `revoke` is set when this phone's account access can be revoked. */
+private class ComputerActions(val extensions: () -> Unit, val screen: () -> Unit, val voice: () -> Unit, val color: () -> Unit,
+ val revoke: (() -> Unit)?, val remove: () -> Unit)
+
/** The paired computer: its connection, how it's reached, and whether it's in the account. */
-@Composable private fun ComputerRow(state: AppState, store: AppStore, inAccount: Boolean, extensions: () -> Unit, screen: () -> Unit,
- remove: () -> Unit) {
+@Composable private fun ComputerRow(state: AppState, store: AppStore, inAccount: Boolean, actions: ComputerActions) {
val computer = state.computers.first()
val link = state.connection
val online = link is LinkState.Ready
val viewable = online && state.screen != null
+ val stale = state.isStale
val detail = if (link is LinkState.Ready) {
val count = state.bots.count { !it.deleted && it.kind != "group" }
"$count bot${if (count == 1) "" else "s"} · ${if (link.route == HostRoute.Direct) "Wi-Fi/Tailscale" else "Cloudflare"}"
- } else connectionLabel(link)
+ } else computerStatusText(state)
Row(Modifier.fillMaxWidth().contextActions(items = {
listOfNotNull(
- if (online) MenuItem("Extensions", icon = "square.grid.2x2", action = extensions) else null,
- if (viewable) MenuItem("Screen", icon = "display", action = screen) else null,
- MenuItem("Remove", icon = "trash", destructive = true, divider = online, action = remove),
+ MenuItem("Color", icon = "paintpalette", action = actions.color),
+ if (online) MenuItem("Extensions", icon = "square.grid.2x2", action = actions.extensions) else null,
+ if (online) MenuItem("Voice chat", icon = "waveform", action = actions.voice) else null,
+ if (viewable) MenuItem("Screen", icon = "display", action = actions.screen) else null,
+ actions.revoke?.let { MenuItem("Revoke this phone's access", icon = "lock.slash", destructive = true, divider = true, action = it) },
+ MenuItem("Remove", icon = "trash", destructive = true, divider = actions.revoke == null, action = actions.remove),
)
}), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
- ComputerBadge(state.hello?.text("device"), 40.dp)
+ ComputerBadge(state.hello?.text("device"), 40.dp, computer.color)
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(state.hello?.text("name") ?: computer.name, style = Type.body.semibold, color = Palette.text, maxLines = 1)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
val ink = if (link is LinkState.ComputerOffline || link is LinkState.Failed) Palette.warning else Palette.secondary
- Text(detail, style = Type.subheadline, color = ink, maxLines = 1)
+ Text(detail, style = Type.subheadline, color = ink, maxLines = if (stale) 2 else 1, overflow = TextOverflow.Ellipsis)
if (link is LinkState.Ready) Symbol(if (link.route == HostRoute.Direct) "wifi" else "cloud", size = 14.dp, tint = ink,
contentDescription = if (link.route == HostRoute.Direct) "Wi-Fi or Tailscale" else "Through Cloudflare")
}
}
- if (online) IconButton("Extensions", "square.grid.2x2", action = extensions)
- if (viewable) IconButton("Screen", "display", action = screen)
+ if (online) IconButton("Extensions", "square.grid.2x2", action = actions.extensions)
+ if (viewable) IconButton("Screen", "display", action = actions.screen)
+ // Revoked, or this computer under an earlier identity: nothing to do but remove it.
+ if (stale) IconButton("Remove", "trash", action = actions.remove)
// Which route goes first, and whether Cloudflare is a fallback at all.
- DropdownMenu({ ConnectionRoute.entries.map { route -> MenuItem(route.title, icon = route.icon, selected = route == computer.route) { store.setRoute(route) } } },
+ else DropdownMenu({ ConnectionRoute.entries.map { route -> MenuItem(route.title, icon = route.icon, selected = route == computer.route) { store.setRoute(route) } } },
Modifier.size(36.dp), label = "Connection") {
Symbol(computer.route.icon, size = 21.dp, tint = Palette.secondary)
}
@@ -182,11 +223,11 @@ import kotlinx.serialization.json.put
}
/** A computer in the account that this phone can't use yet. */
-@Composable private fun AccountComputerRow(computer: CloudComputer, code: String?, canAsk: Boolean, ask: () -> Unit) {
+@Composable private fun AccountComputerRow(computer: CloudComputer, code: String?, canAsk: Boolean, ask: () -> Unit, revoke: () -> Unit) {
val online = if (computer.online == true) "Online" else "Offline"
val detail = when {
code != null -> "Waiting for your OK on the computer · $code"
- computer.access == "granted" -> "Approved for an earlier install of Codync. Ask again to use it here."
+ computer.access == "granted" -> "Approved for an earlier install of Codync. Revoke it, then ask again."
computer.access == "pending" -> "$online · A request is waiting"
canAsk -> "$online · In your account"
// One computer per phone for now: the paired one goes first.
@@ -198,7 +239,24 @@ import kotlinx.serialization.json.put
Text(computer.name, style = Type.body.semibold, color = Palette.text, maxLines = 1)
Text(detail, style = Type.subheadline, color = Palette.secondary, maxLines = 2)
}
- SecondaryButton(if (code != null) "Code" else "Ask for access", enabled = code != null || canAsk, action = ask)
+ when {
+ code != null -> SecondaryButton("Code", action = ask)
+ computer.access == "granted" -> SecondaryButton("Revoke", action = revoke)
+ else -> SecondaryButton("Ask for access", enabled = canAsk, action = ask)
+ }
+ }
+}
+
+/** The same machine under an earlier identity: one tap cleans it out of the account. */
+@Composable private fun OlderCopyRow(computer: CloudComputer, remove: () -> Unit) {
+ val seen = computer.lastSeenAt?.let { " · last seen ${RelativeTime.day(it)}" }.orEmpty()
+ Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Box(Modifier.graphicsLayer { alpha = 0.35f }) { ComputerBadge(computer.device, 40.dp) }
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(computer.name, style = Type.body.semibold, color = Palette.secondary, maxLines = 1)
+ Text("Older copy of this computer$seen", style = Type.subheadline, color = Palette.tertiary, maxLines = 2)
+ }
+ IconButton("Remove from account", "trash", action = remove)
}
}
@@ -215,13 +273,45 @@ import kotlinx.serialization.json.put
}
}
-/** A computer's icon showing what it is (laptop, desktop, Linux), as CodyncUI `ComputerBadge`. */
-@Composable internal fun ComputerBadge(device: String?, size: Dp) {
+/** A computer's icon showing what it is (laptop, Mac mini, Linux…) in the color picked for it, as CodyncUI `ComputerBadge`. */
+@Composable internal fun ComputerBadge(device: String?, size: Dp, color: String? = null) {
+ val tint = color?.let(AvatarPalette::tint) ?: Palette.text
Box(Modifier.size(size), contentAlignment = Alignment.Center) {
- when (device) {
- "linux" -> Symbol("computer.linux", size = size * 0.55f, tint = Palette.text)
- "laptop" -> Symbol("laptopcomputer", size = size * 0.6f, tint = Palette.text)
- else -> Symbol("desktopcomputer", size = size * 0.6f, tint = Palette.text)
+ if (device == "linux") Symbol("computer.linux", size = size * 0.55f, tint = tint)
+ else Symbol(when (device) {
+ "laptop" -> "laptopcomputer"
+ "macmini" -> "macmini"
+ "macstudio" -> "macstudio"
+ "macpro" -> "macpro.gen3"
+ else -> "desktopcomputer"
+ }, size = size * 0.6f, tint = tint)
+ }
+}
+
+/** The computer color choices over the dimmed app: a grid of colored dots, the current one checked. */
+@Composable private fun SwatchPanel(isPresented: Boolean, selected: String?, close: () -> Unit, pick: (String) -> Unit) {
+ val visible = remember { MutableTransitionState(false) }
+ visible.targetState = isPresented
+ if (!visible.currentState && !visible.targetState) return
+ BackHandler(isPresented, close)
+ Overlay {
+ AnimatedVisibility(visible, enter = fadeIn(Motion.layout()), exit = fadeOut(Motion.fade())) {
+ Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.35f)).clickable(remember { MutableInteractionSource() }, null, onClick = close),
+ contentAlignment = Alignment.Center) {
+ Column(Modifier.graphicsLayer { shadowElevation = 24f; shape = RoundedRectangle(22.dp); clip = true }.background(Palette.bubbleAgent)
+ .clickable(remember { MutableInteractionSource() }, null) {}.semantics { paneTitle = "Color" }.padding(14.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ for (swatches in AvatarPalette.colors.entries.chunked(6)) Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ for ((id, hex) in swatches) Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) {
+ Box(Modifier.size(32.dp).clip(Capsule()).background(Color(hex)).clickable(role = Role.RadioButton) { close(); pick(id) }
+ .semantics { contentDescription = id.replaceFirstChar(Char::uppercase); this.selected = id == selected },
+ contentAlignment = Alignment.Center) {
+ if (id == selected) Symbol("checkmark", size = 13.dp, tint = Color.White)
+ }
+ }
+ }
+ }
+ }
}
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/StateScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/StateScreen.kt
index f3ecf74a..070ba2d8 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/StateScreen.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/StateScreen.kt
@@ -117,7 +117,7 @@ internal fun openNotificationSettings(context: Context) = context.startActivity(
val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { asked++; store?.syncPush() }
var kind by rememberSaveable { mutableStateOf("usage") }
var provider by rememberSaveable { mutableStateOf("claude") }
- var size by rememberSaveable { mutableStateOf("medium") }
+ var sizeChoice by rememberSaveable { mutableStateOf("medium") }
var pinFailed by remember { mutableStateOf(false) }
Row(Modifier.fillMaxWidth().clip(RoundedRectangle(22.dp)).background(Palette.surface).padding(16.dp),
@@ -155,14 +155,17 @@ internal fun openNotificationSettings(context: Context) = context.startActivity(
Box(Modifier.weight(1f)) { SectionLabel("Choose your widget") }
Text("Sample data", style = Type.caption2, color = Palette.secondary)
}
- SegmentedChoice(kind, listOf("usage" to "Provider usage", "bots" to "Bots", "team" to "Team"), { kind = it })
+ ChoicePicker(kind, listOf("usage" to "Provider usage", "limits" to "Usage limits", "bots" to "Bots", "team" to "Team"), { kind = it })
val report = remember(state.usage) { runCatching { UsageReport.decode(state.usage) }.getOrNull() }
val providers = (WidgetPreview.usage.providers + report?.providers.orEmpty()).distinctBy { it.id }
if (kind == "usage") {
if (providers.size <= 3) SegmentedChoice(provider, providers.map { it.id to it.name }, { provider = it })
else ChoicePicker(provider, providers.map { it.id to it.name }, { provider = it })
}
- if (kind != "team") ChoicePicker(size, listOf("small" to "Small", "medium" to "Medium", "large" to "Large"), { size = it })
+ // Usage limits comes small and medium, as on iOS.
+ val sizes = listOf("small" to "Small", "medium" to "Medium", "large" to "Large").take(if (kind == "limits") 2 else 3)
+ val size = sizeChoice.takeIf { shown -> sizes.any { it.first == shown } } ?: "medium"
+ if (kind != "team") ChoicePicker(size, sizes, { picked -> sizeChoice = picked })
Column(Modifier.fillMaxWidth().clip(RoundedRectangle(26.dp)).background(Palette.bubbleAgent).padding(14.dp),
verticalArrangement = Arrangement.spacedBy(18.dp), horizontalAlignment = Alignment.CenterHorizontally) {
val small = size == "small" || kind == "team"
@@ -174,6 +177,7 @@ internal fun openNotificationSettings(context: Context) = context.startActivity(
"usage" -> providers.firstOrNull { it.id == provider }?.let {
ProviderWidgetCard(it, if (size == "large") ProviderLayout.Large else if (size == "medium") ProviderLayout.Medium else ProviderLayout.Small)
}
+ "limits" -> UsageLimitsCard(WidgetPreview.usage, wide = size != "small")
"team" -> BotsTeamCard(teamSlots(WidgetPreview.bots, emptyList()))
else -> BotsWidgetCard(WidgetPreview.bots, WidgetPreview.activities, wide = size != "small", large = size == "large")
}
@@ -182,6 +186,7 @@ internal fun openNotificationSettings(context: Context) = context.startActivity(
Text(if (kind == "team") "Small widget" else "${size.replaceFirstChar(Char::uppercase)} widget", style = Type.subheadline.medium, color = Palette.text)
Text(when (kind) {
"usage" -> "Small shows the tightest limit. Medium shows two windows. Large adds a summary and up to four limits."
+ "limits" -> "Every provider's limits in one widget. The tightest leads; small shows two more and medium up to four."
"team" -> "Four bots as characters with a dot for each one at work; the bots that need you come first."
else -> "See who needs you and who's still working. Large shows up to six bots."
}, style = Type.caption, color = Palette.secondary)
@@ -207,7 +212,7 @@ internal fun openNotificationSettings(context: Context) = context.startActivity(
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
SectionLabel("Add a widget")
- val kindToPin = when (kind) { "usage" -> WidgetKind.Provider; "team" -> WidgetKind.Team; else -> WidgetKind.Bots }
+ val kindToPin = when (kind) { "usage" -> WidgetKind.Provider; "limits" -> WidgetKind.Usage; "team" -> WidgetKind.Team; else -> WidgetKind.Bots }
if (AppWidgetManager.getInstance(context).isRequestPinAppWidgetSupported)
PrimaryButton("Add to Home Screen") { pinFailed = !CodyncWidgets.pin(context, kindToPin) }
if (pinFailed) Text("Your launcher couldn't add it. Add it from the Home Screen instead.", style = Type.footnote, color = Palette.danger)
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.kt
index bc574191..d4c0898d 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.kt
@@ -17,10 +17,7 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
-import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
-import androidx.compose.material3.pulltorefresh.PullToRefreshBox
-import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
@@ -33,7 +30,6 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
-import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.codync.android.core.LinkState
@@ -51,8 +47,7 @@ import kotlin.math.roundToInt
* Usage limits, opened from the State tab (iOS `UsageSheet` + `UsageView`): one card per
* provider, the tightest limit as a big bar, every limit listed below. Pull down to refresh.
*/
-@OptIn(ExperimentalMaterial3Api::class)
-@Composable fun UsageScreen(state: AppState, refresh: (force: Boolean) -> Unit) {
+@Composable fun UsageScreen(state: AppState, refresh: (force: Boolean) -> Unit, reload: suspend () -> Unit) {
val dismiss = LocalDismissModal.current
val report = remember(state.usage) { runCatching { UsageReport.decode(state.usage) }.getOrNull() ?: UsageReport() }
val online = state.actualConnection is LinkState.Ready
@@ -65,10 +60,7 @@ import kotlin.math.roundToInt
EmptyUsage("No computer yet", "Usage shows up once a computer is connected.")
return@Column
}
- val pull = rememberPullToRefreshState()
- PullToRefreshBox("usage" in state.busy, { if (online) refresh(true) }, Modifier.weight(1f), state = pull,
- indicator = { Box(Modifier.align(Alignment.TopCenter).padding(top = 12.dp).graphicsLayer {
- alpha = if ("usage" in state.busy) 1f else pull.distanceFraction.coerceIn(0f, 1f) }) { Spinner(18.dp) } }) {
+ PullToRefresh({ if (online) reload() }, Modifier.weight(1f)) {
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
for (provider in report.providers) key(provider.id) { ProviderCard(provider) }
if (report.providers.isEmpty()) EmptyUsage("No usage yet", "Your computer reads the limits from Claude Code and Codex.")
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt b/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt
index 7aa6dd8c..72693d0f 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt
@@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
@@ -31,10 +32,12 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
+import com.codync.android.core.ProviderLimit
import com.codync.android.core.UsageProvider
import com.codync.android.core.UsageReport
import com.codync.android.core.UsageWindow
import com.codync.android.core.WidgetBot
+import com.codync.android.core.usageLimits
import com.codync.android.design.*
import com.kyant.shapes.Capsule
import com.kyant.shapes.RoundedRectangle
@@ -152,6 +155,44 @@ internal fun until(at: Long, now: Long): String {
}
}
+/** Every provider's limits: the tightest is the headline, the rest thin bars that take color near the limit (iOS `UsageWidgetView`). */
+@Composable internal fun UsageLimitsCard(report: UsageReport, wide: Boolean) {
+ val limits = usageLimits(report)
+ val top = limits.firstOrNull() ?: return
+ val rest = limits.drop(1)
+ if (wide) Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(18.dp)) {
+ Box(Modifier.width(118.dp)) { LimitHero(top) }
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(9.dp)) { for (limit in rest.take(4)) LimitBar(limit) }
+ } else Column(Modifier.fillMaxSize()) {
+ LimitHero(top)
+ Spacer(Modifier.weight(1f).heightIn(min = 6.dp))
+ Column(verticalArrangement = Arrangement.spacedBy(7.dp)) { for (limit in rest.take(2)) LimitBar(limit) }
+ }
+}
+
+@Composable private fun LimitHero(limit: ProviderLimit) {
+ val percent = limit.window.percent ?: 0.0
+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text("${limit.provider} · ${limit.window.label}", style = Type.caption, color = Palette.secondary, maxLines = 1)
+ Text("${percent.roundToInt()}%", style = Type.system(34f).semibold.monospacedDigit, color = if (percent >= 90) Palette.danger else Palette.text, maxLines = 1)
+ Text(limit.window.resetsShort() ?: " ", style = Type.caption2, color = Palette.tertiary, maxLines = 1)
+ }
+}
+
+@Composable private fun LimitBar(limit: ProviderLimit) {
+ val percent = limit.window.percent ?: 0.0
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Row {
+ Text("${limit.provider} ${limit.window.label}", Modifier.weight(1f), style = Type.caption2, color = Palette.secondary, maxLines = 1)
+ Text("${percent.roundToInt()}%", style = Type.caption2.monospacedDigit, color = Palette.secondary)
+ }
+ UsageTicks(percent, usageTint(percent), 10.dp)
+ }
+}
+
+/** "How full is this limit" (CodyncKit `Palette.usageTint`). */
+@Composable private fun usageTint(percent: Double): Color = if (percent >= 90) Palette.danger else if (percent >= 70) Palette.warning else Palette.accent
+
/** The state word the widgets show and its color: only what needs you (or failed) stands out. */
@Composable internal fun widgetState(status: String): Pair<String, Color> = when (status) {
"needsInput" -> "Needs you" to Palette.attention
diff --git a/apps/android/app/src/main/res/values/widget.xml b/apps/android/app/src/main/res/values/widget.xml
index ba8a0036..36442558 100644
--- a/apps/android/app/src/main/res/values/widget.xml
+++ b/apps/android/app/src/main/res/values/widget.xml
@@ -4,6 +4,7 @@
<string name="widget_bots_description">Latest bot status and unread counts</string>
<string name="widget_team_description">Four bots as characters, the ones that need you first</string>
<string name="widget_provider_description">Latest limits from your selected provider</string>
+ <string name="widget_usage_description">Subscription limits your computer reports, for every provider</string>
<color name="widget_background">#F8F8F8</color>
<color name="widget_foreground">#111111</color>
<color name="widget_secondary">#666666</color>
diff --git a/apps/android/app/src/main/res/xml/widget_usage.xml b/apps/android/app/src/main/res/xml/widget_usage.xml
new file mode 100644
index 00000000..e2e9927c
--- /dev/null
+++ b/apps/android/app/src/main/res/xml/widget_usage.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
+ android:minWidth="110dp" android:minHeight="110dp" android:minResizeWidth="110dp" android:minResizeHeight="110dp"
+ android:targetCellWidth="2" android:targetCellHeight="2" android:resizeMode="horizontal|vertical"
+ android:updatePeriodMillis="1800000" android:initialLayout="@layout/widget_loading"
+ android:description="@string/widget_usage_description" android:previewLayout="@layout/widget_loading"
+ android:widgetCategory="home_screen" />
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/ComposerAttachmentTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/ComposerAttachmentTest.kt
new file mode 100644
index 00000000..e54f61a6
--- /dev/null
+++ b/apps/android/app/src/test/kotlin/com/codync/android/ComposerAttachmentTest.kt
@@ -0,0 +1,24 @@
+package com.codync.android
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class ComposerAttachmentTest {
+ @Test fun `paste is offered for images and other uris, not for text`() {
+ assertTrue(clipOffersFiles(listOf("image/png")))
+ assertTrue(clipOffersFiles(listOf("application/pdf")))
+ assertTrue(clipOffersFiles(listOf("text/uri-list")))
+ assertFalse(clipOffersFiles(listOf("text/plain")))
+ assertFalse(clipOffersFiles(listOf("text/plain", "text/html")))
+ assertFalse(clipOffersFiles(emptyList()))
+ }
+
+ @Test fun `file chips use the symbol of the file's kind`() {
+ assertEquals("photo", AttachmentIcon.symbol("shot.PNG"))
+ assertEquals("doc.richtext", AttachmentIcon.symbol("paper.pdf"))
+ assertEquals("doc.zipper", AttachmentIcon.symbol("logs.tar"))
+ assertEquals("film", AttachmentIcon.symbol("clip.mov"))
+ assertEquals("waveform", AttachmentIcon.symbol("memo.m4a"))
+ assertEquals("doc", AttachmentIcon.symbol("README"))
+ }
+}
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt
index 12bfd4f5..b54f4dbb 100644
--- a/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt
+++ b/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt
@@ -1,43 +1,78 @@
package com.codync.android
import com.codync.android.core.*
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
import org.junit.Assert.*
import org.junit.Test
class ConnectionPresentationTest {
- private val computer = Computer("fixture", "Computer", "fixture")
- private fun state(link: LinkState, loaded: Boolean = false) = AppState(
+ private val computer = Computer("fixture", "Studio", "fixture")
+ private fun state(link: LinkState, cloud: List<CloudComputer> = emptyList(), computers: List<Computer> = listOf(computer)) = AppState(
account = AccountState(configured = false), loading = false, setupComplete = true,
- computers = listOf(computer), connection = link, actualConnection = link, rosterLoaded = loaded)
-
- @Test fun anUnreachableComputerIsNotAnEmptyRoster() {
- for (loaded in listOf(false, true)) {
- val empty = emptyRoster(state(LinkState.ComputerOffline(null), loaded), "", false)
- assertEquals("Computer offline", empty.title)
- assertFalse(empty.canCreate)
- assertNotNull(empty.detail)
+ computers = computers, connection = link, actualConnection = link, cloudComputers = cloud)
+ private fun cloud(id: String, online: Boolean, name: String = "Studio") = CloudComputer(id, name, "key", online = online)
+
+ @Test fun eachConnectionReadsAsOnIPhone() {
+ val revoked = LinkState.Failed("This device isn't allowed on Studio anymore.", 403)
+ val cases = listOf(
+ LinkState.Ready(HostRoute.Relay) to Triple("Online", "Connected", "Connected through Cloudflare"),
+ LinkState.Ready(HostRoute.Direct) to Triple("Online", "Connected", "Connected over Wi-Fi or Tailscale"),
+ LinkState.Connecting to Triple("Connecting…", "Connecting…", "Connecting"),
+ LinkState.ComputerOffline(null) to Triple("Offline", "Offline", "Offline"),
+ LinkState.Failed("Connection closed.") to Triple("Can't reach", "Offline", "Offline"),
+ revoked to Triple(revoked.message, "No access", "No access"),
+ )
+ for ((link, words) in cases) {
+ assertEquals(words.first, statusText(state(link)))
+ assertEquals(words.second, connectionLabel(state(link)))
+ assertEquals(words.third, connectionDescription(state(link)))
}
+ val unpaired = state(LinkState.Connecting, computers = emptyList())
+ assertEquals("Not paired", statusText(unpaired))
+ assertEquals("Not paired", connectionLabel(unpaired))
+ assertEquals("Not paired", connectionDescription(unpaired))
}
- @Test fun accessAndCompatibilityFailuresKeepTheirActionableMessage() {
- for ((status, title) in listOf(403 to "Access denied", 426 to "Update required", 500 to "Disconnected")) {
- val link = LinkState.Failed("Actionable host error", status)
- assertEquals(title, connectionLabel(link))
- val empty = emptyRoster(state(link), "", false)
- assertEquals(title, empty.title)
- assertEquals(link.message, empty.detail)
- assertFalse(empty.canCreate)
- }
+ @Test fun anOfflineComputerSaysWhenItWasLastSeen() {
+ val seen = System.currentTimeMillis() - 60_000
+ assertEquals("Offline · seen ${RelativeTime.day(seen)}", statusText(state(LinkState.ComputerOffline(seen))))
+ }
+
+ @Test fun aComputerBehindTheAppNeedsAnUpdate() {
+ val online = state(LinkState.Ready(HostRoute.Direct)).copy(hello = buildJsonObject { put("version", "2.0.0"); put("minApp", "2.0.0") })
+ assertEquals("Needs update", statusText(online))
+ assertEquals("Needs update", connectionLabel(online))
+ assertEquals("Needs update", connectionDescription(online))
+ }
+
+ @Test fun theHeaderSummarizesTheComputers() {
+ assertEquals("1 connected", connectionSummary(state(LinkState.Ready(HostRoute.Direct))))
+ assertEquals("Connecting…", connectionSummary(state(LinkState.Connecting)))
+ assertEquals("No access", connectionSummary(state(LinkState.Failed("Revoked", 403))))
+ assertEquals("1 offline", connectionSummary(state(LinkState.ComputerOffline(null))))
+ assertEquals("Computers", connectionSummary(state(LinkState.Connecting, computers = emptyList())))
+ }
+
+ @Test fun aComputerTurningThisPhoneAwayOrReplacedByANewIdentityIsStale() {
+ assertTrue(state(LinkState.Failed("Revoked", 403)).isStale)
+ val offline = state(LinkState.ComputerOffline(null), listOf(cloud("new", online = true)))
+ assertTrue(offline.isStale)
+ assertEquals("Older copy of this computer · Offline", computerStatusText(offline))
+ assertFalse(state(LinkState.ComputerOffline(null), listOf(cloud("new", online = false))).isStale)
+ assertFalse(state(LinkState.Ready(HostRoute.Direct), listOf(cloud("new", online = true))).isStale)
+ assertEquals("Revoked", computerStatusText(state(LinkState.Failed("Revoked", 403), listOf(cloud("new", online = true)))))
}
- @Test fun creationWaitsForAnAuthoritativeOnlineRoster() {
- val online = state(LinkState.Ready(HostRoute.Direct))
- assertEquals("Syncing bots…", emptyRoster(online, "", false).title)
- val loaded = online.copy(rosterLoaded = true)
- assertTrue(emptyRoster(loaded, "", false).canCreate)
- assertFalse(emptyRoster(loaded.copy(actualConnection = LinkState.Connecting), "", false).canCreate)
- assertEquals("No matching bots", emptyRoster(loaded, "missing", false).title)
- assertEquals("No hidden bots", emptyRoster(loaded, "", true).title)
- assertFalse(emptyRoster(loaded, "", true).canCreate)
+ @Test fun anOfflineAccountComputerNamedLikeTheCurrentOneIsAnOlderCopy() {
+ val old = cloud("old", online = false)
+ assertTrue(state(LinkState.Connecting, listOf(old)).isOlderCopy(old))
+ assertFalse(state(LinkState.Connecting, listOf(old.copy(online = true))).isOlderCopy(old.copy(online = true)))
+ assertFalse(state(LinkState.Connecting, listOf(old), computers = emptyList()).isOlderCopy(old))
+ val renamed = cloud("old", online = false, name = "Laptop")
+ assertFalse(state(LinkState.Connecting, listOf(renamed)).isOlderCopy(renamed))
+ // Not paired here, but the new identity is online in the account.
+ val accountOnly = state(LinkState.Connecting, listOf(old, cloud("new", online = true)), computers = emptyList())
+ assertTrue(accountOnly.isOlderCopy(old))
}
}
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/ReadingTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/ReadingTest.kt
new file mode 100644
index 00000000..e178f024
--- /dev/null
+++ b/apps/android/app/src/test/kotlin/com/codync/android/ReadingTest.kt
@@ -0,0 +1,32 @@
+package com.codync.android
+
+import com.codync.android.core.Bot
+import com.codync.android.core.Entry
+import com.codync.android.core.MirrorEvent
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class ReadingTest {
+ private val main = ReadingScope("bot", null)
+ private val thread = ReadingScope("bot", "root")
+
+ private fun message(thread: String?, kind: String = "user", bot: String = "bot") =
+ MirrorEvent.EntryChanged(Entry("e", 1, bot, thread, 1, kind, data = buildJsonObject { put("text", "hi") }))
+
+ @Test fun `the chat stays read under its thread and Full conversation`() {
+ assertEquals(listOf(main, thread), AppState(selectedBot = "bot", thread = "root", trace = true).readingScopes)
+ assertEquals(listOf(main), AppState(selectedBot = "bot").readingScopes)
+ assertEquals(emptyList<ReadingScope>(), AppState().readingScopes)
+ }
+
+ @Test fun `a message is read where it lands, and a bot counting unread reads all it shows`() {
+ val scopes = listOf(main, thread)
+ assertEquals(listOf(thread), readAfter(listOf(message("root")), scopes))
+ assertEquals(listOf(main), readAfter(listOf(message(null)), scopes))
+ assertEquals(emptyList<ReadingScope>(), readAfter(listOf(message(null, kind = "tool"), message(null, bot = "other")), scopes))
+ assertEquals(scopes, readAfter(listOf(MirrorEvent.BotChanged(Bot("bot", unread = 2))), scopes))
+ assertEquals(emptyList<ReadingScope>(), readAfter(listOf(MirrorEvent.BotChanged(Bot("bot", unread = 0))), scopes))
+ }
+}
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/RosterMoveTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/RosterMoveTest.kt
new file mode 100644
index 00000000..da5a533c
--- /dev/null
+++ b/apps/android/app/src/test/kotlin/com/codync/android/RosterMoveTest.kt
@@ -0,0 +1,21 @@
+package com.codync.android
+
+import com.codync.android.core.Bot
+import org.junit.Assert.*
+import org.junit.Test
+
+class RosterMoveTest {
+ private val roster = listOf(Bot("pin", pinned = true), Bot("a"), Bot("b"), Bot("c"))
+
+ @Test fun moveUpAndDownSwapWithTheNeighbor() {
+ assertEquals(listOf("pin", "b", "a", "c"), moved(roster, "b", -1))
+ assertEquals(listOf("pin", "a", "c", "b"), moved(roster, "b", 1))
+ }
+
+ @Test fun aBotStaysAmongBotsWithItsPinStateAndInsideTheList() {
+ assertNull(moved(roster, "a", -1))
+ assertNull(moved(roster, "pin", 1))
+ assertNull(moved(roster, "c", 1))
+ assertNull(moved(roster, "missing", 1))
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt
index 9c7821b3..237b01c2 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt
@@ -95,6 +95,19 @@ class CloudClient private constructor(base: String, private val identity: Device
} finally { nonce.fill(0) }
}
+ /** Takes back this device's grants on a computer, including one approved for an earlier install. */
+ suspend fun revokeAccess(computerId: String) {
+ val devices = request("GET", listOf("v1", "devices")).getValue("devices").jsonArray.map { it.jsonObject }
+ val device = devices.firstOrNull { it.text("deviceKey") == identity.publicKey }?.text("deviceId") ?: return
+ val grants = request("GET", listOf("v1", "computers", computerId, "grants")).getValue("grants").jsonArray.map { it.jsonObject }
+ for (grant in grants.filter { it.text("deviceId") == device }) {
+ request("DELETE", listOf("v1", "computers", computerId, "grants", requireNotNull(grant.text("grantId")) { "Invalid grant" }))
+ }
+ }
+
+ /** Takes a computer out of the account; its grants and pending requests go with it. */
+ suspend fun removeComputer(id: String) { request("DELETE", listOf("v1", "computers", id)) }
+
suspend fun accessStatus(id: String): AccessStatus {
val result = request("GET", listOf("v1", "access-requests", id))
return json.decodeFromJsonElement(result)
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt
index 5419bf8c..cef22741 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt
@@ -12,6 +12,8 @@ data class Computer(
val urls: List<String> = emptyList(),
val cloud: String? = null,
val route: ConnectionRoute = ConnectionRoute.Automatic,
+ /** The badge color picked on this phone (an `AvatarPalette` id). */
+ val color: String? = null,
) {
fun validate() {
require(RelayCrypto.computerId(signKey.decodeBase64Url(32)) == id) { "This computer's identity changed. Pair it again." }
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt
index deb099b6..3fd923f7 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt
@@ -28,6 +28,8 @@ data class Entry(
val text: String get() = data.text("text").orEmpty()
val clientNonce: String? get() = data.text("clientNonce")
val status: String? get() = data.text("status")
+ /** Files the bot shared in this message. */
+ val files: List<SharedFile> get() = data["files"]?.let { WireJson.decodeFromJsonElement<List<SharedFile>>(it) }.orEmpty()
val isChat: Boolean get() = kind in listOf("user", "permission", "notice") ||
kind == "agent" && data["final"]?.jsonPrimitive?.booleanOrNull == true
@@ -56,7 +58,8 @@ private data class EntryFields(
val final: Boolean? = null, val title: String? = null, val command: String? = null,
val detail: String? = null, val output: String? = null, val author: String? = null,
val options: List<PermissionChoice>? = null, val reactions: List<String>? = null,
- val thread: ReplySummary? = null, val attachments: List<Attachment>? = null, val callSeconds: Long? = null,
+ val thread: ReplySummary? = null, val attachments: List<Attachment>? = null, val files: List<SharedFile>? = null,
+ val callSeconds: Long? = null,
)
@Serializable private data class PermissionChoice(val optionId: String, val name: String, val kind: String)
@Serializable private data class ReplySummary(val count: Int)
@@ -64,6 +67,19 @@ private data class EntryFields(
val isImage: Boolean get() = name.substringAfterLast('.', "").lowercase() in listOf("png", "jpg", "jpeg", "heic", "gif", "webp", "tiff", "bmp")
}
+/** A file a bot shared: immutable on the computer, checked against its SHA-256 once downloaded. */
+@Serializable data class SharedFile(val id: String, val name: String, val size: Long, val sha256: String) {
+ /** Before any of it is read: a name that can't leave its folder and a hash to check. */
+ fun validate() {
+ require(size in 0..MAX_FILE_BYTES && sha256.length == 64 && sha256.all { it in "0123456789abcdef" } &&
+ name.isNotEmpty() && name.toByteArray(Charsets.UTF_8).size <= 200 && name != "." && name != ".." &&
+ '/' !in name && '\\' !in name && name.codePoints().noneMatch { Character.getType(it).toByte() in CONTROLS }) { "Invalid file metadata." }
+ }
+}
+
+/** Unicode control and format characters, which a file name may not contain. */
+private val CONTROLS = setOf(Character.CONTROL, Character.FORMAT)
+
@Serializable
enum class SendStatus { Sending, Waiting, Delivering, Failed }
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
index f832a369..2814189f 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
@@ -57,6 +57,10 @@ data class Bot(
/** Why Fast mode isn't in effect, when the agent turned it off itself. */
val fastModeRefusal: String? get() = if (fastMode && fastModeSupport == "refused")
"The agent turned it off: ${fastModeIssue ?: "not available"}. Switch it off and on to try again." else null
+
+ /** Working right now in this chat's main conversation (`thread == null`) or in that thread. */
+ fun isWorking(chat: String, thread: String?): Boolean =
+ status in listOf("working", "needsInput") && (workingChat ?: id) == chat && workingThread == thread
}
object HostClient {
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/HostFiles.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostFiles.kt
index c720e1c2..0c8e053d 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/HostFiles.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostFiles.kt
@@ -2,8 +2,10 @@ package com.codync.android.core
import java.io.File
import java.io.IOException
+import java.security.MessageDigest
import java.util.Base64
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.*
@@ -62,6 +64,45 @@ class HostFiles(private val call: suspend (String, JsonObject, Long) -> JsonElem
} finally { partial.delete() }
}
+ /**
+ * A file a bot shared (iOS `FileDownload.save`), read chunk by chunk into its own new `folder`,
+ * checked against its SHA-256, then moved to `folder/ready/<name>`. Any failure removes the folder.
+ */
+ suspend fun downloadShared(entryId: String, file: SharedFile, folder: File, progress: (Long) -> Unit = {}): File = withContext(Dispatchers.IO) {
+ file.validate()
+ if (!folder.mkdirs()) throw IOException("Couldn't prepare the download.")
+ var saved = false
+ try {
+ val partial = File(folder, ".download-partial")
+ val hash = MessageDigest.getInstance("SHA-256")
+ partial.outputStream().use { output ->
+ var offset = 0L
+ do {
+ ensureActive()
+ val chunk = call("readFile", buildJsonObject { put("entryId", entryId); put("fileId", file.id); put("offset", offset) }, 60_000).jsonObject
+ val data = chunk["data"]?.jsonPrimitive?.contentOrNull
+ val bytes = if (chunk["size"]?.jsonPrimitive?.longOrNull == file.size && data != null && data.length <= CHUNK_BYTES / 3 * 4)
+ try { Base64.getDecoder().decode(data) } catch (_: IllegalArgumentException) { null } else null
+ if (bytes == null || bytes.size.toLong() != minOf(CHUNK_BYTES.toLong(), file.size - offset)) {
+ throw IOException("The download was truncated or changed. Retry the download.")
+ }
+ output.write(bytes)
+ hash.update(bytes)
+ offset += bytes.size
+ progress(offset)
+ } while (offset < file.size)
+ output.fd.sync()
+ }
+ if (hash.digest().joinToString("") { "%02x".format(it) } != file.sha256) throw IOException("The file integrity check failed. Retry the download.")
+ ensureActive()
+ // A name like .download-partial stays valid: the finished file lives in its own folder.
+ val destination = File(File(folder, "ready").apply { mkdirs() }, file.name)
+ if (!partial.renameTo(destination)) throw IOException("Couldn't save the downloaded file.")
+ saved = true
+ destination
+ } finally { if (!saved) folder.deleteRecursively() }
+ }
+
/** A small text file the host prepared (a memory export), read chunk by chunk. */
suspend fun readText(botId: String, id: String): String {
val bytes = java.io.ByteArrayOutputStream()
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/PushAlert.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/PushAlert.kt
new file mode 100644
index 00000000..13280805
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/PushAlert.kt
@@ -0,0 +1,33 @@
+package com.codync.android.core
+
+import kotlinx.serialization.Serializable
+
+/** The private alert the host seals to this phone's push key (spec §6.7). */
+@Serializable data class PushAlert(
+ val title: String,
+ /** What happened: "Task complete", "Response needed" or "Task failed". */
+ val subtitle: String? = null,
+ val body: String,
+ /** The member bot speaking, when the alert is for a group chat. */
+ val from: String? = null,
+ /** The chat, its first members and the speaker: names and avatars only, sent with the alert
+ * so a bot the phone hasn't seen yet still shows its face. */
+ val faces: List<Bot> = emptyList(),
+) {
+ /** Who the alert is from, for a conversation notification; null when no face came for the chat. */
+ fun conversation(botId: String): AlertConversation? {
+ val chat = faces.firstOrNull { it.id == botId } ?: return null
+ val members = chat.members.mapNotNull { id -> faces.firstOrNull { it.id == id } }
+ val speaker = faces.firstOrNull { it.id == from }.takeIf { chat.kind == "group" }
+ return AlertConversation(chat, members, speaker)
+ }
+
+ companion object {
+ fun decode(plain: String): PushAlert = WireJson.decodeFromString<PushAlert>(plain).run {
+ copy(title = title.take(120), subtitle = subtitle?.take(120), body = body.take(400), faces = faces.take(8))
+ }
+ }
+}
+
+/** A chat's alert: the chat, its members the alert carried a face for, and in a group the member speaking. */
+data class AlertConversation(val chat: Bot, val members: List<Bot>, val speaker: Bot?)
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/WidgetFeed.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/WidgetFeed.kt
index de779cf6..f988db58 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/WidgetFeed.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/WidgetFeed.kt
@@ -10,7 +10,20 @@ import kotlinx.serialization.Serializable
val computerName: String = "", val bots: List<WidgetBot> = emptyList(), val botsAt: Long = 0,
val usage: UsageReport = UsageReport(), val usageAt: Long = 0)
-enum class WidgetKind { Provider, Bots, Team }
+enum class WidgetKind { Provider, Usage, Bots, Team }
+
+/** A limit in the Usage limits widget, named with its provider. */
+data class ProviderLimit(val provider: String, val window: UsageWindow)
+
+/** Every provider's limits for the Usage limits widget: the tightest first (its headline), then the rest in report order. */
+fun usageLimits(report: UsageReport): List<ProviderLimit> {
+ val all = report.providers.flatMap { provider -> provider.windows.map { ProviderLimit(provider.name, it) } }
+ val top = all.withIndex().maxByOrNull { it.value.window.reportedPercent ?: -1.0 } ?: return emptyList()
+ return listOf(top.value) + all.filterIndexed { index, _ -> index != top.index }
+}
+
+/** The Bots tile's bot: the one that needs you most, in the feed's order, if any bot is at work. */
+fun leadBot(bots: List<WidgetBot>): WidgetBot? = bots.firstOrNull { it.status == "needsInput" || it.status == "working" }
/** The Team widget's four spots: the picked bots first (a deleted pick falls back), then the feed's order (who needs you). */
fun teamSlots(bots: List<WidgetBot>, picks: List<String?>): List<WidgetBot?> {
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt
index 85004dfc..fc23d56a 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt
@@ -88,4 +88,40 @@ class CloudClientTest {
assertEquals("/v1/access-requests/r", withdrawal?.path)
} finally { server.shutdown() }
}
+
+ @Test fun `revoking access removes only this device's grants on that computer`() = runBlocking {
+ val server = MockWebServer()
+ server.start()
+ try {
+ server.enqueue(MockResponse().setBody("""{"devices":[{"deviceId":"other","deviceKey":"elsewhere","name":"iPhone"},
+ {"deviceId":"mine","deviceKey":"${identity.publicKey}","name":"Pixel","revoked":false}]}"""))
+ server.enqueue(MockResponse().setBody("""{"grants":[{"grantId":"g1","deviceId":"other"},{"grantId":"g2","deviceId":"mine","scopes":["chat"]}]}"""))
+ server.enqueue(MockResponse().setBody("{}"))
+ val client = CloudClient(server.url("/").toString(), identity, { "session" }, OkHttpClient(), 1, Unit)
+ client.revokeAccess(id)
+ assertEquals("/v1/devices", server.takeRequest().path)
+ assertEquals("/v1/computers/$id/grants", server.takeRequest().path)
+ val revoke = server.takeRequest()
+ assertEquals("DELETE", revoke.method)
+ assertEquals("/v1/computers/$id/grants/g2", revoke.path)
+ assertEquals("Bearer session", revoke.getHeader("Authorization"))
+ assertEquals(3, server.requestCount)
+ } finally { server.shutdown() }
+ }
+
+ @Test fun `an unknown device has no grants to revoke and removing a computer deletes it from the account`() = runBlocking {
+ val server = MockWebServer()
+ server.start()
+ try {
+ server.enqueue(MockResponse().setBody("""{"devices":[]}"""))
+ server.enqueue(MockResponse().setBody("{}"))
+ val client = CloudClient(server.url("/").toString(), identity, { "session" }, OkHttpClient(), 1, Unit)
+ client.revokeAccess(id)
+ client.removeComputer(id)
+ assertEquals("/v1/devices", server.takeRequest().path)
+ val remove = server.takeRequest()
+ assertEquals("DELETE", remove.method)
+ assertEquals("/v1/computers/$id", remove.path)
+ } finally { server.shutdown() }
+ }
}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.kt
index f359d99f..133e5d64 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.kt
@@ -8,6 +8,17 @@ class ConversationTest {
private fun entry(kind: String, final: Boolean = false) = Entry("e", 1, "b", rev = 1, kind = kind,
data = buildJsonObject { put("text", "message"); put("final", final) })
+ @Test fun `a bot works in the one chat and thread its turn talks in`() {
+ val bot = Bot("b", status = "working")
+ assertTrue(bot.isWorking("b", null))
+ assertFalse(bot.isWorking("b", "root"))
+ assertTrue(bot.copy(workingThread = "root").isWorking("b", "root"))
+ assertFalse(bot.copy(workingThread = "root").isWorking("b", null))
+ assertTrue(bot.copy(workingChat = "group").isWorking("group", null))
+ assertFalse(bot.copy(workingChat = "group").isWorking("b", null))
+ assertFalse(bot.copy(status = "idle").isWorking("b", null))
+ }
+
@Test fun `chat shows final replies permissions notices and users without narration`() {
assertTrue(entry("user").isChat)
assertTrue(entry("permission").isChat)
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/HostFilesTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/HostFilesTest.kt
index c76bbcc5..42e02d06 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/HostFilesTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/HostFilesTest.kt
@@ -46,4 +46,56 @@ class HostFilesTest {
assertFalse(root.resolve("saved.partial").exists())
} finally { root.deleteRecursively() }
}
+
+ private fun shared(bytes: ByteArray, name: String = "report.pdf", sha256: String? = null) = SharedFile("file", name, bytes.size.toLong(),
+ sha256 ?: java.security.MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) })
+
+ /** Serves `bytes` as the host's readFile does, in chunks from the requested offset. */
+ private fun host(bytes: ByteArray) = HostFiles { method, body, _ ->
+ assertEquals("readFile", method)
+ assertEquals("entry", body.getValue("entryId").jsonPrimitive.content)
+ val offset = body.getValue("offset").jsonPrimitive.long.toInt()
+ val end = minOf(offset + HostFiles.CHUNK_BYTES, bytes.size)
+ buildJsonObject { put("size", bytes.size); put("data", Base64.getEncoder().encodeToString(bytes.copyOfRange(offset, end))) }
+ }
+
+ @Test fun `a shared file arrives whole and verified in its own folder`() = runBlocking {
+ val root = Files.createTempDirectory("codync-shared").toFile()
+ try {
+ for (size in listOf(0, HostFiles.CHUNK_BYTES * 2 + 5)) {
+ val bytes = ByteArray(size) { (it % 251).toByte() }
+ val progress = mutableListOf<Long>()
+ val folder = root.resolve("download-$size")
+ val saved = host(bytes).downloadShared("entry", shared(bytes), folder) { progress += it }
+ assertEquals(folder.resolve("ready/report.pdf"), saved)
+ assertArrayEquals(bytes, saved.readBytes())
+ assertEquals(size.toLong(), progress.last())
+ assertFalse(folder.resolve(".download-partial").exists())
+ }
+ } finally { root.deleteRecursively() }
+ }
+
+ @Test fun `a changed or truncated shared file leaves nothing behind`() = runBlocking {
+ val root = Files.createTempDirectory("codync-shared").toFile()
+ try {
+ val bytes = ByteArray(10) { it.toByte() }
+ val folder = root.resolve("download")
+ val integrity = assertFails<java.io.IOException> { host(bytes).downloadShared("entry", shared(bytes, sha256 = "0".repeat(64)), folder) }
+ assertEquals("The file integrity check failed. Retry the download.", integrity.message)
+ assertFalse(folder.exists())
+ val short = HostFiles { _, _, _ -> buildJsonObject { put("size", 10); put("data", "YWI=") } }
+ assertFails<java.io.IOException> { short.downloadShared("entry", shared(bytes), folder) }
+ assertFalse(folder.exists())
+ } finally { root.deleteRecursively() }
+ }
+
+ @Test fun `shared file names and hashes are checked before anything is read`() = runBlocking {
+ val files = HostFiles { _, _, _ -> error("read before validation") }
+ for (file in listOf(shared(ByteArray(1), name = "../escape"), shared(ByteArray(1), name = ".."), shared(ByteArray(1), name = "a\u0000b"),
+ shared(ByteArray(1), sha256 = "ABC"), SharedFile("file", "big", MAX_FILE_BYTES + 1, "0".repeat(64)))) {
+ val error = assertFails<IllegalArgumentException> { files.downloadShared("entry", file, Files.createTempDirectory("codync-shared").toFile().resolve("x")) }
+ assertEquals("Invalid file metadata.", error.message)
+ }
+ shared(ByteArray(1), name = ".download-partial").validate()
+ }
}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/PushAlertTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/PushAlertTest.kt
new file mode 100644
index 00000000..931867e9
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/PushAlertTest.kt
@@ -0,0 +1,35 @@
+package com.codync.android.core
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class PushAlertTest {
+ private fun face(id: String, kind: String = "agent", members: List<String> = emptyList()) =
+ """{"id":"$id","kind":"$kind","members":${members.joinToString(",", "[", "]") { "\"$it\"" }},"name":"${id.uppercase()}","avatarColor":"green","avatarShape":"hex"}"""
+
+ @Test fun `a bot's alert names the bot as the sender`() {
+ val alert = PushAlert.decode("""{"title":"Reviewer","subtitle":"Task complete","body":"All tests pass","faces":[${face("rev")}]}""")
+ assertEquals("Task complete", alert.subtitle)
+ val conversation = requireNotNull(alert.conversation("rev"))
+ assertEquals("REV", conversation.chat.name)
+ assertEquals("hex", conversation.chat.avatarShape)
+ assertNull(conversation.speaker)
+ }
+
+ @Test fun `a group's alert takes its speaker from from and its members from the faces`() {
+ val alert = PushAlert.decode("""{"title":"B in G","subtitle":"Task complete","body":"Done","from":"b",
+ "faces":[${face("g", "group", listOf("a", "b", "gone"))},${face("a")},${face("b")}]}""")
+ val conversation = requireNotNull(alert.conversation("g"))
+ assertEquals(listOf("a", "b"), conversation.members.map { it.id })
+ assertEquals("b", conversation.speaker?.id)
+ assertNull(PushAlert.decode("""{"title":"G","body":"x","faces":[${face("g", "group", listOf("a"))}]}""").conversation("g")?.speaker)
+ }
+
+ @Test fun `an alert without its chat's face stays plain and long text is bounded`() {
+ val alert = PushAlert.decode("""{"title":"${"t".repeat(200)}","body":"${"b".repeat(600)}","unknown":1}""")
+ assertNull(alert.conversation("rev"))
+ assertNull(alert.subtitle)
+ assertEquals(120, alert.title.length)
+ assertEquals(400, alert.body.length)
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/RelayVectorsTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/RelayVectorsTest.kt
index 85d44ace..52e71a36 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/RelayVectorsTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/RelayVectorsTest.kt
@@ -150,9 +150,9 @@ class RelayVectorsTest {
}
}
-internal inline fun <reified T : Throwable> assertFails(block: () -> Unit) {
+internal inline fun <reified T : Throwable> assertFails(block: () -> Unit): T {
try { block() } catch (error: Throwable) {
- if (error is T) return
+ if (error is T) return error
throw AssertionError("Expected ${T::class.simpleName}, got ${error::class.simpleName}", error)
}
throw AssertionError("Expected ${T::class.simpleName}")
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/WidgetFeedTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/WidgetFeedTest.kt
index 73f6c3db..a85c68b4 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/WidgetFeedTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/WidgetFeedTest.kt
@@ -16,4 +16,22 @@ class WidgetFeedTest {
assertEquals(listOf("c", "a", "b", null), teamSlots(bots, listOf("c", "gone", null, null)).map { it?.id })
assertEquals(listOf("a", "b", "c", null), teamSlots(bots, emptyList()).map { it?.id })
}
+
+ @Test fun `usage limits lead with the tightest limit of any provider and keep the rest in order`() {
+ val report = UsageReport(listOf(
+ UsageProvider("claude", "Claude", listOf(UsageWindow("five_hour", "5-hour", 16.0), UsageWindow("seven_day", "Weekly", 59.0))),
+ UsageProvider("codex", "Codex", listOf(UsageWindow("primary", "5-hour", 8.0), UsageWindow("secondary", "Weekly", null)))))
+ assertEquals(listOf("Claude Weekly", "Claude 5-hour", "Codex 5-hour", "Codex Weekly"),
+ usageLimits(report).map { "${it.provider} ${it.window.label}" })
+ assertEquals(listOf("Codex Weekly"), usageLimits(UsageReport(listOf(UsageProvider("codex", "Codex",
+ listOf(UsageWindow("secondary", "Weekly")))))).map { "${it.provider} ${it.window.label}" })
+ assertTrue(usageLimits(UsageReport()).isEmpty())
+ }
+
+ @Test fun `the lead bot is the first at work and nobody when all are quiet`() {
+ val bots = listOf(WidgetBot("a", "A", "needsInput"), WidgetBot("b", "B", "working"), WidgetBot("c", "C", "error"))
+ assertEquals("a", leadBot(bots)?.id)
+ assertEquals("b", leadBot(bots.drop(1))?.id)
+ assertNull(leadBot(bots.drop(2)))
+ }
}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/CharacterAvatar.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/CharacterAvatar.kt
index 9427b812..a9de5605 100644
--- a/apps/android/design/src/main/kotlin/com/codync/android/design/CharacterAvatar.kt
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/CharacterAvatar.kt
@@ -34,25 +34,24 @@ object AvatarPalette {
data class AvatarFace(val shape: String, val color: String, val status: String = "idle")
-/** Static system-widget drawing uses the same mask, palette and eyes as the app. */
-fun characterAvatarBitmap(shape: String, color: String, pixels: Int, ink: Int, highlight: Int? = null): android.graphics.Bitmap {
- require(pixels in 1..256)
+/** Static system-widget drawing uses the same mask, palette and eyes as the app; [cells] is its grid (7, 9 or 13). */
+fun characterAvatarBitmap(shape: String, color: String, pixels: Int, ink: Int, highlight: Int? = null, cells: Int = 9): android.graphics.Bitmap {
+ require(pixels in 1..256 && cells in listOf(7, 9, 13))
val bitmap = android.graphics.Bitmap.createBitmap(pixels, pixels, android.graphics.Bitmap.Config.ARGB_8888)
val canvas = android.graphics.Canvas(bitmap)
val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG)
- val cells = 9
val step = pixels / cells.toFloat()
val half = pixels / 2.0
val lx = sin(-.7) * .8; val ly = .55; val lz = cos(-.7) * .5 + .6
val ll = sqrt(lx * lx + ly * ly + lz * lz)
for ((row, col) in avatarDots(shape, cells)) {
- if (col in listOf(3, 6) && row in listOf(3, 4)) continue
+ if (col in eyeColumns(cells) && row in eyeRows(cells)) continue
val x = (col + .5f) * step; val y = (row + .5f) * step
val u = (x - half) / half; val v = (half - y) / half
val z = sqrt(max(.2, 1.0 - u * u - v * v))
val shade = .3 + .7 * max(0.0, (u * lx + v * ly + z * lz) / (sqrt(u * u + v * v + z * z) * ll))
val radius = (step * .42 * (.55 + .45 * shade)).toFloat()
- paint.color = ink; paint.alpha = ((.4 + .4 * shade) * 255).roundToInt().coerceIn(0, 255)
+ paint.color = ink; paint.alpha = (dotInk(cells, shade) * 255).roundToInt().coerceIn(0, 255)
canvas.drawCircle(x, y, radius, paint)
if (shade > .6) {
paint.color = highlight ?: (AvatarPalette.colors[color] ?: AvatarPalette.colors.getValue("blue")).toInt()
@@ -86,8 +85,8 @@ fun characterAvatarBitmap(shape: String, color: String, pixels: Int, ink: Int, h
val step = this.size.width / cells
val half = this.size.width / 2
val glance = if (status == "working" && time > 0) (sin(time * 2 * PI / 3.2) * 1.4).roundToInt() else 0
- val eyes = (when (cells) { 7 -> listOf(2, 4); 9 -> listOf(3, 6); else -> listOf(4, 8) }).map { it + glance }
- val eyeRows = when (cells) { 7 -> listOf(2, 3); 9 -> listOf(3, 4); else -> listOf(4, 5, 6) }
+ val eyes = eyeColumns(cells).map { it + glance }
+ val eyeRows = eyeRows(cells)
val blinking = time > 0 && (time / 4.7) % 1 < 0.035
val yaw = if (status == "working" && time > 0) time * 1.4 else -0.7
val lx = sin(yaw) * .8; val ly = .55; val lz = cos(yaw) * .5 + .6
@@ -101,8 +100,7 @@ fun characterAvatarBitmap(shape: String, color: String, pixels: Int, ink: Int, h
var shade = .3 + .7 * max(0.0, (u * lx + v * ly + z * lz) / (nl * ll))
if (status == "needsInput") shade *= .6 + .4 * (.5 + .5 * sin(sqrt((u * u + v * v).toDouble()) * 9 - time * 5))
val radius = (step * .42 * (.55 + .45 * shade)).toFloat()
- val alpha = if (cells < 13) .4 + .4 * shade else .2 + .4 * min(1.0, shade / .7)
- drawCircle(ink.copy(alpha = alpha.toFloat()), radius, center)
+ drawCircle(ink.copy(alpha = dotInk(cells, shade).toFloat()), radius, center)
if (shade > .6) drawCircle(tint.copy(alpha = ((shade - .6) / .4).toFloat().coerceIn(0f, 1f)), radius, center)
}
}
@@ -131,6 +129,11 @@ fun characterAvatarBitmap(shape: String, color: String, pixels: Int, ink: Int, h
}
}
+private fun eyeColumns(cells: Int) = when (cells) { 7 -> listOf(2, 4); 9 -> listOf(3, 6); else -> listOf(4, 8) }
+private fun eyeRows(cells: Int) = when (cells) { 7 -> listOf(2, 3); 9 -> listOf(3, 4); else -> listOf(4, 5, 6) }
+/** A dot's ink opacity for its shade: finer grids fade their dim side further. */
+private fun dotInk(cells: Int, shade: Double) = if (cells < 13) .4 + .4 * shade else .2 + .4 * min(1.0, shade / .7)
+
/** Integer mask is computed once per shape/grid, never in the animation loop. */
private fun avatarDots(shape: String, cells: Int): List<Pair<Int, Int>> {
val path = avatarPath(shape)
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/PullToRefresh.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/PullToRefresh.kt
new file mode 100644
index 00000000..cee50b9d
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/PullToRefresh.kt
@@ -0,0 +1,149 @@
+package com.codync.android.design
+
+import androidx.compose.animation.core.LinearEasing
+import androidx.compose.animation.core.RepeatMode
+import androidx.compose.animation.core.animate
+import androidx.compose.animation.core.animateFloat
+import androidx.compose.animation.core.infiniteRepeatable
+import androidx.compose.animation.core.rememberInfiniteTransition
+import androidx.compose.animation.core.tween
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxScope
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.padding
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.drawWithContent
+import androidx.compose.ui.draw.rotate
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.graphics.drawscope.clipPath
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.hapticfeedback.HapticFeedbackType
+import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
+import androidx.compose.ui.input.nestedscroll.NestedScrollSource
+import androidx.compose.ui.input.nestedscroll.nestedScroll
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.platform.LocalHapticFeedback
+import androidx.compose.ui.semantics.clearAndSetSemantics
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.Velocity
+import androidx.compose.ui.unit.dp
+import kotlin.math.hypot
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+
+/** How far past the top a pull completes the circle. */
+private val PullDistance = 110.dp
+/** Room kept open above the content while it refreshes, for the indicator. */
+private val PullHold = 52.dp
+/** A finger past the top moves the content this much (UIKit's rubber band, roughly). */
+private const val PullResistance = 0.5f
+/** Long enough to read as a refresh even when it's done at once. */
+private const val MinimumRefreshMillis = 600L
+
+/**
+ * A pull past the top of scrolling content (iOS `PullToRefresh` with its chat list): the content
+ * follows the finger, the arrow sweeps in with the pull, and the refresh starts only when the
+ * reader lets go of a full circle, so a long pull never refreshes under the finger. The content
+ * stays lowered under the turning arrow until `refresh` returns, then eases back up.
+ * `indicatorTop` is where the content's visible top is (under any bars it scrolls beneath).
+ */
+@Composable fun PullToRefresh(refresh: suspend () -> Unit, modifier: Modifier = Modifier, indicatorTop: Dp = 0.dp,
+ content: @Composable BoxScope.() -> Unit) {
+ val density = LocalDensity.current
+ val distance = with(density) { PullDistance.toPx() }
+ val hold = with(density) { PullHold.toPx() }
+ val haptics = LocalHapticFeedback.current
+ val scope = rememberCoroutineScope()
+ val latest by rememberUpdatedState(refresh)
+ var pull by remember { mutableFloatStateOf(0f) }
+ var refreshing by remember { mutableStateOf(false) }
+ val connection = remember(distance, hold) {
+ object : NestedScrollConnection {
+ var settling: Job? = null
+
+ fun pullBy(delta: Float) {
+ settling?.cancel()
+ val before = pull
+ pull = (pull + delta).coerceAtLeast(0f)
+ if (before < distance && pull >= distance) haptics.performHapticFeedback(HapticFeedbackType.GestureThresholdActivate)
+ }
+
+ fun settle(to: Float) {
+ settling = scope.launch { animate(pull, to, animationSpec = Motion.spring(0.5f)) { value, _ -> pull = value } }
+ }
+
+ // Pushing back up takes back the pull before the content scrolls.
+ override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
+ if (refreshing || pull <= 0f || available.y >= 0f || source != NestedScrollSource.UserInput) return Offset.Zero
+ val used = maxOf(available.y, -pull / PullResistance)
+ pullBy(used * PullResistance)
+ return Offset(0f, used)
+ }
+
+ override fun onPostScroll(consumed: Offset, available: Offset, source: NestedScrollSource): Offset {
+ if (refreshing || available.y <= 0f || source != NestedScrollSource.UserInput) return Offset.Zero
+ pullBy(available.y * PullResistance)
+ return Offset(0f, available.y)
+ }
+
+ override suspend fun onPreFling(available: Velocity): Velocity {
+ if (refreshing || pull <= 0f) return Velocity.Zero
+ if (pull < distance) { settle(0f); return available }
+ refreshing = true
+ settle(hold)
+ scope.launch {
+ val started = System.currentTimeMillis()
+ try { latest() }
+ finally {
+ delay(MinimumRefreshMillis - (System.currentTimeMillis() - started))
+ refreshing = false
+ settle(0f)
+ }
+ }
+ return available
+ }
+ }
+ }
+ Box(modifier.nestedScroll(connection)) {
+ Box(Modifier.fillMaxSize().graphicsLayer { translationY = pull }, content = content)
+ PullIndicator(if (refreshing) 1f else (pull / distance).coerceIn(0f, 1f), refreshing,
+ Modifier.align(Alignment.TopCenter).padding(top = indicatorTop + 8.dp))
+ }
+}
+
+/** The arrow, swept in from its tail as the pull grows, turning while it refreshes. */
+@Composable private fun PullIndicator(progress: Float, refreshing: Boolean, modifier: Modifier) {
+ val still = reduceMotion() || !refreshing
+ val turn = if (still) 0f else rememberInfiniteTransition(label = "Refreshing")
+ .animateFloat(0f, 360f, infiniteRepeatable(tween(800, easing = LinearEasing), RepeatMode.Restart), label = "Turn").value
+ Box(modifier.padding(8.dp).graphicsLayer { alpha = if (refreshing) 1f else minOf(1f, progress * 2) }
+ .then(if (refreshing) Modifier.clearAndSetSemantics { contentDescription = "Refreshing" } else Modifier.clearAndSetSemantics {})) {
+ Symbol("arrow.clockwise", Modifier.rotate(turn).drawWithContent {
+ // A full turn is the whole arrow (a 360° arc would come out empty).
+ if (progress >= 1f) { drawContent(); return@drawWithContent }
+ val radius = hypot(size.width, size.height)
+ val wedge = Path().apply {
+ moveTo(center.x, center.y)
+ arcTo(Rect(center - Offset(radius, radius), center + Offset(radius, radius)), SweepStart, 360f * progress, false)
+ close()
+ }
+ clipPath(wedge) { [email protected]() }
+ }, size = 22.dp, tint = Palette.secondary)
+ }
+}
+
+/** Where the arrow's tail is: the Material arrow starts at 3 o'clock (SF's just above it, at -15°). */
+private const val SweepStart = 0f
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt
index ce11fa8b..58181576 100644
--- a/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt
@@ -71,6 +71,7 @@ import androidx.annotation.DrawableRes
"doc.text" -> R.drawable.sf_doc_text
"doc.zipper" -> R.drawable.sf_doc_zipper
"ellipsis" -> R.drawable.sf_ellipsis
+ "ellipsis.bubble.fill" -> R.drawable.sf_ellipsis_bubble_fill
"envelope.fill" -> R.drawable.sf_envelope_fill
"escape" -> R.drawable.sf_escape
"exclamationmark" -> R.drawable.sf_exclamationmark
@@ -81,6 +82,7 @@ import androidx.annotation.DrawableRes
"eye" -> R.drawable.sf_eye
"eye.slash" -> R.drawable.sf_eye_slash
"figure.run" -> R.drawable.sf_figure_run
+ "film" -> R.drawable.sf_film
"folder" -> R.drawable.sf_folder
"function" -> R.drawable.sf_function
"gearshape" -> R.drawable.sf_gearshape
@@ -105,11 +107,15 @@ import androidx.annotation.DrawableRes
"lock.rectangle" -> R.drawable.sf_lock_rectangle
"lock.shield" -> R.drawable.sf_lock_shield
"lock.slash" -> R.drawable.sf_lock_slash
+ "macmini" -> R.drawable.sf_macmini
+ "macpro.gen3" -> R.drawable.sf_macpro_gen3
+ "macstudio" -> R.drawable.sf_macstudio
"magnifyingglass" -> R.drawable.sf_magnifyingglass
"map.fill" -> R.drawable.sf_map_fill
"mic" -> R.drawable.sf_mic
"mic.fill" -> R.drawable.sf_mic_fill
"mic.slash" -> R.drawable.sf_mic_slash
+ "moon.zzz.fill" -> R.drawable.sf_moon_zzz_fill
"move" -> R.drawable.sf_move
"music.note" -> R.drawable.sf_music_note
"network" -> R.drawable.sf_network
diff --git a/apps/android/design/src/main/res/drawable/sf_ellipsis_bubble_fill.xml b/apps/android/design/src/main/res/drawable/sf_ellipsis_bubble_fill.xml
new file mode 100644
index 00000000..5d879860
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_ellipsis_bubble_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `sms` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M316.16-517.13q18.21 0 30.55-12.32 12.33-12.32 12.33-30.53 0-18.22-12.32-30.55-12.32-12.34-30.53-12.34t-30.55 12.32q-12.34 12.32-12.34 30.53 0 18.22 12.32 30.55 12.32 12.34 30.54 12.34Zm163.82 0q18.22 0 30.55-12.32 12.34-12.32 12.34-30.53 0-18.22-12.32-30.55-12.32-12.34-30.53-12.34-18.22 0-30.55 12.32-12.34 12.32-12.34 30.53 0 18.22 12.32 30.55 12.32 12.34 30.53 12.34Zm163.83 0q18.21 0 30.55-12.32t12.34-30.53q0-18.22-12.32-30.55-12.32-12.34-30.54-12.34-18.21 0-30.55 12.32-12.33 12.32-12.33 30.53 0 18.22 12.32 30.55 12.32 12.34 30.53 12.34ZM231.87-231.87l-82.44 82.44q-21.63 21.63-49.59 9.77-27.97-11.86-27.97-42.36v-615.11q0-37.78 26.61-64.39t64.39-26.61h634.26q37.78 0 64.39 26.61t26.61 64.39v474.26q0 37.78-26.61 64.39t-64.39 26.61H231.87Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_film.xml b/apps/android/design/src/main/res/drawable/sf_film.xml
new file mode 100644
index 00000000..e44215ca
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_film.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `movie`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m162.87-808.13 65 130q7 14 20 22t28 8q30 0 46-25.5t2-52.5l-41-82h80l65 130q7 14 20 22t28 8q30 0 46-25.5t2-52.5l-41-82h80l65 130q7 14 20 22t28 8q30 0 46-25.5t2-52.5l-41-82h114.26q37.78 0 64.39 26.61t26.61 64.39v474.26q0 37.78-26.61 64.39t-64.39 26.61H162.87q-37.78 0-64.39-26.37t-26.61-63.91v-474.98q0-37.78 26.61-64.39t64.39-26.61Zm0 251v314.26h634.26v-314.26H162.87Zm0 0v314.26-314.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_macmini.xml b/apps/android/design/src/main/res/drawable/sf_macmini.xml
new file mode 100644
index 00000000..882782f1
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_macmini.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `hard_drive`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M163.83-284.3h632.34v-230.44H163.83v230.44Zm517.13-55.22q25 0 42.5-17.5t17.5-42.5q0-25-17.5-42.5t-42.5-17.5q-25 0-42.5 17.5t-17.5 42.5q0 25 17.5 42.5t42.5 17.5Zm206.21-263.83H758.63l-73.3-73.3H274.67l-73.3 73.3H72.83L210.78-741.3q12.68-12.68 29.18-19.52 16.5-6.83 34.71-6.83h410.66q18.21 0 34.71 6.83 16.5 6.84 29.18 19.52l137.95 137.95ZM163.83-193.3q-37.79 0-64.4-26.61-26.6-26.61-26.6-64.39v-319.05h814.34v319.05q0 37.78-26.6 64.39-26.61 26.61-64.4 26.61H163.83Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_macpro_gen3.xml b/apps/android/design/src/main/res/drawable/sf_macpro_gen3.xml
new file mode 100644
index 00000000..a7246917
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_macpro_gen3.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `host`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M162.87-111.87q-37.78 0-64.39-26.61t-26.61-64.39v-554.26q0-37.78 26.61-64.39t64.39-26.61h190.91q37.79 0 64.39 26.61 26.61 26.61 26.61 64.39v554.26q0 37.78-26.61 64.39-26.6 26.61-64.39 26.61H162.87Zm443.35 0q-37.79 0-64.39-26.61-26.61-26.61-26.61-64.39v-554.26q0-37.78 26.61-64.39 26.6-26.61 64.39-26.61h190.91q37.78 0 64.39 26.61t26.61 64.39v554.26q0 37.78-26.61 64.39t-64.39 26.61H606.22Zm-445.74-88.61h195.69v-559.04H160.48v559.04Zm443.35 0h195.69v-559.04H603.83v559.04ZM316.65-388.76q0-18.2-12.46-30.65-12.46-12.46-30.89-12.46h-30.43q-18.22 0-30.54 12.46Q200-406.96 200-388.76t12.33 30.65q12.32 12.46 30.54 12.46h30.43q18.43 0 30.89-12.46 12.46-12.45 12.46-30.65Zm443.35 0q0-18.2-12.46-30.65-12.47-12.46-30.89-12.46h-30.43q-18.22 0-30.55 12.46-12.32 12.45-12.32 30.65t12.32 30.65q12.33 12.46 30.55 12.46h30.43q18.42 0 30.89-12.46Q760-370.56 760-388.76ZM316.65-514.38q0-18.32-12.46-31.01-12.46-12.7-30.89-12.7h-30.43q-18.22 0-30.54 12.7Q200-532.7 200-514.26q0 18.02 12.33 30.2 12.32 12.19 30.54 12.19h30.43q18.2 0 30.78-12.1 12.57-12.1 12.57-30.41Zm443.35 0q0-18.32-12.46-31.01-12.47-12.7-30.89-12.7h-30.43q-18.22 0-30.55 12.7-12.32 12.69-12.32 31.13 0 18.02 12.32 30.2 12.33 12.19 30.55 12.19h30.43q18.2 0 30.77-12.1Q760-496.07 760-514.38ZM316.65-640.6q0-18.31-12.46-31.01-12.46-12.69-30.89-12.69h-30.43q-18.22 0-30.54 12.69Q200-658.91 200-640.48q0 18.02 12.33 30.21 12.32 12.18 30.54 12.18h30.43q18.2 0 30.78-12.09 12.57-12.1 12.57-30.42Zm443.35 0q0-18.31-12.46-31.01-12.47-12.69-30.89-12.69h-30.43q-18.22 0-30.55 12.69-12.32 12.7-12.32 31.13 0 18.02 12.32 30.21 12.33 12.18 30.55 12.18h30.43q18.2 0 30.77-12.09Q760-622.28 760-640.6ZM160.48-200.48h195.69-195.69Zm443.35 0h195.69-195.69Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_macstudio.xml b/apps/android/design/src/main/res/drawable/sf_macstudio.xml
new file mode 100644
index 00000000..8e68b248
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_macstudio.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `hard_drive_2`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M551.39-202.87q17.81 0 29.86-12.22 12.05-12.21 12.05-29.81 0-17.6-12.05-29.7-12.05-12.1-29.86-12.1t-29.86 12.05q-12.05 12.05-12.05 29.87 0 17.48 12.05 29.69 12.05 12.22 29.86 12.22Zm123.95 0q17.59 0 29.69-12.22 12.1-12.21 12.1-29.81 0-17.6-12.05-29.7-12.05-12.1-29.86-12.1-17.48 0-29.7 12.05-12.22 12.05-12.22 29.87 0 17.48 12.22 29.69 12.22 12.22 29.82 12.22ZM111.87-448.13v-349q0-37.78 26.61-64.39t64.39-26.61h554.26q37.78 0 64.39 26.61t26.61 64.39v349h-91v-349H202.87v349h-91Zm91 91v194.26h554.26v-194.26H202.87Zm0 285.26q-37.78 0-64.39-26.61t-26.61-64.39v-285.26h736.26v285.26q0 37.78-26.61 64.39t-64.39 26.61H202.87Zm0-376.26h554.26-554.26Zm0 91h554.26-554.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_moon_zzz_fill.xml b/apps/android/design/src/main/res/drawable/sf_moon_zzz_fill.xml
new file mode 100644
index 00000000..dcf4fa27
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_moon_zzz_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `bedtime` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M524-35.22q-84.96 0-159.29-32.36-74.34-32.35-129.56-87.57-55.22-55.22-87.57-129.56-32.36-74.33-32.36-159.29 0-126.8 70.44-230.57 70.45-103.76 189.06-148.86 26.06-10.87 49.49 4.54 23.42 15.41 23.62 43.43-.61 82.61 28.79 157.7 29.4 75.09 87.73 133.41 58.32 58.33 133.29 87.61t157.34 28.91q30.06.44 45.31 22.41 15.25 21.96 5.34 47.83-45.91 119.05-149.77 190.71Q652-35.22 524-35.22Z"/>
+ </group>
+</vector>
diff --git a/apps/android/tools/symbols.py b/apps/android/tools/symbols.py
index 9d47785e..f4333dbc 100644
--- a/apps/android/tools/symbols.py
+++ b/apps/android/tools/symbols.py
@@ -82,6 +82,7 @@ MAP = {
"doc.text": "description",
"doc.zipper": "folder_zip",
"ellipsis": "more_horiz",
+ "ellipsis.bubble.fill": "sms+",
"envelope.fill": "mail+",
"escape": "keyboard_return",
"exclamationmark": "priority_high",
@@ -92,6 +93,7 @@ MAP = {
"eye": "visibility",
"eye.slash": "visibility_off",
"figure.run": "directions_run",
+ "film": "movie",
"folder": "folder",
"function": "function",
"gearshape": "settings",
@@ -116,11 +118,15 @@ MAP = {
"lock.rectangle": "password",
"lock.shield": "shield_lock",
"lock.slash": "lock_open",
+ "macmini": "hard_drive",
+ "macpro.gen3": "host",
+ "macstudio": "hard_drive_2",
"magnifyingglass": "search",
"map.fill": "map+",
"mic": "mic",
"mic.fill": "mic+",
"mic.slash": "mic_off",
+ "moon.zzz.fill": "bedtime+",
"move": "open_with",
"music.note": "music_note",
"network": "public",
diff --git a/docs/guides/development.md b/docs/guides/development.md
index bc7a47ba..86621692 100644
--- a/docs/guides/development.md
+++ b/docs/guides/development.md
@@ -93,7 +93,7 @@ git config core.hooksPath .githooks
It runs CI's checks for each part a commit touches, so a failure shows up before the push:
host (`cargo fmt --check`, clippy, `cargo test` and the memory tests, with CI's pinned Engram
fetched once into `host/target/engram-test-runtime`), desktop, cloud and relay (`npm run typecheck`,
-`npm test`), the Android app (core and app unit tests and a Kotlin compile, with JDK 21), Linux
+`npm test`), the Android app (core and app unit tests, and a Kotlin compile of the app and its instrumentation tests, with JDK 21), Linux
screen helper formatting, and a parse of the macOS screen helper's Swift sources (on macOS). It checks the staged files only, in a copy under `.git/precommit-snapshot`,
so other agents' uncommitted edits in the same checkout neither break nor rescue a commit; the
host builds into `host/target/precommit`, and its tests are stopped after 5 minutes so a hung
diff --git a/docs/plans/android-app.md b/docs/plans/android-app.md
index cf053b48..be7a1f26 100644
--- a/docs/plans/android-app.md
+++ b/docs/plans/android-app.md
@@ -14,16 +14,17 @@ emulator against a real host; device acceptance is listed separately.
| Area | Android | Remaining |
| --- | --- | --- |
| Welcome/pairing | Ported: welcome crew and chat glimpse, Install (Mac/Linux) and Scan pages with the camera on the page, paste link, Tailscale note, sign-in | Physical optical scan, camera permission denial |
-| Accounts/access | Ported: account sheet and switcher, Computers & settings, account computer access with its code, access banner | Provider browser round trip on a device; one computer per phone ([multiple computers are future work](../architecture/overview.md)) |
-| Roster | Ported: rows, menus, pin/hide/delete, groups, drag to reorder (host-synced order), computer header | Multiple computers |
-| Conversation/threads | Ported: bubbles, Markdown/code, permissions, reactions, threads, Full conversation, bot-to-bot exchange lines and their conversation, routine notices | Physical keyboard and TalkBack |
-| Composer | Ported: files/photos/paste, `/` commands (Fast mode, New session, skills), @mentions in groups, call/send/stop button | — |
-| Bot and group editors | Ported: avatar, profile, agent and model options, Fast mode, workspace folder picker, permissions, activity, connectors, skills | — |
+| Accounts/access | Ported: account sheet and switcher, Computers & settings (connection status, badge color, Revoke this phone's access, older copies removed from the account), account computer access with its code, access banner, `codync-dev://computers` and `codync-dev://plugins` | Provider browser round trip on a device; Revoke and older copies against a signed-in account (covered by cloud request tests only); one computer per phone ([multiple computers are future work](../architecture/overview.md)) |
+| Roster | Ported: rows, menus, pin/hide/delete, groups, drag to reorder (host-synced order) and TalkBack Move up/down, computer header, pull to refresh (also in Computers & settings) | Multiple computers |
+| Conversation/threads | Ported: bubbles, Markdown/code, permissions, reactions, threads, Full conversation, bot-to-bot exchange lines and their conversation, routine notices that open their routine, files a bot shares (verified download, then the share sheet), sent images full size, pull down to reconnect, jump to latest, read receipts for every conversation on screen | Physical keyboard and TalkBack |
+| Composer | Ported: files/photos/paste (groups too, image thumbnails, Paste only when the clipboard holds files), `/` commands (Fast mode, New session, skills listed fresh on `/`), @mentions in groups, call/send/stop/interrupt button | — |
+| Bot and group editors | Ported: avatar, profile, agent and model options, Fast mode, workspace folder picker, permissions, activity, connectors, skills (with their details) | — |
| Memory | Ported: search, filters, add/edit, pin, review, history and timeline, export/import, forget all | — |
| Routines | Ported: list with switches, editor (schedule, webhook panel, run settings), test run, delete | Live provider/routine acceptance |
| Extensions | Ported: agents (install, sign-in, setup terminal), registry connectors, Composio apps, skills, installed list, custom connector, own skill, credentials, chat connection request card | Real provider OAuth, 1Password |
| Voice | Ported: call bar (provider name, fallback notice), Voice chat settings (engine, mode, models, voice, minutes this month), on device (Vosk English + Android TTS), OpenAI Realtime (WebRTC), Gemini Live, Speech mode, fallback to on device, group calls | Both providers with a real key on a device; on-device recognition in languages other than English |
-| State/widgets | Ported: Widget (with the animated Add a widget guide), Live update and Status bar pages, Usage sheet, Choose the look; Provider usage, Bots and Team widgets with launcher Edit widget | Physical launcher refresh |
+| State/widgets | Ported: Widget (with the animated Add a widget guide), Live update and Status bar pages, Usage sheet, Choose the look; Provider usage, Usage limits, Bots and Team widgets with launcher Edit widget and picker previews (Android 15+); the Bots Quick Settings tile (iOS's Control Center control) | Physical launcher refresh; the tile opens Codync, not Computers, when no bot is at work |
+| Notifications | Ported: alerts as conversations with the bot's face (a group's face and its speaking member), conversation shortcuts, what happened ("Task complete") as sub text | Android's conversation layout doesn't draw sub text; background delivery needs FCM in the deployment |
| Live updates | Android 16 Live updates (`ProgressStyle`), the status bar chip on Android 16 QPR1 (API 36.1) | Background updates need FCM in the deployment |
| Version check | `VersionMismatch.MIN_HOST`, the host's `minApp`, the update card in the roster and in place of the composer | Set `MIN_HOST` to the first release that ships Android support when it's cut |
| Remote screen | Ported: viewer from Computers, the chat header (watch a bot, then take over) and `codync-dev://screen`; WebRTC H.264, trackpad and direct touch, long-press drag, two-finger scroll, pinch zoom streaming the visible region, keyboard with IME and modifier keys, clipboard, displays, take over/hand back, Rotate | Pinch, IME composition and a hardware keyboard on a device; TURN relay path and renewal |