Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ internal fun isPresent(peers: List<RemotePeer>, ghosts: List<RemoteGhost>, insta
peers.any { it.instanceId == instanceId } || ghosts.any { it.instanceId == instanceId }

/**
* Who a join link follows: the instance it names, else the instance of the sender that was active last. A ghost with more
* time left has left later.
* Who a join link follows: the instance it names, else the instance of the sender that was active last, never one of
* their AI agents. A ghost with more time left has left later.
*
* @return null if the sender is fully away
*/
Expand All @@ -36,8 +36,9 @@ internal fun joinFollowInstance(
instance: String?,
): String? {
if (instance != null && isPresent(peers, ghosts, instance)) return instance
return peers.filter { it.accountId == from }.maxByOrNull { it.lastActiveAt.orEmpty() }?.instanceId
?: ghosts.filter { it.accountId == from }.maxByOrNull { it.remainingMs }?.instanceId
// an agent of the sender has no cursor or viewport, and while it edits it is the one that was active last
return peers.filter { it.accountId == from && it.agent == null }.maxByOrNull { it.lastActiveAt.orEmpty() }?.instanceId
?: ghosts.filter { it.accountId == from && it.agent == null }.maxByOrNull { it.remainingMs }?.instanceId
}

/** @return null while there is nothing to look at: no connection of the instance has a viewport or a cursor */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,13 @@ import androidx.compose.foundation.border
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.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.SmartToy
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
Expand All @@ -27,12 +31,14 @@ import androidx.compose.ui.unit.dp
import de.markusressel.mkdocseditor.feature.avatar.ui.compose.UserAvatar
import de.markusressel.mkdocseditor.feature.theme.MkDocsEditorTheme
import de.markusressel.mkdocseditor.util.compose.CombinedPreview
import de.markusressel.mkdocsrestclient.sync.automerge.RemoteAgent
import de.markusressel.mkdocsrestclient.sync.automerge.RemotePeer

private const val MAX_VISIBLE_USERS = 3

/**
* Shows the other client instances in this document as colored circles with the initial of their user
* Shows the other client instances in this document as colored circles with the initial of their user, AI agents as a
* robot
*
* @param remotePeers the other connections in this document
*/
Expand All @@ -50,13 +56,24 @@ internal fun OnlineUsersAction(
)
DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {
remotePeers.instances().forEach { user ->
DropdownMenuItem(
text = { Text(stringResource(R.string.follow_user, user.label)) },
onClick = {
menuOpen = false
onFollowClicked(user.instanceId)
},
)
val agent = user.agent
if (agent != null) {
// an agent has no cursor or viewport to follow
DropdownMenuItem(
text = { Text(stringResource(R.string.online_agent, agent.name, user.name)) },
leadingIcon = { AgentAvatar(modifier = Modifier.size(24.dp), color = user.composeColor) },
enabled = false,
onClick = {},
)
} else {
DropdownMenuItem(
text = { Text(stringResource(R.string.follow_user, user.label)) },
onClick = {
menuOpen = false
onFollowClicked(user.instanceId)
},
)
}
}
}
}
Expand All @@ -75,12 +92,16 @@ private fun OnlineUsersBadges(
verticalAlignment = Alignment.CenterVertically,
) {
users.take(MAX_VISIBLE_USERS).forEach { user ->
UserAvatar(
modifier = Modifier.badge(),
name = user.name,
color = user.composeColor,
avatar = user.avatarModel,
)
if (user.agent != null) {
AgentAvatar(modifier = Modifier.badge(), color = user.composeColor)
} else {
UserAvatar(
modifier = Modifier.badge(),
name = user.name,
color = user.composeColor,
avatar = user.avatarModel,
)
}
}

if (users.size > MAX_VISIBLE_USERS) {
Expand Down Expand Up @@ -113,6 +134,22 @@ private fun OnlineUserBadge(
}
}

/** An AI agent: a robot in the color of its person */
@Composable
private fun AgentAvatar(modifier: Modifier = Modifier, color: Color) {
Box(
modifier = modifier.background(color, CircleShape),
contentAlignment = Alignment.Center,
) {
Icon(
imageVector = Icons.Outlined.SmartToy,
contentDescription = null,
tint = labelTextColorOn(color),
modifier = Modifier.fillMaxSize(0.7f),
)
}
}

/** the ring keeps overlapping badges apart */
@Composable
private fun Modifier.badge() = this
Expand All @@ -132,6 +169,7 @@ private fun OnlineUsersActionPreview() {
displayName = null,
color = null,
selections = emptyList(),
agent = if (index == 1) RemoteAgent(tokenId = "t1", name = "Claude Code") else null,
)
}
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,4 +146,5 @@ internal fun RemoteGhost.asPeer() = RemotePeer(
deviceName = deviceName,
instanceColor = instanceColor,
avatar = avatar,
agent = agent,
)
1 change: 1 addition & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@
<string name="open_in_browser">Open in browser</string>
<string name="more_actions">More</string>
<string name="follow_user">Follow %1$s</string>
<string name="online_agent">%1$s (agent of %2$s)</string>
<string name="following_user">Following %1$s</string>
<string name="following_user_paused">Following %1$s (paused)</string>
<string name="follow_stop">Stop following</string>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package de.markusressel.mkdocseditor.feature.editor.domain

import de.markusressel.mkdocsrestclient.sync.automerge.RemoteAgent
import de.markusressel.mkdocsrestclient.sync.automerge.RemoteGhost
import de.markusressel.mkdocsrestclient.sync.automerge.RemotePeer
import de.markusressel.mkdocsrestclient.sync.automerge.RemotePosition
Expand All @@ -20,6 +21,7 @@ class SenderPositionTest {
lastActiveAt: String? = null,
viewport: RemoteViewport? = null,
instance: String = account,
agent: RemoteAgent? = null,
) = RemotePeer(
clientId = "c",
username = "u",
Expand All @@ -30,6 +32,7 @@ class SenderPositionTest {
lastActiveAt = lastActiveAt,
viewport = viewport,
instanceId = instance,
agent = agent,
)

private fun ghost(
Expand All @@ -49,6 +52,15 @@ class SenderPositionTest {
remainingMs = remainingMs,
)

@Test
fun `a join link follows the sender and not their agent that edits right now`() {
val peers = listOf(
peer("sender", 1, "2026-11-05T10:00:00Z", instance = "phone"),
peer("sender", null, "2026-11-05T10:05:00Z", instance = "agent", agent = RemoteAgent("t1", "Claude Code")),
)
assertEquals("phone", joinFollowInstance(peers, emptyList(), "sender", instance = null))
}

@Test
fun `follows the connection of the instance that moved last`() {
val peers = listOf(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package de.markusressel.mkdocsrestclient.sync.automerge

import de.markusressel.mkdocsrestclient.moshi
import de.markusressel.mkdocsrestclient.sync.automerge.protocol.ActorInfo
import de.markusressel.mkdocsrestclient.sync.automerge.protocol.AgentMessage
import de.markusressel.mkdocsrestclient.sync.automerge.protocol.ActorMessage
import de.markusressel.mkdocsrestclient.sync.automerge.protocol.DocumentRenamedMessage
import de.markusressel.mkdocsrestclient.sync.automerge.protocol.ErrorMessage
Expand Down Expand Up @@ -59,6 +60,15 @@ data class RemotePeer(
val instanceColor: String? = null,
/** version of the profile picture of [accountId], null without one */
val avatar: String? = null,
/** set when this is an AI agent of [accountId], which has no cursor and no viewport */
val agent: RemoteAgent? = null,
)

/** An AI agent that works with an app token of an account */
data class RemoteAgent(
val tokenId: String,
/** the name of the app token */
val name: String,
)

/** The text another user is looking at, as UTF-16 indices of the first and the last visible character */
Expand Down Expand Up @@ -90,8 +100,11 @@ data class RemoteGhost(
val deviceName: String? = null,
val instanceColor: String? = null,
val avatar: String? = null,
val agent: RemoteAgent? = null,
)

private fun AgentMessage.toRemote() = RemoteAgent(tokenId, name)

/** A new id of a client instance, which the server expects as 32 lowercase hex characters */
fun newInstanceId(random: SecureRandom = SecureRandom()): String =
ByteArray(16).also { random.nextBytes(it) }.toHex()
Expand Down Expand Up @@ -198,6 +211,7 @@ class DocumentSyncSession(
val deviceName: String?,
val instanceColor: String?,
val avatar: String?,
val agent: RemoteAgent?,
)

private class Peer(
Expand Down Expand Up @@ -356,7 +370,7 @@ class DocumentSyncSession(
MessageType.PRESENCE_SNAPSHOT -> onPresenceSnapshot(parse(text))
MessageType.PRESENCE_LEAVE -> onPresenceLeave(parse(text))
MessageType.ACTOR -> parse<ActorMessage>(text).let {
actors[it.actorId] = ActorInfo(it.actorId, it.username, it.displayName, it.color)
actors[it.actorId] = ActorInfo(it.actorId, it.username, it.displayName, it.color, it.agent)
reportAuthorColors()
}

Expand Down Expand Up @@ -637,6 +651,7 @@ class DocumentSyncSession(
deviceName = ghost.deviceName,
instanceColor = ghost.instanceColor,
avatar = ghost.avatar,
agent = ghost.agent?.toRemote(),
)
}
notifyGhosts()
Expand Down Expand Up @@ -664,6 +679,7 @@ class DocumentSyncSession(
deviceName = message.deviceName,
instanceColor = message.instanceColor,
avatar = message.avatar ?: left?.presence?.avatar,
agent = left?.presence?.agent?.toRemote(),
)
notifyGhosts()
}
Expand All @@ -686,6 +702,7 @@ class DocumentSyncSession(
deviceName = ghost.deviceName,
instanceColor = ghost.instanceColor,
avatar = ghost.avatar,
agent = ghost.agent,
)
}
)
Expand Down Expand Up @@ -785,6 +802,7 @@ class DocumentSyncSession(
deviceName = peer.presence.deviceName,
instanceColor = peer.presence.instanceColor,
avatar = peer.presence.avatar,
agent = peer.presence.agent?.toRemote(),
)
}
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ data class PresenceMessage(
val instanceColor: String? = null,
/** version of the profile picture of the account, null without one */
val avatar: String? = null,
/** set when an AI agent with an app token of the account is this connection */
val agent: AgentMessage? = null,
val type: String = MessageType.PRESENCE,
)

Expand All @@ -96,6 +98,14 @@ data class LocalPresenceMessage(
val type: String = MessageType.PRESENCE,
)

/** An AI agent that works with an app token of an account. It has no cursor and no viewport. */
@JsonClass(generateAdapter = true)
data class AgentMessage(
val tokenId: String,
/** the name of the app token */
val name: String,
)

/** Cursors of the first and the last visible character */
@JsonClass(generateAdapter = true)
data class ViewportMessage(
Expand Down Expand Up @@ -138,6 +148,7 @@ data class GhostMessage(
val selections: List<SelectionMessage> = emptyList(),
val viewport: ViewportMessage? = null,
val avatar: String? = null,
val agent: AgentMessage? = null,
)

@JsonClass(generateAdapter = true)
Expand Down Expand Up @@ -173,6 +184,8 @@ data class ActorInfo(
val username: String,
val displayName: String? = null,
val color: String? = null,
/** set when the changes of this actor come from an AI agent of the account */
val agent: AgentMessage? = null,
)

@JsonClass(generateAdapter = true)
Expand All @@ -181,6 +194,7 @@ data class ActorMessage(
val username: String,
val displayName: String? = null,
val color: String? = null,
val agent: AgentMessage? = null,
val type: String = MessageType.ACTOR,
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -550,6 +550,26 @@ class DocumentSyncSessionTest {
assertEquals("fedcba9876543210", listener.ghosts.single { it.instanceId == "i2" }.avatar)
}

@Test
fun `peers of a snapshot and of a presence name their agent`() {
val listener = EditorListener()
val (server, session) = connectedSession(listener)

session.onMessage(
"""{"type":"presence-snapshot","documentId":"${server.documentId}","peers":[
{"documentId":"${server.documentId}","clientId":"agent-0123456789ab","instanceId":"i1","accountId":"a1","username":"bob","deviceName":"Claude Code",
"agent":{"tokenId":"t1","name":"Claude Code"},"selections":[]}
]}"""
)
assertEquals(RemoteAgent("t1", "Claude Code"), listener.peers.single().agent)

session.onMessage(
"""{"type":"presence","documentId":"${server.documentId}","clientId":"c2","instanceId":"i2","accountId":"a1","username":"bob",
"selections":[]}"""
)
assertEquals(null, listener.peers.single { it.instanceId == "i2" }.agent)
}

@Test
fun `hello names the instance and its color, the same after a reconnect`() {
val session = DocumentSyncSession("doc", InMemoryDocumentStore(), EditorListener(), instanceId = "0f".repeat(16))
Expand Down
Loading