fix(prompt-gate): harden internal prompt dispatch

This commit is contained in:
YeonGyu-Kim
2026-05-19 16:02:18 +09:00
parent 6c63372ef9
commit 1492bffd20
49 changed files with 1488 additions and 141 deletions
+14 -2
View File
@@ -3,7 +3,10 @@ import type { PluginInput } from "@opencode-ai/plugin"
import type { BackgroundTaskConfig, TmuxConfig } from "../../config/schema"
import { setContinuationMarkerSource } from "../../features/run-continuation-state"
import type { ModelFallbackControllerAccessor } from "../../hooks/model-fallback"
import { dispatchInternalPrompt, type PromptAsyncGateResult } from "../../hooks/shared/prompt-async-gate"
import {
dispatchInternalPrompt,
type PromptAsyncGateResult,
} from "../../hooks/shared/prompt-async-gate"
import { isSessionActive as isOpenCodeSessionActive } from "../../hooks/shared/session-idle-settle"
import {
createInternalAgentTextPart,
@@ -485,7 +488,7 @@ export class BackgroundManager {
private restoreTaskAfterSkippedResume(
task: BackgroundTask,
snapshot: ResumeTaskSnapshot,
skippedStatus: Exclude<PromptAsyncGateResult["status"], "dispatched" | "failed">,
skippedStatus: Exclude<PromptAsyncGateResult["status"], "dispatched" | "queued" | "failed">,
): void {
log("[background-agent] Restoring task after skipped resume prompt:", {
taskId: task.id,
@@ -1306,6 +1309,7 @@ The fallback retry session is now created and can be inspected directly.
sessionID: existingTask.sessionId,
source: "background-agent-resume",
settleMs: 0,
queueBehavior: "defer",
input: {
path: { id: existingTask.sessionId },
body: {
@@ -1332,6 +1336,14 @@ The fallback retry session is now created and can be inspected directly.
if (promptResult.status === "failed") {
throw promptResult.error
}
if (promptResult.status === "queued") {
log("[background-agent] resume prompt queued by prompt dispatcher:", {
taskId: existingTask.id,
sessionID: existingTask.sessionId,
queuedBy: promptResult.queuedBy,
})
return
}
if (promptResult.status !== "dispatched") {
log("[background-agent] resume prompt skipped by promptAsync gate:", {
taskId: existingTask.id,
@@ -1,7 +1,14 @@
import { resolveRegisteredAgentName } from "../claude-code-session-state"
import { createInternalAgentTextPart, isSyntheticOrInternalUserMessage, log, messagesInDirectory, normalizeSDKResponse } from "../../shared"
import {
createInternalAgentTextPart,
isAmbiguousPromptDispatchFailure,
isSyntheticOrInternalUserMessage,
log,
messagesInDirectory,
normalizeSDKResponse,
} from "../../shared"
import { isSessionActive as isOpenCodeSessionActive, settleAfterSessionIdle } from "../../hooks/shared/session-idle-settle"
import { dispatchInternalPrompt } from "../../hooks/shared/prompt-async-gate"
import { dispatchInternalPrompt, isInternalPromptDispatchAccepted } from "../../hooks/shared/prompt-async-gate"
import type { PluginInput } from "@opencode-ai/plugin"
type OpencodeClient = PluginInput["client"]
@@ -180,8 +187,9 @@ export class ParentWakeNotifier {
const notificationContent = latestWake.notifications.join("\n\n")
let dispatchStartedAt = Date.now()
try {
const dispatchStartedAt = Date.now()
dispatchStartedAt = Date.now()
const promptResult = await dispatchInternalPrompt({
mode: "async",
client: this.deps.client,
@@ -209,7 +217,7 @@ export class ParentWakeNotifier {
})
return
}
if (promptResult.status !== "dispatched") {
if (!isInternalPromptDispatchAccepted(promptResult)) {
this.requeueWake(sessionID, latestWake)
this.schedulePendingParentWakeFlush(sessionID)
log("[background-agent] Deferred parent wake skipped by promptAsync gate:", {
@@ -221,6 +229,18 @@ export class ParentWakeNotifier {
log("[background-agent] Sent deferred parent wake:", { sessionID })
this.trackDispatchedParentWake(sessionID, latestWake, dispatchStartedAt)
} catch (error) {
if (isAmbiguousPromptDispatchFailure(error)) {
const dispatchedWake = this.cloneParentWake(latestWake)
dispatchedWake.dispatchedAt = dispatchStartedAt
if (await this.hasAcceptedMessageAfterDispatchedParentWake(sessionID, dispatchedWake)) {
this.trackDispatchedParentWake(sessionID, latestWake, dispatchStartedAt)
log("[background-agent] Treated failed parent wake prompt as accepted after observing session history:", {
sessionID,
error,
})
return
}
}
this.requeueWake(sessionID, latestWake)
this.schedulePendingParentWakeFlush(sessionID)
log("[background-agent] Failed to send deferred parent wake:", { sessionID, error })
@@ -1,6 +1,9 @@
import { describe, expect, test } from "bun:test"
import { ParentWakeNotifier } from "./parent-wake-notifier"
import { releaseAllPromptAsyncReservationsForTesting } from "../../hooks/shared/prompt-async-gate"
import {
releaseAllPromptAsyncReservationsForTesting,
releasePromptAsyncReservation,
} from "../../hooks/shared/prompt-async-gate"
type PromptAsyncCall = {
path: { id: string }
@@ -693,6 +696,81 @@ describe("ParentWakeNotifier — user message race guard (issue #4120)", () => {
}
})
test("#given promptAsync stores the wake then reports EOF #when the gate hold expires #then parent wake is not requeued into a duplicate prompt", async () => {
// given
const originalDateNow = Date.now
let now = 1_000
Date.now = () => now
const sessionMessages: SessionMessageStub[] = [
{
info: {
role: "assistant",
finish: "stop",
time: { created: 500 },
},
},
]
const promptAsyncCalls: PromptAsyncCall[] = []
const client = {
session: {
status: async () => ({ data: { "parent-eof-before-return": { type: "idle" } } }),
messages: async () => ({ data: sessionMessages }),
promptAsync: async (call: PromptAsyncCall) => {
promptAsyncCalls.push(call)
sessionMessages.push({
info: {
role: "user",
time: { created: 1_100 },
},
parts: [{ type: "text", text: "task complete\n<!-- OMO_INTERNAL_INITIATOR -->" }],
})
now = 2_000
throw new Error("JSON Parse error: Unexpected EOF")
},
},
} as unknown as ConstructorParameters<typeof ParentWakeNotifier>[0]["client"]
const notifier = new ParentWakeNotifier(
{
client,
directory: "/tmp/test-omo",
enqueueNotificationForParent: async (_sessionID, operation) => {
await operation()
},
},
{
pendingRetryMs: 1_000,
acceptedMessageSkewMs: 100,
toolCallDeferMaxMs: 5_000,
failureRequeueWindowMs: 5_000,
userMessageInProgressWindowMs: 0,
},
)
notifier.queuePendingParentWake(
"parent-eof-before-return",
"task complete",
{ agent: "sisyphus" },
true,
)
try {
// when
await notifier.flushPendingParentWake("parent-eof-before-return")
const released = releasePromptAsyncReservation("parent-eof-before-return", "test:simulate-expired-hold", {
reservedBy: "background-agent-parent-wake",
})
await notifier.flushPendingParentWake("parent-eof-before-return")
// then
expect(released).toBe(true)
expect(promptAsyncCalls).toHaveLength(1)
expect(notifier.getPendingParentWakes().has("parent-eof-before-return")).toBe(false)
} finally {
Date.now = originalDateNow
notifier.shutdown()
releaseAllPromptAsyncReservationsForTesting()
}
})
test("#given accepted wake produces sdk tool-call output #when late failure is requeued #then accepted dispatch is not duplicated", async () => {
// given
const originalDateNow = Date.now
@@ -1,7 +1,7 @@
import type { PluginInput } from "@opencode-ai/plugin"
import { promptWithModelSuggestionRetry } from "../../shared"
import { dispatchInternalPrompt } from "../../shared/prompt-async-gate"
import { dispatchInternalPrompt, isInternalPromptDispatchAccepted } from "../../shared/prompt-async-gate"
type OpencodeClient = PluginInput["client"]
@@ -46,10 +46,10 @@ export function promptAsyncInDirectory(
if (result.status === "failed") {
throw result.error
}
if (result.status !== "dispatched") {
if (!isInternalPromptDispatchAccepted(result)) {
throw new Error(`promptAsync skipped by gate: ${result.status}`)
}
return result.response
return result.status === "dispatched" ? result.response : undefined
})
}