diff --git a/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt b/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt index 5723c1919..83837fd39 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt @@ -28,6 +28,7 @@ import com.yugahashimoto.andcode.data.repository.PullRequestStatusRepository import com.yugahashimoto.andcode.data.repository.RuntimeActivityRepository import com.yugahashimoto.andcode.data.repository.RuntimeCatalogRepository import com.yugahashimoto.andcode.data.repository.SessionAutoArchiver +import com.yugahashimoto.andcode.data.repository.SessionPullRequestDiscovery import com.yugahashimoto.andcode.data.schedule.ScheduleRepository import com.yugahashimoto.andcode.data.settings.AppPreferencesRepository import com.yugahashimoto.andcode.di.appModule @@ -236,6 +237,9 @@ class AndCodeApplication : Application() { lateinit var pullRequestStatusRepository: PullRequestStatusRepository private set + lateinit var sessionPullRequestDiscovery: SessionPullRequestDiscovery + private set + lateinit var deviceStorageAccess: DeviceStorageAccess private set @@ -543,6 +547,14 @@ class AndCodeApplication : Application() { ), messages = AndroidRuntimeCatalogMessages(this), ) + // Learns each recent chat's pull requests from its transcript, so the drawer can badge a + // chat the user has never opened. Built after the registry it reads targets from. + sessionPullRequestDiscovery = + SessionPullRequestDiscovery( + scope = applicationScope, + loadMessages = { ref -> runtimeRegistry.target(ref.runtimeId)?.listMessages(ref.session.id) }, + onDiscovered = pullRequestStatusRepository::trackSession, + ) activityRepository = RuntimeActivityRepository( registry = runtimeRegistry, diff --git a/app/src/main/java/com/yugahashimoto/andcode/core/api/GitHubPullRequest.kt b/app/src/main/java/com/yugahashimoto/andcode/core/api/GitHubPullRequest.kt index 85fbb5eec..5b93e95f7 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/core/api/GitHubPullRequest.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/core/api/GitHubPullRequest.kt @@ -1,5 +1,9 @@ package com.yugahashimoto.andcode.core.api +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull + /** Highest number of pull requests kept from one conversation, newest first. */ const val MAX_TRACKED_PULL_REQUESTS = 5 @@ -80,3 +84,47 @@ fun parsePullRequestRefs(text: String): List { .distinct() .toList() } + +/** + * The one pull request [text] names, or null when it names none - or several. + * + * A piece of text that links several at once is listing them (release notes, `gh pr list`), not + * reporting one, so only a lone link counts as "this part opened a pull request". + */ +fun singlePullRequestIn(text: String): PullRequestRef? = parsePullRequestRefs(text).singleOrNull() + +/** The one pull request a tool call reports in its output or error, or null when it reports none. */ +fun singlePullRequestInTool( + output: String?, + error: String?, +): PullRequestRef? = + (parsePullRequestRefs(output.orEmpty()) + parsePullRequestRefs(error.orEmpty())) + .distinct() + .singleOrNull() + +/** + * Every distinct pull request linked in [messages]' transcript, newest first. + * + * This is the same rule the chat's own badge uses, applied to a transcript that was never opened: + * the drawer scans recent chats so a badge does not have to wait for the user to visit one. + */ +fun pullRequestRefsIn(messages: List): List { + val refs = LinkedHashSet() + messages.forEach { message -> + message.parts.forEach { part -> part.openedPullRequest()?.let(refs::add) } + } + return refs.toList().takeLast(MAX_TRACKED_PULL_REQUESTS).reversed() +} + +private fun OpenCodePart.openedPullRequest(): PullRequestRef? = + when (type) { + "text" -> singlePullRequestIn(text.orEmpty()) + "tool" -> + singlePullRequestInTool( + output = state?.get("output")?.jsonPrimitiveOrNull(), + error = state?.get("error")?.jsonPrimitiveOrNull(), + ) + else -> null + } + +private fun JsonElement.jsonPrimitiveOrNull(): String? = (this as? JsonPrimitive)?.contentOrNull ?: (this as? JsonPrimitive)?.content diff --git a/app/src/main/java/com/yugahashimoto/andcode/data/repository/PullRequestStatusRepository.kt b/app/src/main/java/com/yugahashimoto/andcode/data/repository/PullRequestStatusRepository.kt index e9c6d25aa..981d05ef8 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/data/repository/PullRequestStatusRepository.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/data/repository/PullRequestStatusRepository.kt @@ -109,16 +109,17 @@ class PullRequestStatusRepository( ) { if (sessionId.isBlank() || refs.isEmpty()) return val tracked = refs.distinct().take(MAX_TRACKED_PULL_REQUESTS) - if (sessionRefs.value[sessionId] == tracked) { - track(tracked) - return + // Merge with what is on disk: the chat screen, the drawer and the drawer's transcript + // scan can each record a chat on a different thread, and none may drop a chat another + // just remembered. + synchronized(sessionWriteLock) { + if (sessionRefs.value[sessionId] != tracked) { + val remembered = sessionStore?.sessionPullRequests ?: sessionRefs.value + val updated = remembered + (sessionId to tracked) + sessionRefs.value = updated + sessionStore?.sessionPullRequests = updated + } } - // Merge with what is on disk: the chat screen and the drawer can each hold a repository - // instance in the same process, and neither may drop a chat the other just remembered. - val remembered = sessionStore?.sessionPullRequests ?: sessionRefs.value - val updated = remembered + (sessionId to tracked) - sessionRefs.value = updated - sessionStore?.sessionPullRequests = updated track(tracked) } @@ -126,7 +127,9 @@ class PullRequestStatusRepository( fun refreshTrackedSessions() { // Another repository instance in the same process may have remembered a chat since this // one was built, so take the store's copy before refreshing it. - sessionStore?.let { sessionRefs.value = it.sessionPullRequests } + synchronized(sessionWriteLock) { + sessionStore?.let { sessionRefs.value = it.sessionPullRequests } + } track(sessionRefs.value.values.flatten()) } @@ -139,6 +142,15 @@ class PullRequestStatusRepository( } return clock() - last >= interval } + + private companion object { + /** + * Serializes the session map's read-modify-write across every repository instance in the + * process: the app builds one for the drawer and Koin another for a chat view model, and + * both write the same settings store. + */ + val sessionWriteLock = Any() + } } /** diff --git a/app/src/main/java/com/yugahashimoto/andcode/data/repository/SessionPullRequestDiscovery.kt b/app/src/main/java/com/yugahashimoto/andcode/data/repository/SessionPullRequestDiscovery.kt new file mode 100644 index 000000000..9f166d532 --- /dev/null +++ b/app/src/main/java/com/yugahashimoto/andcode/data/repository/SessionPullRequestDiscovery.kt @@ -0,0 +1,81 @@ +package com.yugahashimoto.andcode.data.repository + +import com.yugahashimoto.andcode.core.api.OpenCodeMessage +import com.yugahashimoto.andcode.core.api.PullRequestRef +import com.yugahashimoto.andcode.core.api.pullRequestRefsIn +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import java.util.concurrent.ConcurrentHashMap + +/** How long a transcript read that failed is left alone before the next attempt. */ +private const val FAILED_SCAN_RETRY_MILLIS = 60_000L + +/** + * Learns which pull requests a chat linked without the user opening it. + * + * The drawer can badge a chat from the association that was remembered while the chat was open, so + * a chat nobody had visited since the feature shipped showed no badge. This scans the transcripts + * of the chats the drawer is about to show and reports what they linked, so the badge is there on + * the first look. + * + * Reads run one at a time and only when the session's updated time differs from the last scan, so + * reopening the drawer costs nothing for chats that have not changed. A session that is open right + * now is skipped: its chat view model already tracks it live. + */ +class SessionPullRequestDiscovery( + private val scope: CoroutineScope, + private val clock: () -> Long = System::currentTimeMillis, + /** Reads a session's transcript, or returns null when it cannot be read right now. */ + private val loadMessages: suspend (RuntimeSessionRef) -> List? = { null }, + /** Records the pull requests a transcript linked, as the repository's session store does. */ + private val onDiscovered: (String, List) -> Unit = { _, _ -> }, +) { + /** Session id to the updated time its transcript was last scanned at. */ + private val scannedRevision = ConcurrentHashMap() + + /** Session id to the earliest time a failed read may be retried. */ + private val retryAfter = ConcurrentHashMap() + + private var job: Job? = null + + /** Scans [sessions]' transcripts for pull request links, newest first, one at a time. */ + fun discover( + sessions: List, + openSessionId: String? = null, + ) { + job?.cancel() + job = + scope.launch { + sessions.forEach { ref -> scan(ref, openSessionId) } + } + } + + private suspend fun scan( + ref: RuntimeSessionRef, + openSessionId: String?, + ) { + val session = ref.session + // A subagent conversation is shown under its parent, and the open chat already records + // its own links while it streams. + if (session.parentId != null || session.id == openSessionId) return + val revision = session.time.updated ?: session.time.created + val waitingForRetry = (retryAfter[session.id] ?: 0L) > clock() + if (scannedRevision[session.id] == revision || waitingForRetry) return + + val messages = + try { + loadMessages(ref) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + retryAfter[session.id] = clock() + FAILED_SCAN_RETRY_MILLIS + return + } ?: return + + val refs = pullRequestRefsIn(messages) + if (refs.isNotEmpty()) onDiscovered(session.id, refs) + scannedRevision[session.id] = revision + } +} diff --git a/app/src/main/java/com/yugahashimoto/andcode/feature/chat/PullRequestLinks.kt b/app/src/main/java/com/yugahashimoto/andcode/feature/chat/PullRequestLinks.kt index b0f171428..4b13cd654 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/feature/chat/PullRequestLinks.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/feature/chat/PullRequestLinks.kt @@ -3,7 +3,8 @@ package com.yugahashimoto.andcode.feature.chat import com.yugahashimoto.andcode.core.api.MAX_TRACKED_PULL_REQUESTS import com.yugahashimoto.andcode.core.api.PullRequestRef import com.yugahashimoto.andcode.core.api.PullRequestStatus -import com.yugahashimoto.andcode.core.api.parsePullRequestRefs +import com.yugahashimoto.andcode.core.api.singlePullRequestIn +import com.yugahashimoto.andcode.core.api.singlePullRequestInTool /** A pull request linked in the open chat, paired with its state once GitHub has answered. */ data class ChatPullRequest( @@ -36,16 +37,11 @@ fun pullRequestRefsIn(messages: List): List { * opens one names one - `gh pr create` prints a single link, and an agent announces its work as it * lands - so a lone link is the signal, and anything longer is a list to be read, not a badge. */ -private fun ChatPart.openedPullRequest(): PullRequestRef? { - val refs = - when (this) { - is ChatPart.Text -> parsePullRequestRefs(text) - // A retried command can report the same pull request twice, once as output and once as - // the error of the attempt before it, and that is still a single pull request. - is ChatPart.Tool -> - (parsePullRequestRefs(output.orEmpty()) + parsePullRequestRefs(error.orEmpty())) - .distinct() - else -> return null - } - return refs.singleOrNull() -} +private fun ChatPart.openedPullRequest(): PullRequestRef? = + when (this) { + is ChatPart.Text -> singlePullRequestIn(text) + // A retried command can report the same pull request twice, once as output and once as + // the error of the attempt before it, and that is still a single pull request. + is ChatPart.Tool -> singlePullRequestInTool(output = output, error = error) + else -> null + } diff --git a/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt b/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt index c840fd7ec..8a3832f4c 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt @@ -943,6 +943,21 @@ fun AndCodeApp( ) } + // The chats the drawer is about to show. Their transcripts are scanned so a badge does not + // depend on the chat having been opened at least once. Keyed by identity and revision rather + // than by the list itself: a badge arriving rebuilds the list but must not restart the scan. + val discoverySessions = + remember(allSessions, recentSessions) { + val visibleIds = browsableSessions(recentSessions).mapTo(HashSet()) { it.id } + allSessions.filter { it.session.id in visibleIds } + } + val discoveryKey = + remember(discoverySessions) { + discoverySessions.map { ref -> + "${ref.runtimeId}:${ref.session.id}:${ref.session.time.updated ?: ref.session.time.created}" + } + } + // Local agents that are actually provisioned. A target reports Unavailable while its agent is // missing, which is exactly the case the switcher must not offer. // @@ -994,9 +1009,6 @@ fun AndCodeApp( fun openDrawer() { keyboardController?.hide() - // A pull request merged or closed elsewhere since the last look should be current when the - // list with its badges appears. - app.pullRequestStatusRepository.refreshTrackedSessions() drawerScope.launch { drawerState.open() } } @@ -1020,8 +1032,15 @@ fun AndCodeApp( navController.navigate(ROUTE_CHAT) { launchSingleTop = true } } - LaunchedEffect(drawerState.isOpen) { - if (drawerState.isOpen) keyboardController?.hide() + LaunchedEffect(drawerState.isOpen, discoveryKey, chatState.sessionId) { + if (!drawerState.isOpen) return@LaunchedEffect + keyboardController?.hide() + // A pull request merged or closed elsewhere since the last look should be current when the + // list with its badges appears. + app.pullRequestStatusRepository.refreshTrackedSessions() + // Chats never opened in this run have no remembered pull request yet; read their + // transcripts so the badges do not wait for the user to visit each one. + app.sessionPullRequestDiscovery.discover(discoverySessions, chatState.sessionId) } val drawerGesturesEnabled = currentRoute in DRAWER_ROOT_ROUTES diff --git a/app/src/test/java/com/yugahashimoto/andcode/core/api/OpenCodePullRequestRefsTest.kt b/app/src/test/java/com/yugahashimoto/andcode/core/api/OpenCodePullRequestRefsTest.kt new file mode 100644 index 000000000..a0745b41e --- /dev/null +++ b/app/src/test/java/com/yugahashimoto/andcode/core/api/OpenCodePullRequestRefsTest.kt @@ -0,0 +1,89 @@ +package com.yugahashimoto.andcode.core.api + +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class OpenCodePullRequestRefsTest { + @Test + fun `reads a pull request out of assistant text`() { + val messages = + listOf( + message( + part( + type = "text", + text = "Opened https://github.com/o/r/pull/7 for review.", + ), + ), + ) + + assertEquals(listOf(PullRequestRef("o", "r", 7)), pullRequestRefsIn(messages)) + } + + @Test + fun `reads a pull request out of tool output and errors`() { + val messages = + listOf( + message(part(type = "tool", state = mapOf("output" to JsonPrimitive("https://github.com/o/r/pull/2")))), + message(part(type = "tool", state = mapOf("error" to JsonPrimitive("reported https://github.com/o/r/pull/3")))), + ) + + assertEquals( + listOf(PullRequestRef("o", "r", 3), PullRequestRef("o", "r", 2)), + pullRequestRefsIn(messages), + ) + } + + @Test + fun `ignores a part that lists several pull requests`() { + val messages = + listOf( + message( + part( + type = "tool", + state = + mapOf( + "output" to + JsonPrimitive( + "https://github.com/o/r/pull/12\nhttps://github.com/o/r/pull/11", + ), + ), + ), + ), + ) + + assertTrue(pullRequestRefsIn(messages).isEmpty()) + } + + @Test + fun `keeps only the newest few pull requests, newest first`() { + val messages = (1..8).map { number -> message(part(type = "text", text = "https://github.com/o/r/pull/$number")) } + + assertEquals( + listOf(8, 7, 6, 5, 4).map { PullRequestRef("o", "r", it) }, + pullRequestRefsIn(messages), + ) + } + + private fun message(vararg parts: OpenCodePart): OpenCodeMessage = + OpenCodeMessage( + info = OpenCodeMessageInfo(id = "m-${parts.first().id}", sessionId = "s", role = "assistant"), + parts = parts.toList(), + ) + + private fun part( + type: String, + text: String? = null, + state: Map? = null, + ): OpenCodePart = + OpenCodePart( + id = "part-${text.orEmpty()}-${state.orEmpty()}", + sessionId = "s", + messageId = "m", + type = type, + text = text, + state = state, + ) +} diff --git a/app/src/test/java/com/yugahashimoto/andcode/data/repository/SessionPullRequestDiscoveryTest.kt b/app/src/test/java/com/yugahashimoto/andcode/data/repository/SessionPullRequestDiscoveryTest.kt new file mode 100644 index 000000000..b57e98e46 --- /dev/null +++ b/app/src/test/java/com/yugahashimoto/andcode/data/repository/SessionPullRequestDiscoveryTest.kt @@ -0,0 +1,171 @@ +package com.yugahashimoto.andcode.data.repository + +import com.yugahashimoto.andcode.core.api.OpenCodeMessage +import com.yugahashimoto.andcode.core.api.OpenCodeMessageInfo +import com.yugahashimoto.andcode.core.api.OpenCodePart +import com.yugahashimoto.andcode.core.api.OpenCodeSession +import com.yugahashimoto.andcode.core.api.OpenCodeTime +import com.yugahashimoto.andcode.core.api.PullRequestRef +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class SessionPullRequestDiscoveryTest { + @Test + fun `scans the transcripts the drawer is about to show and records what they linked`() = + runTest { + val loads = mutableListOf() + val discovered = mutableMapOf>() + val discovery = + discovery( + loads = loads, + onDiscovered = { id, refs -> discovered[id] = refs }, + ) + + discovery.discover(listOf(sessionRef("s1"), sessionRef("s2"))) + advanceUntilIdle() + + assertEquals(listOf("s1", "s2"), loads) + assertEquals(mapOf("s1" to listOf(PullRequestRef("o", "r", 7))), discovered) + } + + @Test + fun `does not rescan a chat whose transcript has not changed`() = + runTest { + val loads = mutableListOf() + val discovery = discovery(loads = loads) + + discovery.discover(listOf(sessionRef("s1", updated = 10))) + advanceUntilIdle() + discovery.discover(listOf(sessionRef("s1", updated = 10))) + advanceUntilIdle() + + assertEquals(listOf("s1"), loads) + } + + @Test + fun `rescans a chat after a newer turn changed its transcript`() = + runTest { + val loads = mutableListOf() + val discovery = discovery(loads = loads) + + discovery.discover(listOf(sessionRef("s1", updated = 10))) + advanceUntilIdle() + discovery.discover(listOf(sessionRef("s1", updated = 11))) + advanceUntilIdle() + + assertEquals(listOf("s1", "s1"), loads) + } + + @Test + fun `skips the chat that is open because its view model already tracks it`() = + runTest { + val loads = mutableListOf() + val discovery = discovery(loads = loads) + + discovery.discover(listOf(sessionRef("s1")), openSessionId = "s1") + advanceUntilIdle() + + assertTrue(loads.isEmpty()) + } + + @Test + fun `skips subagent transcripts that are shown under their parent`() = + runTest { + val loads = mutableListOf() + val discovery = discovery(loads = loads) + + discovery.discover(listOf(sessionRef("child", parentId = "parent"))) + advanceUntilIdle() + + assertTrue(loads.isEmpty()) + } + + @Test + fun `retries a failed read only after the cooldown`() = + runTest { + var now = 1_000L + var fail = true + val loads = mutableListOf() + val discovery = + discovery( + clock = { now }, + loads = loads, + load = { ref -> + if (fail) error("offline") else messagesFor(ref.session.id) + }, + ) + + discovery.discover(listOf(sessionRef("s1", updated = 1))) + advanceUntilIdle() + fail = false + now += 30_000L + discovery.discover(listOf(sessionRef("s1", updated = 1))) + advanceUntilIdle() + + assertEquals(listOf("s1"), loads) + + now += 31_000L + discovery.discover(listOf(sessionRef("s1", updated = 1))) + advanceUntilIdle() + + assertEquals(listOf("s1", "s1"), loads) + } + + private fun TestScope.discovery( + clock: () -> Long = { 0L }, + loads: MutableList = mutableListOf(), + load: suspend (RuntimeSessionRef) -> List? = { messagesFor(it.session.id) }, + onDiscovered: (String, List) -> Unit = { _, _ -> }, + ) = SessionPullRequestDiscovery( + scope = this, + clock = clock, + loadMessages = { ref -> + loads += ref.session.id + load(ref) + }, + onDiscovered = onDiscovered, + ) + + private fun sessionRef( + id: String, + updated: Long = 1L, + parentId: String? = null, + ) = RuntimeSessionRef( + runtimeId = "local", + agent = null, + session = + OpenCodeSession( + id = id, + parentId = parentId, + title = id, + time = OpenCodeTime(created = 1L, updated = updated), + ), + ) + + private fun messagesFor(sessionId: String): List = + if (sessionId != "s1") { + emptyList() + } else { + listOf( + OpenCodeMessage( + info = OpenCodeMessageInfo(id = "m1", sessionId = sessionId, role = "assistant"), + parts = + listOf( + OpenCodePart( + id = "p1", + sessionId = sessionId, + messageId = "m1", + type = "text", + text = "Opened https://github.com/o/r/pull/7", + ), + ), + ), + ) + } +}