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
Expand Up @@ -82,7 +82,9 @@ class CodexRuntime(
val process: Process,
val client: CodexJsonRpcClient,
val readerJob: Job,
)
) {
val loadedThreads = CodexLoadedThreads()
}

@Volatile private var server: ServerProcess? = null

Expand Down Expand Up @@ -350,6 +352,7 @@ class CodexRuntime(
val result = call("thread/start", params)
val thread = result["thread"]?.jsonObject ?: error("Codex did not return a thread")
val session = threadToSession(thread)
server?.loadedThreads?.markLoaded(session.id)
val requestedTitle = title?.takeIf(String::isNotBlank)
if (requestedTitle == null) return session
// Applied to the returned object directly rather than re-fetching the thread: the rename
Expand Down Expand Up @@ -407,7 +410,10 @@ class CodexRuntime(
attachments: List<PromptAttachment> = emptyList(),
) {
val params = codexTurnStartParams(sessionId, prompt, model, effort, serviceTier, attachments)
runCatching { call("turn/start", params) }
runCatching {
ensureThreadLoaded(sessionId)
call("turn/start", params)
}
.onSuccess { result ->
// Recorded by turn id, not just session id, so onServerEnded can evict exactly this
// turn's in-progress assistant message from CodexItemParser if the process dies
Expand Down Expand Up @@ -473,6 +479,19 @@ class CodexRuntime(
server = null
}

/**
* A new app-server process (after the app restarts, or after the previous one died) only knows
* a thread from its rollout on disk and answers `turn/start` on it with "thread not found"
* until the thread is loaded with `thread/resume`.
*/
private suspend fun ensureThreadLoaded(threadId: String) {
ensureServer()
val current = server ?: return
if (!current.loadedThreads.needsResume(threadId)) return
current.client.call("thread/resume", codexThreadResumeParams(threadId))
current.loadedThreads.markLoaded(threadId)
}

private suspend fun call(
method: String,
params: JsonElement? = null,
Expand Down Expand Up @@ -742,6 +761,30 @@ internal fun resolveCodexTurnSettings(
/** The app-server's explicit "standard speed" tier, which turns off a fast tier left on earlier. */
internal const val DEFAULT_SERVICE_TIER = "default"

/**
* The threads one app-server process has loaded, by `thread/start` or `thread/resume`. Each process
* gets its own instance, so a restarted app-server starts with none.
*/
internal class CodexLoadedThreads {
private val ids: MutableSet<String> = ConcurrentHashMap.newKeySet()

fun needsResume(threadId: String): Boolean = threadId !in ids

fun markLoaded(threadId: String) {
ids += threadId
}
}

/**
* The `thread/resume` params that load [threadId] into the running app-server. Its past turns are
* left out of the response: the chat already renders them from its own message store.
*/
internal fun codexThreadResumeParams(threadId: String): JsonObject =
buildJsonObject {
put("threadId", JsonPrimitive(threadId))
put("excludeTurns", JsonPrimitive(true))
}

/**
* The `turn/start` params for one prompt. [effort] and [serviceTier] are sent only when non-blank:
* callers that want the explicit-every-turn behaviour resolve them with [resolveCodexTurnSettings]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.yugahashimoto.andcode.runtime.local

import kotlinx.serialization.json.jsonPrimitive
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test

/**
* A thread created by an earlier app-server process must be loaded with `thread/resume` before
* `turn/start`, or Codex answers "thread not found" (seen with codex-cli 0.172.0 after restarting
* the app). [CodexLoadedThreads] tracks which threads the current process has loaded.
*/
class CodexThreadResumeTest {
@Test
fun `a thread the process has not loaded needs a resume`() {
assertTrue(CodexLoadedThreads().needsResume("thr_1"))
}

@Test
fun `a loaded thread is not resumed again`() {
val loaded = CodexLoadedThreads()
loaded.markLoaded("thr_1")

assertFalse(loaded.needsResume("thr_1"))
assertTrue(loaded.needsResume("thr_2"))
}

@Test
fun `a new process starts with no loaded threads`() {
CodexLoadedThreads().markLoaded("thr_1")

assertTrue(CodexLoadedThreads().needsResume("thr_1"))
}

@Test
fun `resume params name the thread and leave out its past turns`() {
val params = codexThreadResumeParams("thr_1")

assertEquals("thr_1", params.getValue("threadId").jsonPrimitive.content)
assertEquals("true", params.getValue("excludeTurns").jsonPrimitive.content)
}
}