Skip to content

Commit 01ea77e

Browse files
authored
fix: apply Discord model picker choices without false failures (#135382)
* fix: preserve native model picker selections and replies Carry the admitted catalog into native commands and reuse completed capability facts. Preserve post-hook channel suppression through settlement so picker acknowledgements are not replaced by generic recovery. Reported-by: @Call44 (#133550). Reverified the existing #134731 repair from #135095 with an isolated Control UI click and reload. * fix: satisfy model picker delivery lint guards Narrow observed final-delivery promises before aggregation and avoid a shadowed test catalog binding. Targeted lint and 278 reply regressions pass.
1 parent 4a49ceb commit 01ea77e

14 files changed

Lines changed: 286 additions & 86 deletions

‎extensions/discord/src/monitor/native-command-agent-reply.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ export async function dispatchDiscordNativeAgentReply(params: {
7979
if (params.suppressReplies) {
8080
return {
8181
visibleReplySent: false,
82-
suppression: { reason: "no_visible_result" as const },
82+
suppression: { reason: "channel_transform" as const },
8383
};
8484
}
8585
const payloadDelivered = await deliverDiscordInteractionReply({
@@ -111,7 +111,7 @@ export async function dispatchDiscordNativeAgentReply(params: {
111111
if (
112112
params.suppressReplies &&
113113
info.kind === "final" &&
114-
result?.suppression?.reason === "no_visible_result" &&
114+
result?.suppression?.reason === "channel_transform" &&
115115
payload.text?.trim()
116116
) {
117117
hiddenFinalReply = payload;

‎extensions/discord/src/monitor/native-command.plugin-dispatch.test.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1268,12 +1268,12 @@ describe("Discord native plugin command dispatch", () => {
12681268
expect(interaction.deleteReply).toHaveBeenCalledTimes(1);
12691269
});
12701270

1271-
it("preserves a hidden error final and its metadata without sending it to Discord", async () => {
1271+
it.each([false, true])("preserves a hidden final and metadata (isError=%s)", async (isError) => {
12721272
const cfg = createConfig();
12731273
const interaction = createInteraction();
12741274
interaction.responseState = "deferred";
12751275
const finalReply = setReplyPayloadMetadata(
1276-
{ text: "scope-aware model selection result", isError: true },
1276+
{ text: "scope-aware model selection result", isError },
12771277
{ assistantMessageIndex: 3 },
12781278
);
12791279
nativeCommandRuntime.dispatchChannelInboundTurn = async (plan) => {
@@ -1282,6 +1282,10 @@ describe("Discord native plugin command dispatch", () => {
12821282
}
12831283
const info = { kind: "final" as const };
12841284
const deliveryResult = await plan.delivery.deliver(finalReply, info);
1285+
expect(deliveryResult).toEqual({
1286+
visibleReplySent: false,
1287+
suppression: { reason: "channel_transform" },
1288+
});
12851289
await plan.delivery.onDelivered?.(finalReply, info, deliveryResult);
12861290
return {
12871291
admission: { kind: "dispatch" },
@@ -1315,7 +1319,7 @@ describe("Discord native plugin command dispatch", () => {
13151319
});
13161320

13171321
expect(result.hiddenFinalReply).toBe(finalReply);
1318-
expect(result.hiddenFinalReply?.isError).toBe(true);
1322+
expect(result.hiddenFinalReply?.isError).toBe(isError);
13191323
expect(interaction.followUp).not.toHaveBeenCalled();
13201324
expect(interaction.reply).not.toHaveBeenCalled();
13211325
expect(interaction.deleteReply).toHaveBeenCalledTimes(1);
@@ -1330,6 +1334,11 @@ describe("Discord native plugin command dispatch", () => {
13301334
{
13311335
label: "empty final",
13321336
payload: { text: " " },
1337+
suppression: { reason: "channel_transform" as const },
1338+
},
1339+
{
1340+
label: "ordinary invisible result",
1341+
payload: { text: "uncaptured fallback" },
13331342
suppression: { reason: "no_visible_result" as const },
13341343
},
13351344
])("does not capture a hidden final for $label", async ({ payload, suppression }) => {

‎src/agents/prepared-model-catalog.scoped-thinking.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Turn-path thinking reuses published facts before manifest/scoped discovery fallback.
22
import { beforeEach, describe, expect, it, vi } from "vitest";
3+
import type { ModelCatalogEntry, ModelCatalogSnapshot } from "./model-catalog.types.js";
34

45
const manifestCatalogMock = vi.fn((..._args: unknown[]): Array<Record<string, unknown>> => []);
56
const scopedStaticMock = vi.fn(
@@ -94,6 +95,38 @@ describe("loadProviderScopedThinkingCatalog", () => {
9495
expect(scopedLiveMock).not.toHaveBeenCalled();
9596
});
9697

98+
it.each(["thinking", "input"] as const)(
99+
"reuses completed owner catalogs for runtime-only %s capabilities",
100+
async (capability) => {
101+
const entry: ModelCatalogEntry = {
102+
...ollamaEntry,
103+
api: "ollama",
104+
baseUrl: "https://ollama.invalid",
105+
input: ["text", "image"],
106+
};
107+
const completed: ModelCatalogSnapshot = { entries: [entry], routeVariants: [entry] };
108+
publishedSnapshotMock.mockImplementation((input: unknown) => ({
109+
config: (input as { config: unknown }).config,
110+
modelCatalog: { entries: [], routeVariants: [] },
111+
readFullModelCatalog: () => completed,
112+
}));
113+
const { loadProviderScopedThinkingCatalog } = await import("./prepared-model-catalog.js");
114+
const catalog = await loadProviderScopedThinkingCatalog({
115+
config: {},
116+
provider: entry.provider,
117+
model: entry.id,
118+
...(capability === "input"
119+
? { requiredInputRoute: { api: entry.api, baseUrl: entry.baseUrl } }
120+
: {}),
121+
});
122+
123+
expect(catalog).toEqual([expect.objectContaining(entry)]);
124+
expect(manifestCatalogMock).not.toHaveBeenCalled();
125+
expect(scopedStaticMock).not.toHaveBeenCalled();
126+
expect(scopedLiveMock).not.toHaveBeenCalled();
127+
},
128+
);
129+
97130
it("resolves manifest-backed models without any scoped catalog build", async () => {
98131
manifestCatalogMock.mockReturnValue([
99132
{ provider: "openai", id: "gpt-5.6-luna", reasoning: true },

‎src/agents/prepared-model-catalog.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -396,7 +396,7 @@ export async function loadProviderScopedThinkingCatalog(params: {
396396
const entries = normalizeThinkingCatalogProviders(augmented.entries);
397397
return params.requiredInputRoute !== undefined && !entryResolved(entries) ? [] : entries;
398398
};
399-
const publishedCatalog = getPreparedModelCatalogSnapshot(scopedParams);
399+
const publishedCatalog = getAvailablePreparedModelCatalogSnapshot(scopedParams);
400400
if (publishedCatalog && entryResolved(publishedCatalog.entries)) {
401401
return await augmentHarnessCatalog(publishedCatalog);
402402
}

‎src/auto-reply/reply/dispatch-from-config.delivery-and-tts.test-utils.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,74 @@ describe("dispatchReplyFromConfig", () => {
9393
);
9494
});
9595

96+
it.each([
97+
{ name: "channel-owned final", outcomes: ["channel_transform"], fallback: false },
98+
{ name: "ordinary invisible final", outcomes: ["no_visible_result"], fallback: true },
99+
{
100+
name: "later invisible final",
101+
outcomes: ["channel_transform", "no_visible_result"],
102+
fallback: true,
103+
},
104+
{
105+
name: "later cancelled final",
106+
outcomes: ["channel_transform", "cancelled"],
107+
fallback: true,
108+
},
109+
{
110+
name: "later pre-send failure",
111+
outcomes: ["channel_transform", "failed"],
112+
fallback: true,
113+
},
114+
])("preserves post-hook suppression without masking $name", async ({ outcomes, fallback }) => {
115+
setNoAbort();
116+
const delivered: ReplyPayload[] = [];
117+
const dispatcher = createReplyDispatcher({
118+
beforeDeliver: (payload) => {
119+
if (payload.text === "cancelled") {
120+
return null;
121+
}
122+
if (payload.text === "failed") {
123+
throw new Error("pre-send failure");
124+
}
125+
return { ...payload, text: `checked:${payload.text}` };
126+
},
127+
deliver: async (payload) => {
128+
delivered.push(payload);
129+
return {
130+
visibleReplySent: false,
131+
suppression: {
132+
reason:
133+
payload.text === "checked:channel_transform"
134+
? "channel_transform"
135+
: "no_visible_result",
136+
},
137+
};
138+
},
139+
});
140+
const result = await dispatchReplyFromConfig({
141+
ctx: buildTestCtx({
142+
Provider: "discord",
143+
Surface: "discord",
144+
SessionKey: "agent:main:discord:direct:owner",
145+
CommandSource: "native",
146+
}),
147+
cfg: emptyConfig,
148+
dispatcher,
149+
replyResolver: vi.fn(async () => outcomes.map((text) => ({ text }))),
150+
});
151+
dispatcher.markComplete();
152+
const receipt = await dispatcher.waitForIdle();
153+
154+
expect(
155+
delivered.filter((payload) => payload.text === "checked:channel_transform"),
156+
).toHaveLength(outcomes.includes("channel_transform") ? 1 : 0);
157+
expect(delivered.some((payload) => payload.text?.includes("No reply was generated"))).toBe(
158+
fallback,
159+
);
160+
expect(result.noVisibleReplyFallbackEligible === true).toBe(fallback);
161+
expect(receipt?.anyVisibleDelivered).toBe(false);
162+
});
163+
96164
it("does not dispatch a settled final reply after its session writer is replaced", async () => {
97165
setNoAbort();
98166
sessionStoreMocks.currentEntry = {

‎src/auto-reply/reply/dispatch-from-config.final-outcome-counts.test.ts‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,41 @@
11
// Tests settled dispatcher outcome accounting for dispatch-from-config runs.
22
import { describe, expect, it } from "vitest";
33
import { PlatformMessageNotDispatchedError } from "../../infra/outbound/deliver-types.js";
4-
import { createReplyDispatcher } from "./reply-dispatcher.js";
4+
import {
5+
attachReplyDispatchUndeliveredFallback,
6+
captureReplyDispatchDeliveryOutcome,
7+
createReplyDispatcher,
8+
} from "./reply-dispatcher.js";
59

610
describe("settled dispatcher final outcomes", () => {
11+
it.each(["channel_transform", "no_visible_result"])(
12+
"keeps %s distinct when a payload has an undelivered alternative",
13+
async (reason) => {
14+
const delivered: string[] = [];
15+
const payload = { text: "primary" };
16+
const outcome = captureReplyDispatchDeliveryOutcome(payload);
17+
attachReplyDispatchUndeliveredFallback(payload, { text: "alternative" });
18+
const dispatcher = createReplyDispatcher({
19+
deliver: async (reply) => {
20+
delivered.push(reply.text ?? "");
21+
return reply.text === "primary"
22+
? { visibleReplySent: false, suppression: { reason } }
23+
: { visibleReplySent: true };
24+
},
25+
});
26+
27+
dispatcher.sendFinalReply(payload);
28+
dispatcher.markComplete();
29+
const receipt = await dispatcher.waitForIdle();
30+
31+
const suppressed = reason === "channel_transform";
32+
expect(delivered).toEqual(suppressed ? ["primary"] : ["primary", "alternative"]);
33+
await expect(outcome.promise).resolves.toBe(suppressed ? "channel-transform" : "delivered");
34+
expect(receipt?.anyVisibleDelivered).toBe(!suppressed);
35+
expect(receipt?.counts.final.deliveredNotVisible).toBe(suppressed ? 1 : 0);
36+
},
37+
);
38+
739
it("rethrows an opted-in proven no-send failure when nothing was visible", async () => {
840
const error = new PlatformMessageNotDispatchedError("offline before dispatch", {
941
cause: new Error("offline"),

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

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -91,8 +91,7 @@ export async function finalizeDispatchAndAudit(state: ExecuteDispatchReadyState)
9191
let acceptedFinal = false;
9292
let sessionWriterDeliveryRevoked = false;
9393
let channelTransformSuppressedFinal = false;
94-
const finalDeliveries: Promise<ReplyDispatchDeliveryOutcome>[] = [];
95-
let allQueuedFinalsObserved = true;
94+
const finalDeliveries: Array<Promise<ReplyDispatchDeliveryOutcome> | undefined> = [];
9695
const sentFinalPayloadDedupeKeys = new Set<string>();
9796
let deferredTtsTextPending = state.progressState.accumulatedBlockTtsText;
9897
for (const [replyIndex, reply] of replies.entries()) {
@@ -196,11 +195,7 @@ export async function finalizeDispatchAndAudit(state: ExecuteDispatchReadyState)
196195
queuedFinal = finalReply.queuedFinal || queuedFinal;
197196
routedFinalCount += finalReply.routedFinalCount;
198197
if (finalReply.queuedFinal) {
199-
if (finalReply.dispatcherOutcome) {
200-
finalDeliveries.push(finalReply.dispatcherOutcome);
201-
} else {
202-
allQueuedFinalsObserved = false;
203-
}
198+
finalDeliveries.push(finalReply.dispatcherOutcome);
204199
}
205200
if (continuationSettlement) {
206201
if (finalReply.queuedFinal) {
@@ -222,13 +217,13 @@ export async function finalizeDispatchAndAudit(state: ExecuteDispatchReadyState)
222217
throw error;
223218
}
224219
}
225-
const channelTransformSuppressed =
220+
let channelTransformSuppressed =
226221
(state.progressState.channelTransformSuppressed || channelTransformSuppressedFinal) &&
227222
!state.progressState.acceptedReplyPayload &&
228223
!acceptedFinal;
229224

230225
if (attemptedFinalDelivery) {
231-
if (queuedFinal && allQueuedFinalsObserved) {
226+
if (queuedFinal && finalDeliveries.every((outcome) => outcome !== undefined)) {
232227
// Delivery observers run from the queue itself, so direct low-level callers
233228
// reconcile too; the settle task only makes lifecycle owners await it.
234229
const reconcilePendingFinal = Promise.all(finalDeliveries)
@@ -361,6 +356,13 @@ export async function finalizeDispatchAndAudit(state: ExecuteDispatchReadyState)
361356
queuedSettleResult = await turnLedger.settleQueued(getDispatchAbortSignal());
362357
}
363358
if (queuedSettleResult === "settled") {
359+
// Adapter-owned presentation may capture a final after sending hooks. Keep that
360+
// intentional suppression distinct from invisible, cancelled, or failed delivery.
361+
channelTransformSuppressed ||=
362+
noVisibleReplyFallbackAllowed() &&
363+
finalDeliveries.length > 0 &&
364+
finalDeliveries.every((outcome) => outcome !== undefined) &&
365+
(await Promise.all(finalDeliveries)).every((outcome) => outcome === "channel-transform");
364366
sessionWriterDeliveryRevoked ||= replies.some(
365367
(reply) => !state.isSessionWriterDeliveryAuthorized(reply),
366368
);

‎src/auto-reply/reply/dispatch-from-config.turn-ledger.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ describe("requireQueuedReplyDelivery", () => {
3333
it.each([
3434
["delivered", true],
3535
["delivered-not-visible", false],
36+
["channel-transform", false],
3637
["cancelled", false],
3738
["failed-before-deliver", false],
3839
["failed-deliver", false],

‎src/auto-reply/reply/get-reply-native-slash-fast-path.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import path from "node:path";
22
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
33
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
44
import { testing as cliBackendsTesting } from "../../agents/cli-backends.test-support.js";
5+
import type { ModelCatalogSnapshot } from "../../agents/model-catalog.types.js";
56
import * as preparedModelCatalog from "../../agents/prepared-model-catalog.js";
67
import type { OpenClawConfig } from "../../config/config.js";
78
import {
@@ -113,6 +114,7 @@ describe("maybeResolveNativeSlashCommandFastReply", () => {
113114
body: string,
114115
config?: OpenClawConfig,
115116
response: { shouldContinue: boolean; reply?: { text: string } } = { shouldContinue: true },
117+
preparedCatalog?: ModelCatalogSnapshot,
116118
) {
117119
handleCommandsMock.mockResolvedValue(response);
118120
const commandName = body.slice(1).split(/\s+/, 1)[0] ?? "";
@@ -150,6 +152,7 @@ describe("maybeResolveNativeSlashCommandFastReply", () => {
150152
agentCfg: config?.agents?.defaults,
151153
commandAuthorized: true,
152154
typing,
155+
preparedModelCatalog: preparedCatalog,
153156
});
154157

155158
return { result, typing, storePath: resolvedConfig.session?.store };
@@ -261,6 +264,42 @@ describe("maybeResolveNativeSlashCommandFastReply", () => {
261264
},
262265
);
263266

267+
it("applies native model selections using the admitted catalog without rediscovery", async () => {
268+
vi.stubEnv("OPENCLAW_TEST_FAST", "0");
269+
const storePath = path.join(tempDirs.make("openclaw-native-prepared-model-"), "sessions.json");
270+
vi.mocked(preparedModelCatalog.loadPreparedModelCatalogSnapshot).mockRejectedValue(
271+
new Error("native selection must not rediscover the prepared catalog"),
272+
);
273+
const { result } = await resolveNativeDirectiveCommand(
274+
"/model ollama/picker-secondary -s",
275+
{ session: { store: storePath } },
276+
{ shouldContinue: true },
277+
{
278+
entries: [
279+
{
280+
provider: "ollama",
281+
id: "picker-secondary",
282+
name: "Picker secondary",
283+
api: "ollama",
284+
baseUrl: "http://127.0.0.1:11434",
285+
reasoning: false,
286+
contextWindow: 32768,
287+
},
288+
],
289+
routeVariants: [],
290+
},
291+
);
292+
293+
expect(result).toMatchObject({
294+
handled: true,
295+
reply: { text: expect.stringContaining("ollama/picker-secondary") },
296+
});
297+
expect(
298+
loadExactSessionEntry({ sessionKey: "agent:main:telegram:123", storePath })?.entry,
299+
).toMatchObject({ providerOverride: "ollama", modelOverride: "picker-secondary" });
300+
expect(preparedModelCatalog.loadPreparedModelCatalogSnapshot).not.toHaveBeenCalled();
301+
});
302+
264303
it("marks native /compact terminal replies for delivery under message_tool_only (#90185)", async () => {
265304
const reply = {
266305
text: "⚙️ Compaction skipped: no real conversation messages yet • Context 12.1k",

0 commit comments

Comments
 (0)