fix(prompt-gate): harden internal prompt dispatch
This commit is contained in:
@@ -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
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -285,7 +285,7 @@ describe("createTeamSendMessageTool", () => {
|
||||
expect(calls[0]?.directory).toBe(resolveBaseDir(fixture.config))
|
||||
})
|
||||
|
||||
test("#given recipient OpenCode session is busy #when team_send_message attempts live delivery #then it leaves the message unread without starting another reply", async () => {
|
||||
test("#given recipient OpenCode session is busy #when team_send_message attempts live delivery #then it reserves the message in the central prompt queue", async () => {
|
||||
// given
|
||||
const fixture = await createTeamFixture()
|
||||
let promptCalls = 0
|
||||
@@ -309,11 +309,10 @@ describe("createTeamSendMessageTool", () => {
|
||||
// then
|
||||
expect(promptCalls).toBe(0)
|
||||
const unread = await listUnreadMessages(fixture.teamRunId, "m2", fixture.config)
|
||||
expect(unread).toHaveLength(1)
|
||||
expect(unread[0]?.body).toBe("ping while busy")
|
||||
expect(unread).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("#given rapid live deliveries to one recipient #when the first prompt just dispatched #then the next message stays unread instead of starting another reply", async () => {
|
||||
test("#given rapid live deliveries to one recipient #when the first prompt just dispatched #then the next message is queued instead of starting another reply", async () => {
|
||||
// given
|
||||
const fixture = await createTeamFixture()
|
||||
const { client, calls } = createRecordingClient()
|
||||
@@ -335,11 +334,10 @@ describe("createTeamSendMessageTool", () => {
|
||||
expect(calls).toHaveLength(1)
|
||||
expect(calls[0]?.parts[0]?.text).toContain("first ping")
|
||||
const unread = await listUnreadMessages(fixture.teamRunId, "m2", fixture.config)
|
||||
expect(unread).toHaveLength(1)
|
||||
expect(unread[0]?.body).toBe("second ping")
|
||||
expect(unread).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("#given live delivery left a rapid message unread #when recipient idle wake fires immediately #then the wake hint does not start a second reply", async () => {
|
||||
test("#given live delivery queued a rapid message #when recipient idle wake fires immediately #then the wake hint does not start a second reply", async () => {
|
||||
// given
|
||||
const fixture = await createTeamFixture()
|
||||
const { client, calls } = createRecordingClient()
|
||||
@@ -373,8 +371,7 @@ describe("createTeamSendMessageTool", () => {
|
||||
expect(calls).toHaveLength(1)
|
||||
expect(calls[0]?.parts[0]?.text).toContain("first ping")
|
||||
const unread = await listUnreadMessages(fixture.teamRunId, "m2", fixture.config)
|
||||
expect(unread).toHaveLength(1)
|
||||
expect(unread[0]?.body).toBe("second ping")
|
||||
expect(unread).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("live delivery pins the recipient's resolved subagent_type and model on promptAsync", async () => {
|
||||
|
||||
@@ -4,8 +4,9 @@ import { type ToolDefinition, tool } from "@opencode-ai/plugin/tool"
|
||||
import { z } from "zod"
|
||||
|
||||
import type { TeamModeConfig } from "../../../config/schema/team-mode"
|
||||
import { dispatchInternalPrompt } from "../../../hooks/shared/prompt-async-gate"
|
||||
import { dispatchInternalPrompt, isInternalPromptDispatchAccepted } from "../../../hooks/shared/prompt-async-gate"
|
||||
import { log } from "../../../shared/logger"
|
||||
import { isAmbiguousPromptDispatchFailure } from "../../../shared/prompt-failure-classifier"
|
||||
import { applyMemberSessionRouting, buildMemberPromptBody } from "../member-session-routing"
|
||||
import { buildEnvelope } from "../team-mailbox/poll"
|
||||
import {
|
||||
@@ -68,26 +69,6 @@ const TeamSendMessageArgsSchema = z.object({
|
||||
|
||||
type DeliveryReservation = Awaited<ReturnType<typeof reserveMessageForDelivery>>
|
||||
|
||||
function extractPromptFailureMessage(error: unknown): string {
|
||||
if (typeof error === "string") return error
|
||||
if (error instanceof Error) return error.message
|
||||
if (typeof error === "object" && error !== null) {
|
||||
const record = error as Record<string, unknown>
|
||||
if (typeof record.message === "string") return record.message
|
||||
try {
|
||||
return JSON.stringify(error)
|
||||
} catch {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return String(error)
|
||||
}
|
||||
|
||||
function shouldKeepReservationAfterFailedLivePrompt(error: unknown): boolean {
|
||||
const message = extractPromptFailureMessage(error)
|
||||
return message.includes("Unexpected EOF") || message.includes("timed out")
|
||||
}
|
||||
|
||||
async function resolveTeamRuntimeDetails(
|
||||
teamRunId: string,
|
||||
sessionID: string,
|
||||
@@ -230,7 +211,7 @@ async function deliverLive(
|
||||
query: { directory: recipientMember.worktreePath ?? directory },
|
||||
},
|
||||
})
|
||||
if (promptResult.status === "failed" && shouldKeepReservationAfterFailedLivePrompt(promptResult.error)) {
|
||||
if (promptResult.status === "failed" && isAmbiguousPromptDispatchFailure(promptResult.error)) {
|
||||
await markLiveDeliveryPending(teamRunId, recipientName, message.messageId, config)
|
||||
log("[team-mailbox] live delivery prompt failed after dispatch attempt, keeping reservation pending", {
|
||||
teamRunId,
|
||||
@@ -241,7 +222,7 @@ async function deliverLive(
|
||||
})
|
||||
continue
|
||||
}
|
||||
if (promptResult.status !== "dispatched") {
|
||||
if (!isInternalPromptDispatchAccepted(promptResult)) {
|
||||
log("[team-mailbox] live delivery skipped by promptAsync gate, falling back to inbox injection", {
|
||||
status: promptResult.status,
|
||||
teamRunId,
|
||||
|
||||
Reference in New Issue
Block a user