fix(plugin): normalize event session ids

Handle OpenCode session events that carry the session ID under properties.info.id or properties.info.sessionID so background tasks and continuation hooks do not miss idle/error/delete events.

Add regression coverage for nested session.idle events completing background tasks and waking continuation hooks.
This commit is contained in:
YeonGyu-Kim
2026-05-12 11:48:18 +09:00
parent 67f90a819e
commit 4da48555ee
51 changed files with 740 additions and 254 deletions
+19
View File
@@ -304,6 +304,25 @@ describe("ralph-loop", () => {
expect(state?.iteration).toBe(2)
})
test("should inject continuation when idle event carries session id in info", async () => {
// given - active loop state and nested session event shape
const hook = createRalphLoopHook(createMockPluginInput())
hook.startLoop("session-info-idle", "Build a feature", { maxIterations: 10 })
// when - session goes idle with id under info
await hook.event({
event: {
type: "session.idle",
properties: { info: { id: "session-info-idle" } },
},
})
// then - continuation should be injected for that session
expect(promptCalls.length).toBe(1)
expect(promptCalls[0].sessionID).toBe("session-info-idle")
expect(promptCalls[0].text).toContain("RALPH LOOP")
})
test("should settle idle before injecting continuation", async () => {
// given - active loop state with a configured idle settle delay
const hook = createRalphLoopHook(createMockPluginInput(), { idleSettleMs: 25 })
@@ -213,6 +213,77 @@ describe("ralph-loop non-abort error continuation", () => {
expect(hook.getState()?.iteration).toBe(3)
})
test("continues after retry run activity from legacy message.part.updated part session id", async () => {
// given - an active loop retries a recoverable runtime error
const hook = createRalphLoopHook({
directory: testDirectory,
project: testDirectory,
worktree: testDirectory,
serverUrl: "http://localhost:4096",
$: async () => ({}),
client: {
session: {
messages: async (options: { path: { id: string } }) => {
messagesCalls.push({ sessionID: options.path.id })
return { data: [] }
},
promptAsync: async (options: {
path: { id: string }
body: { parts: Array<{ type: string; text: string }> }
}) => {
promptCalls.push({
sessionID: options.path.id,
text: options.body.parts[0]?.text ?? "",
})
return {}
},
prompt: async () => ({}),
},
tui: {
showToast: async () => ({}),
},
},
} as never)
hook.startLoop("session-123", "Keep working", {
messageCountAtStart: 0,
maxIterations: 5,
})
await hook.event({
event: {
type: "session.error",
properties: {
sessionID: "session-123",
error: { name: "RuntimeError" },
},
},
})
// when - the retried run emits legacy assistant activity before any stale idle
await hook.event({
event: {
type: "message.part.updated",
properties: {
part: {
id: "part-1",
messageID: "msg-1",
sessionID: "session-123",
type: "text",
text: "working",
},
},
},
})
await hook.event({
event: { type: "session.idle", properties: { sessionID: "session-123" } },
})
// then - the real idle is allowed to continue the loop
expect(promptCalls).toHaveLength(2)
expect(hook.getState()?.iteration).toBe(3)
})
test("skips immediate runtime retry while background tasks are running", async () => {
// given - an active loop owns running background work
const hook = createRalphLoopHook({
@@ -1,5 +1,6 @@
import type { PluginInput } from "@opencode-ai/plugin"
import { log } from "../../shared/logger"
import { resolveMessageEventSessionID, resolveSessionEventID } from "../../shared/event-session-id"
import type { RalphLoopOptions, RalphLoopState } from "./types"
import { HOOK_NAME } from "./constants"
import { handleDetectedCompletion } from "./completion-handler"
@@ -36,12 +37,6 @@ function hasRunningBackgroundTasks(
: false
}
function getInfoSessionID(props: Record<string, unknown> | undefined): string | undefined {
const info = props?.info as Record<string, unknown> | undefined
const sessionID = info?.sessionID
return typeof sessionID === "string" ? sessionID : undefined
}
function getRuntimeRetryActivitySessionID(
eventType: string,
props: Record<string, unknown> | undefined,
@@ -49,20 +44,19 @@ function getRuntimeRetryActivitySessionID(
if (eventType === "message.updated") {
const info = props?.info as Record<string, unknown> | undefined
const role = info?.role
return role === "assistant" ? getInfoSessionID(props) : undefined
return role === "assistant" ? resolveMessageEventSessionID(props) : undefined
}
if (eventType === "message.part.updated") {
if (typeof props?.sessionID === "string") return props.sessionID
return getInfoSessionID(props)
return resolveMessageEventSessionID(props)
}
if (eventType === "message.part.delta") {
return typeof props?.sessionID === "string" ? props.sessionID : undefined
return resolveMessageEventSessionID(props)
}
if (eventType === "tool.execute.before" || eventType === "tool.execute.after") {
return typeof props?.sessionID === "string" ? props.sessionID : undefined
return resolveMessageEventSessionID(props)
}
return undefined
@@ -198,7 +192,7 @@ export function createRalphLoopEventHandler(
}
if (event.type === "session.idle") {
const sessionID = props?.sessionID as string | undefined
const sessionID = resolveSessionEventID(props)
if (!sessionID) return
if (inFlightSessions.has(sessionID)) {
@@ -389,7 +383,7 @@ export function createRalphLoopEventHandler(
}
if (event.type === "session.error") {
const sessionID = props?.sessionID as string | undefined
const sessionID = resolveSessionEventID(props)
const error = props?.error
if (!sessionID || isAbortError(error)) {
handleErroredLoopSession(props, options.loopState)
@@ -1,4 +1,5 @@
import { log } from "../../shared/logger"
import { resolveSessionEventID } from "../../shared/event-session-id"
import { HOOK_NAME } from "./constants"
import type { RalphLoopState } from "./types"
@@ -11,13 +12,13 @@ export function handleDeletedLoopSession(
props: Record<string, unknown> | undefined,
loopState: LoopStateController,
): boolean {
const sessionInfo = props?.info as { id?: string } | undefined
if (!sessionInfo?.id) return false
const sessionID = resolveSessionEventID(props)
if (!sessionID) return false
const state = loopState.getState()
if (state?.session_id === sessionInfo.id) {
if (state?.session_id === sessionID) {
loopState.clear()
log(`[${HOOK_NAME}] Session deleted, loop cleared`, { sessionID: sessionInfo.id })
log(`[${HOOK_NAME}] Session deleted, loop cleared`, { sessionID })
}
return true
}
@@ -26,7 +27,7 @@ export function handleErroredLoopSession(
props: Record<string, unknown> | undefined,
loopState: LoopStateController,
): boolean {
const sessionID = props?.sessionID as string | undefined
const sessionID = resolveSessionEventID(props)
const error = props?.error as { name?: string } | undefined
if (error?.name === "MessageAbortedError") {