Skip to content

Commit ead5c51

Browse files
committed
fix(acp): preserve source runtime ownership for bound turns
1 parent 90ae49a commit ead5c51

3 files changed

Lines changed: 141 additions & 54 deletions

File tree

‎src/auto-reply/reply/dispatch-from-config.abort-and-dedupe.test-utils.ts‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
33
import type { OpenClawConfig } from "../../config/config.js";
44
import { createApprovalNativeRouteReporter } from "../../infra/approval-native-route-coordinator.js";
55
import type { SessionBindingRecord } from "../../infra/outbound/session-binding-service.js";
6+
import { createTestRegistry } from "../../test-utils/channel-plugins.js";
67
import type { MsgContext } from "../templating.js";
78
import type { GetReplyOptions, ReplyPayload } from "../types.js";
89
import {
@@ -1054,10 +1055,39 @@ describe("dispatchReplyFromConfig", () => {
10541055
SessionKey: sourceSessionKey,
10551056
BodyForAgent: "continue",
10561057
});
1058+
const preparedLookup = vi.fn(async ({ agentId }: { agentId: string }) => {
1059+
if (agentId !== "main") {
1060+
throw new Error(`unexpected prepared reply dispatch owner ${agentId}`);
1061+
}
1062+
return Object.freeze({
1063+
agentId: "main",
1064+
agentDir: "/tmp/main-agent",
1065+
workspaceDir: "/tmp/main-workspace",
1066+
config: cfg,
1067+
modelCatalog: { entries: [], routeVariants: [] },
1068+
inboundPluginRegistry: createTestRegistry([]),
1069+
});
1070+
});
1071+
const runtimeLoaders = await import("./dispatch-from-config.runtime-loaders.js");
1072+
const preparedLoader = vi.spyOn(runtimeLoaders, "loadPreparedModelRuntime").mockResolvedValue({
1073+
loadPublishedGatewayReplyDispatchRuntime: preparedLookup,
1074+
} as never);
10571075

1058-
const result = await dispatchReplyFromConfig({ ctx, cfg, dispatcher, replyResolver });
1076+
let result: Awaited<ReturnType<typeof dispatchReplyFromConfig>>;
1077+
try {
1078+
result = await dispatchReplyFromConfig({
1079+
ctx,
1080+
cfg,
1081+
dispatcher,
1082+
replyResolver,
1083+
usePublishedModelRuntime: true,
1084+
});
1085+
} finally {
1086+
preparedLoader.mockRestore();
1087+
}
10591088

10601089
expect(result.queuedFinal).toBe(true);
1090+
expect(preparedLookup).toHaveBeenCalledWith({ agentId: "main" });
10611091
expect(sessionBindingMocks.resolveByConversation).toHaveBeenCalledWith({
10621092
channel: "discord",
10631093
accountId: "default",

‎src/auto-reply/reply/dispatch-from-config.gather.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,10 +324,17 @@ export async function gatherDispatchRequest(
324324
const routeReplyThreadId = replyRoute.threadId ?? routeThreadId;
325325
const inboundAudio = hasInboundAudio(ctx);
326326
const sessionTtsAuto = normalizeTtsAutoMode(sessionStoreEntry.entry?.ttsAuto);
327+
// A bound ACP key names an external harness, not a configured model-runtime owner.
328+
// Keep the source owner for Gateway dispatch while ACP execution uses the bound target below.
329+
const preparedReplyDispatchAgentId = boundAcpDispatchSessionKey
330+
? resolveSessionAgentId({ sessionKey, config: cfg, fallbackAgentId: ctx.AgentId })
331+
: sessionAgentId;
327332
const preparedReplyDispatchRuntime = params.usePublishedModelRuntime
328333
? await traceReplyPhase("reply.load_prepared_dispatch_runtime", async () => {
329334
const { loadPublishedGatewayReplyDispatchRuntime } = await loadPreparedModelRuntime();
330-
return await loadPublishedGatewayReplyDispatchRuntime({ agentId: sessionAgentId });
335+
return await loadPublishedGatewayReplyDispatchRuntime({
336+
agentId: preparedReplyDispatchAgentId,
337+
});
331338
})
332339
: undefined;
333340
const workspaceDir =

‎src/gateway/gateway-acp-bind.live.test.ts‎

Lines changed: 102 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,30 @@ function extractAssistantTexts(messages: unknown[]): string[] {
118118
return texts;
119119
}
120120

121+
function findAssistantReplyAfterUserToken(messages: unknown[], token: string): string | null {
122+
let sawTokenUserMessage = false;
123+
for (const entry of messages) {
124+
if (!entry || typeof entry !== "object") {
125+
continue;
126+
}
127+
const role = (entry as { role?: unknown }).role;
128+
const text = extractFirstTextBlock(entry);
129+
if (role === "user" && typeof text === "string" && text.includes(token)) {
130+
sawTokenUserMessage = true;
131+
continue;
132+
}
133+
if (
134+
sawTokenUserMessage &&
135+
role === "assistant" &&
136+
typeof text === "string" &&
137+
text.trim().length > 0
138+
) {
139+
return text;
140+
}
141+
}
142+
return null;
143+
}
144+
121145
function createAcpProbePhrase(words: string, nonce: string): string {
122146
return `${words} ${nonce.toLowerCase()}`;
123147
}
@@ -318,6 +342,43 @@ describe("ACP bind live probe prompts", () => {
318342
});
319343
});
320344

345+
describe("ACP bind transcript correlation", () => {
346+
const textMessage = (role: "assistant" | "user", text: string) => ({
347+
role,
348+
content: [{ type: "text", text }],
349+
});
350+
351+
it("does not accept an assistant reply that precedes the routed user turn", () => {
352+
expect(
353+
findAssistantReplyAfterUserToken(
354+
[textMessage("assistant", "late spawn reply"), textMessage("user", "follow-up token")],
355+
"follow-up token",
356+
),
357+
).toBeNull();
358+
});
359+
360+
it("skips non-text assistant entries before the routed textual reply", () => {
361+
expect(
362+
findAssistantReplyAfterUserToken(
363+
[
364+
textMessage("user", "follow-up token"),
365+
{ role: "assistant", content: [{ type: "toolCall", name: "read" }] },
366+
textMessage("assistant", "bound reply"),
367+
],
368+
"follow-up token",
369+
),
370+
).toBe("bound reply");
371+
});
372+
});
373+
374+
describe("ACP bind agent.wait diagnostics", () => {
375+
it("includes the terminal error returned by the gateway", () => {
376+
expect(formatAgentWaitFailure({ status: "error", error: "ACP turn failed" })).toContain(
377+
"ACP turn failed",
378+
);
379+
});
380+
});
381+
321382
function formatAssistantTextPreview(texts: string[], maxChars = 600): string {
322383
const combined = texts.join("\n\n").trim();
323384
if (!combined) {
@@ -416,7 +477,7 @@ async function waitForAgentRunOk(
416477
runId: string,
417478
timeoutMs = LIVE_TIMEOUT_MS,
418479
) {
419-
const result: { status?: string } = await client.request(
480+
const result: { status?: string; [key: string]: unknown } = await client.request(
420481
"agent.wait",
421482
{
422483
runId,
@@ -427,10 +488,14 @@ async function waitForAgentRunOk(
427488
},
428489
);
429490
if (result?.status !== "ok") {
430-
throw new Error(`agent.wait failed for ${runId}: status=${String(result?.status)}`);
491+
throw new Error(`agent.wait failed for ${runId}: ${formatAgentWaitFailure(result)}`);
431492
}
432493
}
433494

495+
function formatAgentWaitFailure(result: { status?: string; [key: string]: unknown }): string {
496+
return JSON.stringify(result);
497+
}
498+
434499
async function sendChatAndWait(params: {
435500
client: GatewayClient;
436501
sessionKey: string;
@@ -747,33 +812,43 @@ describeLive("gateway live (ACP bind)", () => {
747812
}
748813
}
749814
if (!firstBoundHistory) {
750-
try {
751-
const firstBoundTurn = await waitForAssistantTurn({
752-
client,
815+
// Correlate by transcript order instead of counts: a late spawn reply
816+
// precedes this uniquely tokened user turn and cannot satisfy the check.
817+
const deadline = Date.now() + 60_000;
818+
let correlatedHistory: { messages?: unknown[] } | null = null;
819+
let correlatedAssistantText = "";
820+
while (Date.now() < deadline && !correlatedHistory) {
821+
const history: { messages?: unknown[] } = await client.request("chat.history", {
753822
sessionKey: spawnedSessionKey,
754-
minAssistantCount: 1,
755-
timeoutMs: 60_000,
823+
limit: 200,
756824
});
757-
firstBoundHistory = {
758-
messages: firstBoundTurn.messages,
759-
lastAssistantText: firstBoundTurn.lastAssistantText,
760-
matchedAssistantText: firstBoundTurn.lastAssistantText,
761-
};
762-
} catch (error) {
763-
if (liveAgent !== "claude") {
764-
throw error;
825+
correlatedAssistantText =
826+
findAssistantReplyAfterUserToken(history.messages ?? [], followupToken) ?? "";
827+
if (correlatedAssistantText) {
828+
correlatedHistory = history;
829+
} else {
830+
await sleep(500);
765831
}
766-
firstBoundHistory = { messages: [], lastAssistantText: "", matchedAssistantText: "" };
767-
logLiveStep("bound follow-up response not observed; continuing to marker probe");
768832
}
833+
if (!correlatedHistory) {
834+
throw new Error(
835+
`bound follow-up did not land: no assistant reply after the ${followupToken} user turn`,
836+
);
837+
}
838+
const assistantTexts = extractAssistantTexts(correlatedHistory.messages ?? []);
839+
firstBoundHistory = {
840+
messages: correlatedHistory.messages ?? [],
841+
lastAssistantText: assistantTexts.at(-1) ?? "",
842+
matchedAssistantText: correlatedAssistantText,
843+
};
769844
}
770845
const observedFollowupToken =
771846
firstBoundHistory.matchedAssistantText.includes(followupToken);
772847
const firstAssistantCount = extractAssistantTexts(firstBoundHistory.messages).length;
773848

774849
let recallHistory: Awaited<ReturnType<typeof waitForAssistantText>> | null = null;
775850
const expectedRecallAssistantCount = firstAssistantCount + 1;
776-
const maxRecallAttempts = liveAgent === "claude" ? 3 : 1;
851+
const maxRecallAttempts = 1;
777852
for (let attempt = 0; attempt < maxRecallAttempts && !recallHistory; attempt += 1) {
778853
await sendChatAndWait({
779854
client,
@@ -792,7 +867,7 @@ describeLive("gateway live (ACP bind)", () => {
792867
sessionKey: spawnedSessionKey,
793868
contains: followupToken,
794869
minAssistantCount: expectedRecallAssistantCount,
795-
timeoutMs: liveAgent === "claude" ? 60_000 : 25_000,
870+
timeoutMs: 25_000,
796871
});
797872
} catch {
798873
if (attempt === maxRecallAttempts - 1) {
@@ -802,40 +877,15 @@ describeLive("gateway live (ACP bind)", () => {
802877
}
803878
}
804879
if (!recallHistory) {
805-
if (liveAgent === "claude") {
806-
try {
807-
const recallTurn = await waitForAssistantTurn({
808-
client,
809-
sessionKey: spawnedSessionKey,
810-
minAssistantCount: expectedRecallAssistantCount,
811-
timeoutMs: 60_000,
812-
});
813-
recallHistory = {
814-
messages: recallTurn.messages,
815-
lastAssistantText: recallTurn.lastAssistantText,
816-
matchedAssistantText: recallTurn.lastAssistantText,
817-
};
818-
logLiveStep(
819-
"bound memory recall response did not repeat token; using turn progression",
820-
);
821-
} catch {
822-
recallHistory = firstBoundHistory;
823-
logLiveStep(
824-
"bound memory recall response not observed; continuing from previous bound transcript",
825-
);
826-
}
827-
} else {
828-
// Live ACP harnesses can miss or significantly delay this intermediate recall turn.
829-
// Continue from the previously observed bound transcript and validate marker/image/cron
830-
// on subsequent turns.
831-
recallHistory = firstBoundHistory;
832-
logLiveStep(
833-
"bound memory recall response not observed; continuing from previous bound transcript",
834-
);
835-
}
880+
// The intermediate recall is advisory for every connector; the later
881+
// marker remains the shared strict proof of bound transcript progress.
882+
recallHistory = firstBoundHistory;
883+
logLiveStep(
884+
"bound memory recall response not observed; continuing from previous bound transcript",
885+
);
836886
}
837887
const recallAssistantText = recallHistory.matchedAssistantText;
838-
if (liveAgent === "claude" && recallAssistantText.includes(recallToken)) {
888+
if (recallAssistantText.includes(recallToken)) {
839889
expect(recallAssistantText).toContain(followupToken);
840890
expect(recallAssistantText).toContain(recallToken);
841891
}
@@ -913,7 +963,7 @@ describeLive("gateway live (ACP bind)", () => {
913963
client,
914964
sessionKey: spawnedSessionKey,
915965
minAssistantCount: markerAssistantCount + 1,
916-
timeoutMs: liveAgent === "claude" ? 60_000 : 45_000,
966+
timeoutMs: 45_000,
917967
});
918968
} catch {
919969
if (attempt === 1) {

0 commit comments

Comments
 (0)