mirror of
https://github.com/openclaw/openclaw.git
synced 2026-05-14 08:18:34 +00:00
refactor: unify outbound session context wiring
This commit is contained in:
@@ -31,6 +31,9 @@ const queueMocks = vi.hoisted(() => ({
|
||||
ackDelivery: vi.fn(async () => {}),
|
||||
failDelivery: vi.fn(async () => {}),
|
||||
}));
|
||||
const logMocks = vi.hoisted(() => ({
|
||||
warn: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../config/sessions.js", async () => {
|
||||
const actual = await vi.importActual<typeof import("../../config/sessions.js")>(
|
||||
@@ -53,6 +56,18 @@ vi.mock("./delivery-queue.js", () => ({
|
||||
ackDelivery: queueMocks.ackDelivery,
|
||||
failDelivery: queueMocks.failDelivery,
|
||||
}));
|
||||
vi.mock("../../logging/subsystem.js", () => ({
|
||||
createSubsystemLogger: () => {
|
||||
const makeLogger = () => ({
|
||||
warn: logMocks.warn,
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
child: vi.fn(() => makeLogger()),
|
||||
});
|
||||
return makeLogger();
|
||||
},
|
||||
}));
|
||||
|
||||
const { deliverOutboundPayloads, normalizeOutboundPayloads } = await import("./deliver.js");
|
||||
|
||||
@@ -117,6 +132,7 @@ describe("deliverOutboundPayloads", () => {
|
||||
queueMocks.ackDelivery.mockResolvedValue(undefined);
|
||||
queueMocks.failDelivery.mockClear();
|
||||
queueMocks.failDelivery.mockResolvedValue(undefined);
|
||||
logMocks.warn.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -188,7 +204,7 @@ describe("deliverOutboundPayloads", () => {
|
||||
cfg: telegramChunkConfig,
|
||||
channel: "telegram",
|
||||
to: "123",
|
||||
agentId: "work",
|
||||
session: { agentId: "work" },
|
||||
payloads: [{ text: "hi", mediaUrl: "file:///tmp/f.png" }],
|
||||
deps: { sendTelegram },
|
||||
});
|
||||
@@ -583,7 +599,7 @@ describe("deliverOutboundPayloads", () => {
|
||||
to: "+1555",
|
||||
payloads: [{ text: "hello" }],
|
||||
deps: { sendWhatsApp },
|
||||
sessionKey: "agent:main:main",
|
||||
session: { key: "agent:main:main" },
|
||||
});
|
||||
|
||||
expect(internalHookMocks.createInternalHookEvent).toHaveBeenCalledTimes(1);
|
||||
@@ -603,6 +619,25 @@ describe("deliverOutboundPayloads", () => {
|
||||
expect(internalHookMocks.triggerInternalHook).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("warns when session.agentId is set without a session key", async () => {
|
||||
const sendWhatsApp = vi.fn().mockResolvedValue({ messageId: "w1", toJid: "jid" });
|
||||
hookMocks.runner.hasHooks.mockReturnValue(true);
|
||||
|
||||
await deliverOutboundPayloads({
|
||||
cfg: whatsappChunkConfig,
|
||||
channel: "whatsapp",
|
||||
to: "+1555",
|
||||
payloads: [{ text: "hello" }],
|
||||
deps: { sendWhatsApp },
|
||||
session: { agentId: "agent-main" },
|
||||
});
|
||||
|
||||
expect(logMocks.warn).toHaveBeenCalledWith(
|
||||
"deliverOutboundPayloads: session.agentId present without session key; internal message:sent hook will be skipped",
|
||||
expect.objectContaining({ channel: "whatsapp", to: "+1555", agentId: "agent-main" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("calls failDelivery instead of ackDelivery on bestEffort partial failure", async () => {
|
||||
const sendWhatsApp = vi
|
||||
.fn()
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
import type { sendMessageDiscord } from "../../discord/send.js";
|
||||
import { createInternalHookEvent, triggerInternalHook } from "../../hooks/internal-hooks.js";
|
||||
import type { sendMessageIMessage } from "../../imessage/send.js";
|
||||
import { createSubsystemLogger } from "../../logging/subsystem.js";
|
||||
import { getAgentScopedMediaLocalRoots } from "../../media/local-roots.js";
|
||||
import { getGlobalHookRunner } from "../../plugins/hook-runner-global.js";
|
||||
import { markdownToSignalTextChunks, type SignalTextStyleRange } from "../../signal/format.js";
|
||||
@@ -32,11 +33,14 @@ import { ackDelivery, enqueueDelivery, failDelivery } from "./delivery-queue.js"
|
||||
import type { OutboundIdentity } from "./identity.js";
|
||||
import type { NormalizedOutboundPayload } from "./payloads.js";
|
||||
import { normalizeReplyPayloadsForDelivery } from "./payloads.js";
|
||||
import type { OutboundSessionContext } from "./session-context.js";
|
||||
import type { OutboundChannel } from "./targets.js";
|
||||
|
||||
export type { NormalizedOutboundPayload } from "./payloads.js";
|
||||
export { normalizeOutboundPayloads } from "./payloads.js";
|
||||
|
||||
const log = createSubsystemLogger("outbound/deliver");
|
||||
|
||||
type SendMatrixMessage = (
|
||||
to: string,
|
||||
text: string,
|
||||
@@ -207,8 +211,8 @@ type DeliverOutboundPayloadsCoreParams = {
|
||||
bestEffort?: boolean;
|
||||
onError?: (err: unknown, payload: NormalizedOutboundPayload) => void;
|
||||
onPayload?: (payload: NormalizedOutboundPayload) => void;
|
||||
/** Active agent id for media local-root scoping. */
|
||||
agentId?: string;
|
||||
/** Session/agent context used for hooks and media local-root scoping. */
|
||||
session?: OutboundSessionContext;
|
||||
mirror?: {
|
||||
sessionKey: string;
|
||||
agentId?: string;
|
||||
@@ -216,8 +220,6 @@ type DeliverOutboundPayloadsCoreParams = {
|
||||
mediaUrls?: string[];
|
||||
};
|
||||
silent?: boolean;
|
||||
/** Session key for internal hook dispatch (when `mirror` is not needed). */
|
||||
sessionKey?: string;
|
||||
};
|
||||
|
||||
type DeliverOutboundPayloadsParams = DeliverOutboundPayloadsCoreParams & {
|
||||
@@ -296,7 +298,7 @@ async function deliverOutboundPayloadsCore(
|
||||
const sendSignal = params.deps?.sendSignal ?? sendMessageSignal;
|
||||
const mediaLocalRoots = getAgentScopedMediaLocalRoots(
|
||||
cfg,
|
||||
params.agentId ?? params.mirror?.agentId,
|
||||
params.session?.agentId ?? params.mirror?.agentId,
|
||||
);
|
||||
const results: OutboundDeliveryResult[] = [];
|
||||
const handler = await createChannelHandler({
|
||||
@@ -446,7 +448,21 @@ async function deliverOutboundPayloadsCore(
|
||||
return normalized ? [normalized] : [];
|
||||
});
|
||||
const hookRunner = getGlobalHookRunner();
|
||||
const sessionKeyForInternalHooks = params.mirror?.sessionKey ?? params.sessionKey;
|
||||
const sessionKeyForInternalHooks = params.mirror?.sessionKey ?? params.session?.key;
|
||||
if (
|
||||
hookRunner?.hasHooks("message_sent") &&
|
||||
params.session?.agentId &&
|
||||
!sessionKeyForInternalHooks
|
||||
) {
|
||||
log.warn(
|
||||
"deliverOutboundPayloads: session.agentId present without session key; internal message:sent hook will be skipped",
|
||||
{
|
||||
channel,
|
||||
to,
|
||||
agentId: params.session.agentId,
|
||||
},
|
||||
);
|
||||
}
|
||||
for (const payload of normalizedPayloads) {
|
||||
const payloadSummary: NormalizedOutboundPayload = {
|
||||
text: payload.text ?? "",
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
type OutboundSendDeps,
|
||||
} from "./deliver.js";
|
||||
import { normalizeReplyPayloadsForDelivery } from "./payloads.js";
|
||||
import { buildOutboundSessionContext } from "./session-context.js";
|
||||
import { resolveOutboundTarget } from "./targets.js";
|
||||
|
||||
export type MessageGatewayOptions = {
|
||||
@@ -212,11 +213,16 @@ export async function sendMessage(params: MessageSendParams): Promise<MessageSen
|
||||
throw resolvedTarget.error;
|
||||
}
|
||||
|
||||
const outboundSession = buildOutboundSessionContext({
|
||||
cfg,
|
||||
agentId: params.agentId,
|
||||
sessionKey: params.mirror?.sessionKey,
|
||||
});
|
||||
const results = await deliverOutboundPayloads({
|
||||
cfg,
|
||||
channel: outboundChannel,
|
||||
to: resolvedTarget.to,
|
||||
agentId: params.agentId,
|
||||
session: outboundSession,
|
||||
accountId: params.accountId,
|
||||
payloads: normalizedPayloads,
|
||||
replyToId: params.replyToId,
|
||||
@@ -233,7 +239,6 @@ export async function sendMessage(params: MessageSendParams): Promise<MessageSen
|
||||
mediaUrls: mirrorMediaUrls.length ? mirrorMediaUrls : undefined,
|
||||
}
|
||||
: undefined,
|
||||
sessionKey: params.mirror?.sessionKey,
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
37
src/infra/outbound/session-context.ts
Normal file
37
src/infra/outbound/session-context.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { resolveSessionAgentId } from "../../agents/agent-scope.js";
|
||||
import type { OpenClawConfig } from "../../config/config.js";
|
||||
|
||||
export type OutboundSessionContext = {
|
||||
/** Canonical session key used for internal hook dispatch. */
|
||||
key?: string;
|
||||
/** Active agent id used for workspace-scoped media roots. */
|
||||
agentId?: string;
|
||||
};
|
||||
|
||||
function normalizeOptionalString(value?: string | null): string | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
export function buildOutboundSessionContext(params: {
|
||||
cfg: OpenClawConfig;
|
||||
sessionKey?: string | null;
|
||||
agentId?: string | null;
|
||||
}): OutboundSessionContext | undefined {
|
||||
const key = normalizeOptionalString(params.sessionKey);
|
||||
const explicitAgentId = normalizeOptionalString(params.agentId);
|
||||
const derivedAgentId = key
|
||||
? resolveSessionAgentId({ sessionKey: key, config: params.cfg })
|
||||
: undefined;
|
||||
const agentId = explicitAgentId ?? derivedAgentId;
|
||||
if (!key && !agentId) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
...(key ? { key } : {}),
|
||||
...(agentId ? { agentId } : {}),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user