Skip to content

Commit 9671a44

Browse files
committed
fix: keep channel sends on the selected plugin
1 parent 1c9770a commit 9671a44

10 files changed

Lines changed: 399 additions & 79 deletions

‎docs/plugins/sdk-channel-plugins.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,12 @@ them with `listMessageReceiptPlatformIds(...)` or
6060
`resolveMessageReceiptPrimaryId(...)` instead of keeping parallel `messageIds`
6161
fields.
6262

63+
Channel actions and adapter capabilities come from the selected plugin
64+
registration. An omitted `actions`, `message`, or `outbound` surface is not
65+
filled from another plugin with the same channel ID. Prepared delivery handlers
66+
created inside a registry scope retain that handle when invoked after the caller
67+
leaves the scope.
68+
6369
Declare live and finalizer capabilities precisely - core uses these to decide
6470
what a channel can do, and drift between the declared and actual behavior is a
6571
contract test failure:
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import { resetPluginRuntimeStateForTest, setActivePluginRegistry } from "../../plugins/runtime.js";
3+
import { withPluginRuntimeRegistryScope } from "../../plugins/runtime/gateway-request-scope.js";
4+
import {
5+
createChannelTestPluginBase,
6+
createTestRegistry,
7+
} from "../../test-utils/channel-plugins.js";
8+
import { dispatchChannelMessageAction } from "./message-action-dispatch.js";
9+
10+
const receipt = { content: [{ type: "text" as const, text: "delivered" }], details: { ok: true } };
11+
12+
afterEach(() => resetPluginRuntimeStateForTest());
13+
14+
describe("message action registration ownership", () => {
15+
it.each([true, false])(
16+
"uses only the selected scoped action capability (present=%s)",
17+
async (present) => {
18+
const handleRootAction = vi.fn(async () => receipt);
19+
const handleScopedAction = vi.fn(async () => receipt);
20+
const base = createChannelTestPluginBase({ id: "scoped-delivery" });
21+
const root = { ...base, actions: { handleAction: handleRootAction } };
22+
const scoped = {
23+
...base,
24+
...(present ? { actions: { handleAction: handleScopedAction } } : {}),
25+
};
26+
setActivePluginRegistry(
27+
createTestRegistry([{ pluginId: "root", source: "root", origin: "bundled", plugin: root }]),
28+
);
29+
const registry = createTestRegistry([
30+
{ pluginId: "scoped", source: "scoped", origin: "config", plugin: scoped },
31+
]);
32+
33+
const result = await withPluginRuntimeRegistryScope(registry, () =>
34+
dispatchChannelMessageAction({
35+
cfg: {},
36+
channel: base.id,
37+
action: "send",
38+
params: { to: "recipient", message: "hello" },
39+
}),
40+
);
41+
42+
expect(result).toEqual(present ? receipt : null);
43+
expect(handleRootAction).not.toHaveBeenCalled();
44+
expect(handleScopedAction).toHaveBeenCalledTimes(present ? 1 : 0);
45+
},
46+
);
47+
it("keeps scoped channel read authority external beside a bundled same-id registration", async () => {
48+
const handleRootAction = vi.fn(async () => receipt);
49+
const handleScopedAction = vi.fn(async () => receipt);
50+
const base = createChannelTestPluginBase({ id: "scoped-delivery" });
51+
setActivePluginRegistry(
52+
createTestRegistry([
53+
{
54+
pluginId: "root",
55+
source: "root",
56+
origin: "bundled",
57+
plugin: {
58+
...base,
59+
actions: { providerOwnedReadGates: true, handleAction: handleRootAction },
60+
},
61+
},
62+
]),
63+
);
64+
const registry = createTestRegistry([
65+
{
66+
pluginId: "scoped",
67+
source: "scoped",
68+
origin: "config",
69+
plugin: {
70+
...base,
71+
actions: { providerOwnedReadGates: true, handleAction: handleScopedAction },
72+
},
73+
},
74+
]);
75+
const context = { cfg: {}, channel: base.id, action: "read", params: { to: "recipient" } };
76+
77+
await withPluginRuntimeRegistryScope(registry, async () => {
78+
await expect(
79+
dispatchChannelMessageAction({
80+
...context,
81+
conversationReadOrigin: "delegated",
82+
}),
83+
).rejects.toThrow("requires the exact current conversation and account");
84+
expect(handleScopedAction).not.toHaveBeenCalled();
85+
expect(handleRootAction).not.toHaveBeenCalled();
86+
87+
expect(
88+
await dispatchChannelMessageAction({
89+
...context,
90+
conversationReadOrigin: "direct-operator",
91+
}),
92+
).toBe(receipt);
93+
expect(
94+
await dispatchChannelMessageAction({
95+
...context,
96+
conversationReadOrigin: "delegated",
97+
accountId: "ops",
98+
requesterAccountId: "ops",
99+
toolContext: { currentChannelProvider: base.id, currentChannelId: "recipient" },
100+
}),
101+
).toBe(receipt);
102+
expect(handleScopedAction).toHaveBeenCalledTimes(2);
103+
expect(handleRootAction).not.toHaveBeenCalled();
104+
});
105+
});
106+
});

‎src/channels/plugins/registry-loaded.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,10 +144,13 @@ export function getLoadedChannelPluginForRead(id: ChannelId): ChannelPlugin | un
144144
/**
145145
* Returns the loaded channel registry entry by normalized plugin id.
146146
*/
147-
export function getLoadedChannelPluginEntryById(id: string): LoadedChannelPluginEntry | undefined {
147+
export function getLoadedChannelPluginEntryById(
148+
id: string,
149+
registry?: ActivePluginChannelRegistry,
150+
): LoadedChannelPluginEntry | undefined {
148151
const resolvedId = normalizeOptionalString(id) ?? "";
149152
if (!resolvedId) {
150153
return undefined;
151154
}
152-
return resolveChannelPlugins().entriesById.get(resolvedId);
155+
return resolveChannelPlugins(registry).entriesById.get(resolvedId);
153156
}

‎src/channels/plugins/registry.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@ import { afterEach, describe, expect, it, vi } from "vitest";
33
import { createEmptyPluginRegistry } from "../../plugins/registry-empty.js";
44
import type { PluginRegistry } from "../../plugins/registry.js";
55
import { resetPluginRuntimeStateForTest, setActivePluginRegistry } from "../../plugins/runtime.js";
6+
import { withPluginRuntimeRegistryScope } from "../../plugins/runtime/gateway-request-scope.js";
7+
import {
8+
createChannelTestPluginBase,
9+
createTestRegistry,
10+
} from "../../test-utils/channel-plugins.js";
611
import {
712
getChannelPlugin,
813
getLoadedChannelPlugin,
@@ -75,6 +80,47 @@ describe("listChannelPlugins", () => {
7580
});
7681
});
7782

83+
it("keeps the scoped channel implementation and its registration provenance together", () => {
84+
const root = createChannelTestPluginBase({ id: "fallback", label: "Root" });
85+
const scoped = createChannelTestPluginBase({ id: "fallback", label: "Scoped" });
86+
const resolveChannelRuntime = vi.fn();
87+
setActivePluginRegistry(
88+
createTestRegistry([{ pluginId: "root", plugin: root, origin: "bundled", source: "root" }]),
89+
);
90+
const registry = createEmptyPluginRegistry();
91+
registry.channels = [
92+
{
93+
pluginId: "scoped",
94+
plugin: scoped,
95+
origin: "config",
96+
source: "scoped",
97+
resolveChannelRuntime,
98+
},
99+
];
100+
101+
withPluginRuntimeRegistryScope(registry, () => {
102+
expect(resolveChannelPluginRegistration("fallback")).toEqual({
103+
plugin: scoped,
104+
origin: "config",
105+
resolveChannelRuntime,
106+
});
107+
expect(getChannelPlugin("fallback")).toBe(scoped);
108+
});
109+
expect(getChannelPlugin("fallback")).toBe(root);
110+
});
111+
112+
it("preserves unrelated root and bundled addressability inside an empty CLI handle", () => {
113+
const root = createChannelTestPluginBase({ id: "root-only" });
114+
setActivePluginRegistry(
115+
createTestRegistry([{ pluginId: "root-only", plugin: root, source: "root" }]),
116+
);
117+
118+
withPluginRuntimeRegistryScope(createEmptyPluginRegistry(), () => {
119+
expect(getChannelPlugin("root-only")).toBe(root);
120+
expect(resolveChannelPluginRegistration("fallback")?.origin).toBe("bundled");
121+
});
122+
});
123+
78124
it("keeps the first channel implementation and provenance when channel ids collide", () => {
79125
const registry = createEmptyPluginRegistry();
80126
const firstPlugin = {

‎src/channels/plugins/registry.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/** Active channel plugin registry with bundled fallback. */
22
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
3+
import { getPluginRuntimeGatewayRequestScope } from "../../plugins/runtime/gateway-request-scope.js";
34
import { normalizeAnyChannelId } from "../registry.js";
45
import { getBundledChannelPlugin } from "./bundled.js";
56
import {
@@ -44,7 +45,10 @@ export function resolveChannelPluginRegistration(id: ChannelId):
4445
}
4546
// Resolve implementation and provenance together. Loaded overrides win and
4647
// must never borrow bundled authority from the fallback with the same id.
47-
const loadedEntry = getLoadedChannelPluginEntryById(resolvedId);
48+
const scopedRegistry = getPluginRuntimeGatewayRequestScope()?.pluginRegistry;
49+
const loadedEntry =
50+
(scopedRegistry ? getLoadedChannelPluginEntryById(resolvedId, scopedRegistry) : undefined) ??
51+
getLoadedChannelPluginEntryById(resolvedId);
4852
if (loadedEntry) {
4953
const origin = normalizeOptionalString(loadedEntry.origin) ?? undefined;
5054
return {

‎src/infra/outbound/channel-bootstrap.runtime.test.ts‎

Lines changed: 125 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,14 @@ import { createEmptyPluginRegistry } from "../../plugins/registry-empty.js";
88
import {
99
getActivePluginRegistry,
1010
resetPluginRuntimeStateForTest,
11+
requireActivePluginRegistry,
1112
setActivePluginRegistry,
1213
} from "../../plugins/runtime.js";
14+
import { withPluginRuntimeRegistryScope } from "../../plugins/runtime/gateway-request-scope.js";
15+
import {
16+
createChannelTestPluginBase,
17+
createTestRegistry,
18+
} from "../../test-utils/channel-plugins.js";
1319

1420
const loaderMocks = vi.hoisted(() => ({
1521
loadPluginRegistryHandle: vi.fn(),
@@ -26,8 +32,11 @@ vi.mock("../../plugins/loader.js", () => ({
2632

2733
const { bootstrapOutboundChannelPlugin, resetOutboundChannelBootstrapStateForTests } =
2834
await import("./channel-bootstrap.runtime.js");
29-
const { resolveChannelOutboundDirectiveOptions, resolveOutboundDurableFinalDeliverySupport } =
30-
await import("./deliver-channel.js");
35+
const {
36+
createChannelHandler,
37+
resolveChannelOutboundDirectiveOptions,
38+
resolveOutboundDurableFinalDeliverySupport,
39+
} = await import("./deliver-channel.js");
3140
const { resolveChannelTargetForDelivery, resolveOutboundSessionRouteForDelivery } =
3241
await import("../../cron/isolated-agent/delivery-target.runtime.js");
3342

@@ -307,6 +316,52 @@ describe("bootstrapOutboundChannelPlugin", () => {
307316
expect(loaderMocks.loadPluginRegistryHandle).not.toHaveBeenCalled();
308317
});
309318

319+
it.each([false, true])(
320+
"activates the scoped setup shell without borrowing a same-id root sender (cached=%s)",
321+
(cached) => {
322+
const base = createChannelTestPluginBase({ id: "discord" });
323+
const root = {
324+
...base,
325+
...(!cached ? { outbound: { deliveryMode: "direct" as const, sendText: vi.fn() } } : {}),
326+
};
327+
const activated = {
328+
...base,
329+
outbound: { deliveryMode: "direct" as const, sendText: vi.fn() },
330+
};
331+
setActivePluginRegistry(
332+
createTestRegistry([{ pluginId: "root", source: "root", plugin: root }]),
333+
);
334+
const setupRegistry = createTestRegistry([
335+
{ pluginId: "selected", source: "setup", plugin: base },
336+
]);
337+
const runtimeRegistry = createTestRegistry([
338+
{ pluginId: "selected", source: "runtime", plugin: activated },
339+
]);
340+
if (cached) {
341+
const prior = createTestRegistry([
342+
{ pluginId: "root", source: "prior", plugin: activated },
343+
]);
344+
loaderMocks.loadPluginRegistryHandle.mockReturnValue(prior);
345+
expect(bootstrapOutboundChannelPlugin({ channel: "discord", cfg: discordConfig })).toBe(
346+
prior,
347+
);
348+
loaderMocks.loadPluginRegistryHandle.mockClear();
349+
}
350+
loaderMocks.loadPluginRegistryHandle.mockReturnValue(runtimeRegistry);
351+
352+
expect(
353+
withPluginRuntimeRegistryScope(setupRegistry, () =>
354+
bootstrapOutboundChannelPlugin({
355+
channel: "discord",
356+
cfg: discordConfig,
357+
}),
358+
),
359+
).toBe(runtimeRegistry);
360+
expect(loaderMocks.loadPluginRegistryHandle).toHaveBeenCalledOnce();
361+
expect(getActivePluginRegistry()?.channels[0]?.plugin).toBe(root);
362+
},
363+
);
364+
310365
it("returns a scoped handle without replacing the process root", () => {
311366
installDiscordSetupShell();
312367
const root = getActivePluginRegistry();
@@ -361,6 +416,74 @@ describe("bootstrapOutboundChannelPlugin", () => {
361416
).resolves.toEqual({ ok: true, automaticUnknownSendReconciliation: false });
362417
});
363418

419+
it.each(["outbound", "message"] as const)(
420+
"retains the scoped %s transport and its durable capabilities through delivery",
421+
async (transport) => {
422+
const base = createChannelTestPluginBase({ id: "discord" });
423+
const rootSend = vi.fn(async () => ({ channel: "discord", messageId: "root" }));
424+
const sendRegistries: ReturnType<typeof requireActivePluginRegistry>[] = [];
425+
const scopedSend = vi.fn(async () => {
426+
sendRegistries.push(requireActivePluginRegistry());
427+
return { channel: "discord", messageId: "scoped" };
428+
});
429+
const message = (send: typeof rootSend, id: string) => ({
430+
send: {
431+
text: async () => {
432+
await send();
433+
return {
434+
receipt: {
435+
primaryPlatformMessageId: id,
436+
platformMessageIds: [id],
437+
sentAt: 1,
438+
parts: [{ platformMessageId: id, kind: "text" as const, index: 0 }],
439+
},
440+
};
441+
},
442+
},
443+
});
444+
const root = {
445+
...base,
446+
outbound: { deliveryMode: "direct" as const, sendText: rootSend },
447+
message: {
448+
...message(rootSend, "root"),
449+
durableFinal: { capabilities: { text: true, silent: true } },
450+
},
451+
};
452+
const scoped = {
453+
...base,
454+
...(transport === "outbound"
455+
? { outbound: { deliveryMode: "direct" as const, sendText: scopedSend } }
456+
: { message: message(scopedSend, "scoped") }),
457+
};
458+
setActivePluginRegistry(
459+
createTestRegistry([{ pluginId: "root", source: "root", plugin: root }]),
460+
);
461+
const registry = createTestRegistry([
462+
{ pluginId: "scoped", source: "scoped", plugin: scoped },
463+
]);
464+
465+
const handler = await withPluginRuntimeRegistryScope(registry, async () => {
466+
await expect(
467+
resolveOutboundDurableFinalDeliverySupport({
468+
cfg: discordConfig,
469+
channel: "discord",
470+
requirements: { silent: true },
471+
}),
472+
).resolves.toEqual({ ok: false, reason: "capability_mismatch", capability: "silent" });
473+
return await createChannelHandler({
474+
cfg: discordConfig,
475+
channel: "discord",
476+
to: "recipient",
477+
});
478+
});
479+
await expect(handler.sendText("hello")).resolves.toMatchObject({ messageId: "scoped" });
480+
expect(sendRegistries).toEqual([registry]);
481+
expect(scopedSend).toHaveBeenCalledOnce();
482+
expect(rootSend).not.toHaveBeenCalled();
483+
expect(loaderMocks.loadPluginRegistryHandle).not.toHaveBeenCalled();
484+
},
485+
);
486+
364487
it("does not retry an unusable handle in the same generation", () => {
365488
installDiscordSetupShell();
366489
loaderMocks.loadPluginRegistryHandle.mockReturnValue(createEmptyPluginRegistry());

0 commit comments

Comments
 (0)