Skip to content
Open
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
@@ -0,0 +1,177 @@
package com.yugahashimoto.andcode.runtime.local

import android.util.Log
import com.yugahashimoto.andcode.core.api.OpenCodeMessage
import com.yugahashimoto.andcode.core.api.OpenCodeTime
import kotlinx.coroutines.CancellationException
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.longOrNull
import java.util.concurrent.ConcurrentHashMap

internal const val THREAD_ITEMS_LIST_METHOD = "thread/items/list"

private const val DEFAULT_PAGE_SIZE = 100
private const val DEFAULT_MAX_PAGES = 50
private const val TAG = "CodexHistory"

/**
* The `thread/items/list` params for one ascending page of [threadId]'s item history.
*
* Full-history hydration via `thread/resume`/`thread/read` with `includeTurns` is deprecated for
* paginated threads on Codex 0.172+, which directs callers to page through `thread/items/list`.
*/
internal fun codexThreadItemsListParams(
threadId: String,
cursor: String? = null,
limit: Int = DEFAULT_PAGE_SIZE,
): JsonObject =
buildJsonObject {
put("threadId", JsonPrimitive(threadId))
cursor?.takeIf(String::isNotBlank)?.let { put("cursor", JsonPrimitive(it)) }
put("limit", JsonPrimitive(limit))
put("sortDirection", JsonPrimitive("asc"))
}

/**
* Converts `thread/items/list` [entries] for [sessionId] into [OpenCodeMessage]s in display order.
*
* Uses a dedicated [CodexItemParser] instance so the runtime's live parser (and any in-progress
* turns it is assembling) is untouched. Live UI events are discarded; only the assembled messages
* are kept, carrying the historical `startedAtMs`/`completedAtMs` timestamps from each entry or
* item rather than the parser's wall-clock `now()`.
*/
internal fun codexHistoryMessages(
sessionId: String,
entries: List<JsonObject>,
): List<OpenCodeMessage> {
if (entries.isEmpty()) return emptyList()
val parser = CodexItemParser()
val messagesById = linkedMapOf<String, OpenCodeMessage>()
var currentTurnId: String? = null

for (entry in entries) {
val turnId = entry.string("turnId") ?: continue
val item = entry["item"] as? JsonObject ?: continue
if (currentTurnId != null && currentTurnId != turnId) {
parser.forgetTurn(currentTurnId)
}
currentTurnId = turnId

val body =
buildJsonObject {
put("threadId", JsonPrimitive(sessionId))
put("turnId", JsonPrimitive(turnId))
put("item", item)
}
val parsed = parser.handleNotification(sessionId, "item/completed", body)
val startedAtMs = entry.longOrNull("startedAtMs") ?: item.longOrNull("startedAtMs")
val completedAtMs = entry.longOrNull("completedAtMs") ?: item.longOrNull("completedAtMs")

for (message in parsed.messages) {
val previous = messagesById[message.info.id]
val mergedTime = mergeHistoryTime(previous?.info?.time, message.info.time, startedAtMs, completedAtMs)
messagesById[message.info.id] = message.copy(info = message.info.copy(time = mergedTime))
}
}
currentTurnId?.let(parser::forgetTurn)
return messagesById.values.toList()
}

private fun mergeHistoryTime(
previous: OpenCodeTime?,
fallback: OpenCodeTime,
startedAtMs: Long?,
completedAtMs: Long?,
): OpenCodeTime {
if (previous == null) {
val created = startedAtMs ?: completedAtMs ?: return fallback
return OpenCodeTime(
created = created,
updated = completedAtMs ?: created,
completed = completedAtMs,
)
}
val created = if (startedAtMs != null && startedAtMs < previous.created) startedAtMs else previous.created
val updated = listOfNotNull(previous.updated, startedAtMs, completedAtMs).maxOrNull() ?: created
val completed = listOfNotNull(previous.completed, completedAtMs).maxOrNull()
return previous.copy(
created = created,
updated = updated,
completed = completed,
)
}

/**
* Backfills [messageStore] from Codex's `thread/items/list` when a thread has no locally cached
* messages (for example, conversations started in the terminal or transferred from another device).
*
* Threads with a turn in flight in AndCode are skipped because the live notification stream owns
* them. Threads that Codex confirms have no items are remembered per process so opening an empty
* thread does not re-query the app-server on every reload; RPC failures are logged and fall back
* to whatever the store already holds without throwing into the chat screen.
*/
internal class CodexHistoryBackfill(
private val messageStore: ClaudeMessageStore,
private val isTurnInFlight: (String) -> Boolean,
private val fetchPage: suspend (JsonObject) -> JsonObject,
private val pageSize: Int = DEFAULT_PAGE_SIZE,
private val maxPages: Int = DEFAULT_MAX_PAGES,
) {
private val emptySessions = ConcurrentHashMap.newKeySet<String>()

suspend fun listMessages(sessionId: String): List<OpenCodeMessage> {
val stored = messageStore.list(sessionId)
if (stored.isNotEmpty() || isTurnInFlight(sessionId) || sessionId in emptySessions) {
return stored
}
val entries =
try {
fetchAllEntries(sessionId)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Throwable) {
Log.w(TAG, "Could not backfill Codex history for $sessionId", error)
return messageStore.list(sessionId)
}
// Re-check after suspending: a live turn may have started or populated the store while the
// RPC was in flight, in which case the live stream owns the transcript.
val current = messageStore.list(sessionId)
if (current.isNotEmpty() || isTurnInFlight(sessionId)) {
return current
}
val messages = codexHistoryMessages(sessionId, entries)
if (messages.isEmpty()) {
emptySessions += sessionId
return emptyList()
}
messages.forEach { message -> messageStore.upsert(sessionId, message) }
messageStore.flush()
return messageStore.list(sessionId)
}

fun forget(sessionId: String) {
emptySessions -= sessionId
}

private suspend fun fetchAllEntries(sessionId: String): List<JsonObject> {
val entries = mutableListOf<JsonObject>()
var cursor: String? = null
repeat(maxPages) {
val response = fetchPage(codexThreadItemsListParams(sessionId, cursor = cursor, limit = pageSize))
val data = response["data"] as? JsonArray
data?.mapNotNullTo(entries) { it as? JsonObject }
val nextCursor = response.string("nextCursor")?.takeIf(String::isNotBlank)
if (nextCursor == null || nextCursor == cursor) return entries
cursor = nextCursor
}
return entries
}
}

private fun JsonObject.string(key: String): String? = (this[key] as? JsonPrimitive)?.contentOrNull

private fun JsonObject.longOrNull(key: String): Long? = (this[key] as? JsonPrimitive)?.longOrNull
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,13 @@ class CodexRuntime(
*/
private val sessionsWithTurnInFlight = ConcurrentHashMap<String, String>()

private val historyBackfill =
CodexHistoryBackfill(
messageStore = messageStore,
isTurnInFlight = sessionsWithTurnInFlight::containsKey,
fetchPage = { params -> call(THREAD_ITEMS_LIST_METHOD, params) },
)

private class ServerProcess(
val process: Process,
val client: CodexJsonRpcClient,
Expand Down Expand Up @@ -373,12 +380,13 @@ class CodexRuntime(
)
}

fun listMessages(sessionId: String): List<OpenCodeMessage> = messageStore.list(sessionId)
suspend fun listMessages(sessionId: String): List<OpenCodeMessage> = historyBackfill.listMessages(sessionId)

suspend fun deleteSession(sessionId: String): Boolean =
runCatching {
call("thread/delete", buildJsonObject { put("threadId", JsonPrimitive(sessionId)) })
messageStore.remove(sessionId)
historyBackfill.forget(sessionId)
true
}.getOrDefault(false)

Expand Down
Loading