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
12 changes: 12 additions & 0 deletions app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -80,3 +84,47 @@ fun parsePullRequestRefs(text: String): List<PullRequestRef> {
.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<OpenCodeMessage>): List<PullRequestRef> {
val refs = LinkedHashSet<PullRequestRef>()
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
Original file line number Diff line number Diff line change
Expand Up @@ -109,24 +109,27 @@ 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)
}

/** Refetches the remembered pull requests whose cached state has gone stale. */
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())
}

Expand All @@ -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()
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -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<OpenCodeMessage>? = { null },
/** Records the pull requests a transcript linked, as the repository's session store does. */
private val onDiscovered: (String, List<PullRequestRef>) -> Unit = { _, _ -> },
) {
/** Session id to the updated time its transcript was last scanned at. */
private val scannedRevision = ConcurrentHashMap<String, Long>()

/** Session id to the earliest time a failed read may be retried. */
private val retryAfter = ConcurrentHashMap<String, Long>()

private var job: Job? = null

/** Scans [sessions]' transcripts for pull request links, newest first, one at a time. */
fun discover(
sessions: List<RuntimeSessionRef>,
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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -36,16 +37,11 @@ fun pullRequestRefsIn(messages: List<ChatMessage>): List<PullRequestRef> {
* 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
}
29 changes: 24 additions & 5 deletions app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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.
//
Expand Down Expand Up @@ -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() }
}

Expand All @@ -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
Expand Down
Loading
Loading