From adb86f103239a91ed674c7df4a934492af519677 Mon Sep 17 00:00:00 2001 From: Mayaskara Date: Sun, 29 Nov 2026 15:13:18 +0530 Subject: [PATCH] fix(codex): show history of chats started outside the app Codex chats from the terminal or another device opened empty. --- .../andcode/runtime/local/CodexHistory.kt | 177 ++++++++ .../andcode/runtime/local/CodexRuntime.kt | 10 +- .../andcode/runtime/local/CodexHistoryTest.kt | 387 ++++++++++++++++++ 3 files changed, 573 insertions(+), 1 deletion(-) create mode 100644 app/src/main/java/com/yugahashimoto/andcode/runtime/local/CodexHistory.kt create mode 100644 app/src/test/java/com/yugahashimoto/andcode/runtime/local/CodexHistoryTest.kt diff --git a/app/src/main/java/com/yugahashimoto/andcode/runtime/local/CodexHistory.kt b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/CodexHistory.kt new file mode 100644 index 000000000..f99845c39 --- /dev/null +++ b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/CodexHistory.kt @@ -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, +): List { + if (entries.isEmpty()) return emptyList() + val parser = CodexItemParser() + val messagesById = linkedMapOf() + 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() + + suspend fun listMessages(sessionId: String): List { + 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 { + val entries = mutableListOf() + 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 diff --git a/app/src/main/java/com/yugahashimoto/andcode/runtime/local/CodexRuntime.kt b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/CodexRuntime.kt index cd5713205..c82cb5f6f 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/runtime/local/CodexRuntime.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/CodexRuntime.kt @@ -78,6 +78,13 @@ class CodexRuntime( */ private val sessionsWithTurnInFlight = ConcurrentHashMap() + 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, @@ -373,12 +380,13 @@ class CodexRuntime( ) } - fun listMessages(sessionId: String): List = messageStore.list(sessionId) + suspend fun listMessages(sessionId: String): List = 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) diff --git a/app/src/test/java/com/yugahashimoto/andcode/runtime/local/CodexHistoryTest.kt b/app/src/test/java/com/yugahashimoto/andcode/runtime/local/CodexHistoryTest.kt new file mode 100644 index 000000000..7ea9a6212 --- /dev/null +++ b/app/src/test/java/com/yugahashimoto/andcode/runtime/local/CodexHistoryTest.kt @@ -0,0 +1,387 @@ +package com.yugahashimoto.andcode.runtime.local + +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +class CodexHistoryTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private val json = Json { ignoreUnknownKeys = true } + + private fun parseObject(raw: String): JsonObject = json.parseToJsonElement(raw).jsonObject + + private fun newStore(): ClaudeMessageStore = ClaudeMessageStore(File(tempFolder.root, "codex-messages.json"), defaultCodexJson) + + @Test + fun `entries convert into ordered user and assistant messages across two turns with tools and timestamps`() { + val entries = + listOf( + parseObject( + """ + { + "turnId": "turn-1", + "item": { + "type": "userMessage", + "id": "um-1", + "content": [{"type": "text", "text": "Check files", "text_elements": []}], + "startedAtMs": 1795939368593, + "completedAtMs": 1795939368599 + }, + "startedAtMs": 1795939368593, + "completedAtMs": 1795939368599 + } + """.trimIndent(), + ), + parseObject( + """ + { + "turnId": "turn-1", + "item": { + "type": "commandExecution", + "id": "cmd-1", + "command": "ls -la", + "status": "completed", + "aggregatedOutput": "README.md\n" + }, + "startedAtMs": 1795939369000, + "completedAtMs": 1795939369500 + } + """.trimIndent(), + ), + parseObject( + """ + { + "turnId": "turn-1", + "item": { + "type": "agentMessage", + "id": "am-1", + "text": "Found README.md.", + "phase": "final_answer" + }, + "startedAtMs": 1795939370000, + "completedAtMs": 1795939370708 + } + """.trimIndent(), + ), + parseObject( + """ + { + "turnId": "turn-2", + "item": { + "type": "userMessage", + "id": "um-2", + "content": [{"type": "text", "text": "Reply with exactly three words.", "text_elements": []}], + "startedAtMs": 1795939400000, + "completedAtMs": 1795939400010 + } + } + """.trimIndent(), + ), + parseObject( + """ + { + "turnId": "turn-2", + "item": { + "type": "agentMessage", + "id": "am-2", + "text": "Exactly three words.", + "phase": "final_answer", + "startedAtMs": 1795939401000, + "completedAtMs": 1795939401200 + } + } + """.trimIndent(), + ), + ) + + val messages = codexHistoryMessages("thr-1", entries) + + assertEquals(4, messages.size) + + // Turn 1 user message + assertEquals("um-1", messages[0].info.id) + assertEquals("user", messages[0].info.role) + assertEquals("Check files", messages[0].text) + assertEquals(1795939368593L, messages[0].info.time.created) + assertEquals(1795939368599L, messages[0].info.time.completed) + + // Turn 1 assistant message merges commandExecution and agentMessage in order, spanning both timestamps + assertEquals("codex-turn-turn-1", messages[1].info.id) + assertEquals("assistant", messages[1].info.role) + assertEquals(2, messages[1].parts.size) + assertEquals("tool", messages[1].parts[0].type) + assertEquals("bash", messages[1].parts[0].tool) + assertEquals("completed", messages[1].parts[0].state?.get("status")?.jsonPrimitive?.content) + assertEquals("text", messages[1].parts[1].type) + assertEquals("Found README.md.", messages[1].parts[1].text) + assertEquals(1795939369000L, messages[1].info.time.created) + assertEquals(1795939370708L, messages[1].info.time.completed) + + // Turn 2 falls back to item-level timestamps when entry-level ones are absent + assertEquals("um-2", messages[2].info.id) + assertEquals("user", messages[2].info.role) + assertEquals("Reply with exactly three words.", messages[2].text) + assertEquals(1795939400000L, messages[2].info.time.created) + + assertEquals("codex-turn-turn-2", messages[3].info.id) + assertEquals("assistant", messages[3].info.role) + assertEquals("Exactly three words.", messages[3].text) + assertEquals(1795939401000L, messages[3].info.time.created) + assertEquals(1795939401200L, messages[3].info.time.completed) + } + + @Test + fun `backfill pages across nextCursor, persists to store, and does not re-fetch on reload`() = + runBlocking { + val storeFile = File(tempFolder.root, "codex-messages.json") + val store = ClaudeMessageStore(storeFile, defaultCodexJson) + val seenParams = mutableListOf() + val pages = + mapOf( + null to + parseObject( + """ + { + "data": [ + { + "turnId": "turn-1", + "item": { + "type": "userMessage", + "id": "um-1", + "content": [{"type": "text", "text": "Hello", "text_elements": []}] + }, + "startedAtMs": 1000, + "completedAtMs": 1005 + } + ], + "nextCursor": "cursor-page-2" + } + """.trimIndent(), + ), + "cursor-page-2" to + parseObject( + """ + { + "data": [ + { + "turnId": "turn-1", + "item": { + "type": "agentMessage", + "id": "am-1", + "text": "Hi there" + }, + "startedAtMs": 2000, + "completedAtMs": 2500 + } + ], + "nextCursor": null + } + """.trimIndent(), + ), + ) + val backfill = + CodexHistoryBackfill( + messageStore = store, + isTurnInFlight = { false }, + fetchPage = { params -> + seenParams += params + val cursor = params["cursor"]?.jsonPrimitive?.contentOrNull + pages.getValue(cursor) + }, + ) + + val messages = backfill.listMessages("thr-1") + + assertEquals(2, seenParams.size) + assertEquals("thr-1", seenParams[0]["threadId"]?.jsonPrimitive?.content) + assertEquals("asc", seenParams[0]["sortDirection"]?.jsonPrimitive?.content) + assertNull(seenParams[0]["cursor"]) + assertEquals("cursor-page-2", seenParams[1]["cursor"]?.jsonPrimitive?.content) + + assertEquals(listOf("Hello", "Hi there"), messages.map { it.text }) + + // Subsequent call serves straight from the store without hitting the app-server again. + val cached = backfill.listMessages("thr-1") + assertEquals(2, seenParams.size) + assertEquals(messages, cached) + + // Flush persisted to disk so a fresh store instance sees the backfilled transcript. + val reloaded = ClaudeMessageStore(storeFile, defaultCodexJson).list("thr-1") + assertEquals(listOf("Hello", "Hi there"), reloaded.map { it.text }) + } + + @Test + fun `empty thread is remembered per process so reloads do not re-query`() = + runBlocking { + val store = newStore() + var calls = 0 + val backfill = + CodexHistoryBackfill( + messageStore = store, + isTurnInFlight = { false }, + fetchPage = { + calls++ + parseObject("""{"data": [], "nextCursor": null}""") + }, + ) + + assertTrue(backfill.listMessages("thr-empty").isEmpty()) + assertTrue(backfill.listMessages("thr-empty").isEmpty()) + assertEquals(1, calls) + } + + @Test + fun `failing call falls back to the store without throwing and can succeed on a later retry`() = + runBlocking { + val store = newStore() + var shouldFail = true + var calls = 0 + val backfill = + CodexHistoryBackfill( + messageStore = store, + isTurnInFlight = { false }, + fetchPage = { + calls++ + if (shouldFail) throw IllegalStateException("Method not found") + parseObject( + """ + { + "data": [ + { + "turnId": "turn-1", + "item": { + "type": "userMessage", + "id": "um-1", + "content": [{"type": "text", "text": "Recovered", "text_elements": []}] + }, + "startedAtMs": 5000 + } + ], + "nextCursor": null + } + """.trimIndent(), + ) + }, + ) + + assertTrue(backfill.listMessages("thr-1").isEmpty()) + assertEquals(1, calls) + + shouldFail = false + val recovered = backfill.listMessages("thr-1") + assertEquals(2, calls) + assertEquals(listOf("Recovered"), recovered.map { it.text }) + } + + @Test + fun `does not backfill while a turn is in flight`() = + runBlocking { + val store = newStore() + var calls = 0 + var inFlight = true + val backfill = + CodexHistoryBackfill( + messageStore = store, + isTurnInFlight = { inFlight }, + fetchPage = { + calls++ + parseObject("""{"data": [], "nextCursor": null}""") + }, + ) + + assertTrue(backfill.listMessages("thr-live").isEmpty()) + assertEquals(0, calls) + + inFlight = false + assertTrue(backfill.listMessages("thr-live").isEmpty()) + assertEquals(1, calls) + } + + @Test + fun `does not overwrite store if a turn starts while history fetch is suspended`() = + runBlocking { + val store = newStore() + var inFlight = false + val backfill = + CodexHistoryBackfill( + messageStore = store, + isTurnInFlight = { inFlight }, + fetchPage = { + // Simulate a turn starting in AndCode while the RPC was in flight. + inFlight = true + parseObject( + """ + { + "data": [ + { + "turnId": "turn-old", + "item": { + "type": "userMessage", + "id": "um-old", + "content": [{"type": "text", "text": "Stale", "text_elements": []}] + }, + "startedAtMs": 1000 + } + ], + "nextCursor": null + } + """.trimIndent(), + ) + }, + ) + + assertTrue(backfill.listMessages("thr-race").isEmpty()) + assertFalse(store.list("thr-race").any { it.text == "Stale" }) + } + + @Test + fun `paging stops at maxPages even if the server keeps returning cursors`() = + runBlocking { + val store = newStore() + var calls = 0 + val backfill = + CodexHistoryBackfill( + messageStore = store, + isTurnInFlight = { false }, + fetchPage = { + calls++ + parseObject( + """ + { + "data": [ + { + "turnId": "turn-$calls", + "item": { + "type": "userMessage", + "id": "um-$calls", + "content": [{"type": "text", "text": "Msg $calls", "text_elements": []}] + }, + "startedAtMs": ${calls * 1000L} + } + ], + "nextCursor": "cursor-${calls + 1}" + } + """.trimIndent(), + ) + }, + maxPages = 3, + ) + + val messages = backfill.listMessages("thr-capped") + assertEquals(3, calls) + assertEquals(listOf("Msg 1", "Msg 2", "Msg 3"), messages.map { it.text }) + } +}