Skip to content

Commit 4a2b910

Browse files
fix(agents): preserve direct-message sender identity (#124548)
Preserve admitted external direct-message sender metadata at the transcript boundary so Control UI can show the contact label while gateway-local and from-me turns stay attributed to the operator. Co-authored-by: SunnyShu0925 <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 32f980d commit 4a2b910

9 files changed

Lines changed: 135 additions & 27 deletions

File tree

‎extensions/imessage/src/monitor/inbound-processing.test.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -786,7 +786,7 @@ describe("resolveIMessageReactionContext", () => {
786786
});
787787

788788
describe("buildIMessageInboundContext", () => {
789-
it("keeps numeric row id and provider GUID separately for action tooling", async () => {
789+
it("keeps provider IDs separate and projects from-me identity", async () => {
790790
const message = {
791791
id: 12345,
792792
guid: "p:0/GUID-current",
@@ -801,18 +801,23 @@ describe("buildIMessageInboundContext", () => {
801801
return;
802802
}
803803

804-
const { ctxPayload } = await buildIMessageInboundContext({
804+
const contextParams = {
805805
cfg: {} as OpenClawConfig,
806806
accountService: undefined,
807807
decision,
808-
message,
809808
historyLimit: 0,
810809
groupHistories: new Map(),
811-
});
810+
} satisfies Omit<Parameters<typeof buildIMessageInboundContext>[0], "message">;
811+
const { ctxPayload } = await buildIMessageInboundContext({ ...contextParams, message });
812812

813813
expect(ctxPayload.MessageSid).toMatch(/^\d+$/u);
814814
expect(ctxPayload.MessageSid).not.toBe("12345");
815815
expect(ctxPayload.MessageSidFull).toBe("p:0/GUID-current");
816+
const selfContext = await buildIMessageInboundContext({
817+
...contextParams,
818+
message: { ...message, is_from_me: true },
819+
});
820+
expect(selfContext.ctxPayload.SenderIsSelf).toBe(true);
816821
});
817822

818823
it("keeps generated media notices out of command input", async () => {

‎extensions/imessage/src/monitor/inbound-processing.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1034,6 +1034,7 @@ export async function buildIMessageInboundContext(params: {
10341034
sender: {
10351035
id: decision.sender,
10361036
name: decision.senderNormalized,
1037+
isSelf: params.message.is_from_me === true,
10371038
},
10381039
conversation: {
10391040
kind: decision.isGroup ? "group" : "direct",

‎extensions/whatsapp/src/auto-reply/monitor/inbound-dispatch.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,21 @@ function groupAdmission(conversationId: string): TestAdmissionOverride {
284284
}
285285

286286
describe("prepared WhatsApp inbound boundary", () => {
287+
it("projects from-me messages as the operator's own sender identity", async () => {
288+
const prepared = await prepareWhatsAppInboundContext({
289+
combinedBody: "hello from me",
290+
msg: makeMsg({ platform: { fromMe: true } }),
291+
route: makeRoute(),
292+
sender: { id: "+15550001111", name: "Operator" },
293+
});
294+
295+
expect(prepared.inbound.sender.isSelf).toBe(true);
296+
expect(prepared.ctxPayload).toMatchObject({
297+
SenderId: "+15550001111",
298+
SenderIsSelf: true,
299+
});
300+
});
301+
287302
it("separates portable facts from WhatsApp transport callbacks", async () => {
288303
const msg = makeMsg({
289304
event: { id: "current-1", timestamp: 1_710_000_000 },

‎extensions/whatsapp/src/auto-reply/monitor/inbound-dispatch.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,7 @@ export async function prepareWhatsAppInboundContext(params: {
476476
sender: {
477477
id: params.sender.id ?? params.sender.e164,
478478
name: params.sender.name,
479+
isSelf: params.msg.platform.fromMe === true,
479480
},
480481
conversation: {
481482
kind: conversationKind,

‎src/auto-reply/reply/get-reply-run-execute.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,14 @@ export async function executePreparedReplyRun(state: PreparedReplyRunAdmission)
210210
})
211211
: undefined);
212212
setChannelSourceTurnId(sessionCtx, sourceTurnId);
213-
const persistGroupSender = replyRoute.chatType === "group" || replyRoute.chatType === "channel";
213+
// Direct sender identity is safe only after channel admission and an ingress-owned
214+
// self check. Gateway-local and from-me turns must keep the operator identity.
215+
const persistChannelSender =
216+
replyRoute.chatType === "group" ||
217+
replyRoute.chatType === "channel" ||
218+
(replyRoute.chatType === "direct" &&
219+
ctx.InboundAccessAuthorized === true &&
220+
ctx.SenderIsSelf !== true);
214221
const ctxMediaForPersistence = normalizeMediaFacts(ctx.media);
215222
const unresolvedSourceIndexes = new Set(currentTurnImages.unresolvedSourceIndexes ?? []);
216223
const persistedCtxMedia = ctxMediaForPersistence.map((fact, index) =>
@@ -302,8 +309,7 @@ export async function executePreparedReplyRun(state: PreparedReplyRunAdmission)
302309
// is identical whether this turn is sent as the current turn or
303310
// replayed as history. See: https://github.com/openclaw/openclaw/issues/3658
304311
...(userTurnTimestamp ? { timestamp: userTurnTimestamp } : {}),
305-
// Direct transcripts keep their existing identity-storage boundary.
306-
sender: persistGroupSender
312+
sender: persistChannelSender
307313
? {
308314
id: normalizeOptionalString(sessionCtx.SenderId),
309315
name: normalizeOptionalString(sessionCtx.SenderName),

‎src/auto-reply/reply/get-reply-run.media-only.test.ts‎

Lines changed: 84 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1760,49 +1760,113 @@ describe("runPreparedReply media-only handling", () => {
17601760
});
17611761

17621762
it.each([
1763-
["group", true],
1764-
["channel", true],
1765-
["direct", false],
1766-
] as const)("persists sender attribution for %s turns only", async (chatType, shouldPersist) => {
1763+
["group", false],
1764+
["channel", false],
1765+
["direct", true],
1766+
] as const)(
1767+
"persists sender attribution for %s turns from external contacts",
1768+
async (chatType, requiresChannelAdmission) => {
1769+
await runPrepared({
1770+
ctx: {
1771+
...createInboundBody("hello"),
1772+
OriginatingChannel: "telegram",
1773+
OriginatingTo: "chat-1",
1774+
ChatType: chatType,
1775+
...(requiresChannelAdmission ? { InboundAccessAuthorized: true } : {}),
1776+
},
1777+
sessionCtx: {
1778+
...createSessionBody("hello"),
1779+
Provider: "telegram",
1780+
OriginatingChannel: "telegram",
1781+
OriginatingTo: "chat-1",
1782+
ChatType: chatType,
1783+
SenderId: "user-42",
1784+
SenderName: "Ada",
1785+
SenderUsername: "ada",
1786+
},
1787+
sessionEntry: {
1788+
sessionId: "session-1",
1789+
updatedAt: 1,
1790+
chatType,
1791+
channel: "telegram",
1792+
} as SessionEntry,
1793+
});
1794+
1795+
const message = requireRunReplyAgentCall().followupRun.userTurnTranscriptRecorder?.message;
1796+
expect(message).toMatchObject({
1797+
__openclaw: {
1798+
senderId: "user-42",
1799+
senderName: "Ada",
1800+
senderUsername: "ada",
1801+
},
1802+
});
1803+
},
1804+
);
1805+
1806+
it("does not persist sender attribution for operator-authored direct turns", async () => {
17671807
await runPrepared({
17681808
ctx: {
17691809
...createInboundBody("hello"),
17701810
OriginatingChannel: "telegram",
17711811
OriginatingTo: "chat-1",
1772-
ChatType: chatType,
1812+
ChatType: "direct",
1813+
InboundAccessAuthorized: true,
1814+
SenderIsSelf: true,
17731815
},
17741816
sessionCtx: {
17751817
...createSessionBody("hello"),
17761818
Provider: "telegram",
17771819
OriginatingChannel: "telegram",
17781820
OriginatingTo: "chat-1",
1779-
ChatType: chatType,
1821+
ChatType: "direct",
17801822
SenderId: "user-42",
17811823
SenderName: "Ada",
17821824
SenderUsername: "ada",
17831825
},
17841826
sessionEntry: {
17851827
sessionId: "session-1",
17861828
updatedAt: 1,
1787-
chatType,
1829+
chatType: "direct",
17881830
channel: "telegram",
17891831
} as SessionEntry,
17901832
});
17911833

17921834
const message = requireRunReplyAgentCall().followupRun.userTurnTranscriptRecorder?.message;
1793-
if (shouldPersist) {
1794-
expect(message).toMatchObject({
1795-
__openclaw: {
1796-
senderId: "user-42",
1797-
senderName: "Ada",
1798-
senderUsername: "ada",
1799-
},
1800-
});
1801-
} else {
1802-
expect(message).not.toHaveProperty("__openclaw.senderId");
1803-
expect(message).not.toHaveProperty("__openclaw.senderName");
1804-
expect(message).not.toHaveProperty("__openclaw.senderUsername");
1805-
}
1835+
expect(message).not.toHaveProperty("__openclaw.senderId");
1836+
expect(message).not.toHaveProperty("__openclaw.senderName");
1837+
expect(message).not.toHaveProperty("__openclaw.senderUsername");
1838+
});
1839+
1840+
it("does not persist sender attribution for gateway-local direct turns without channel admission", async () => {
1841+
await runPrepared({
1842+
ctx: {
1843+
...createInboundBody("hello"),
1844+
OriginatingChannel: "webchat",
1845+
OriginatingTo: "chat-1",
1846+
ChatType: "direct",
1847+
},
1848+
sessionCtx: {
1849+
...createSessionBody("hello"),
1850+
Provider: "webchat",
1851+
OriginatingChannel: "webchat",
1852+
OriginatingTo: "chat-1",
1853+
ChatType: "direct",
1854+
SenderId: "gateway-cli",
1855+
SenderName: "Gateway CLI",
1856+
SenderUsername: "cli",
1857+
},
1858+
sessionEntry: {
1859+
sessionId: "session-1",
1860+
updatedAt: 1,
1861+
chatType: "direct",
1862+
channel: "webchat",
1863+
} as SessionEntry,
1864+
});
1865+
1866+
const message = requireRunReplyAgentCall().followupRun.userTurnTranscriptRecorder?.message;
1867+
expect(message).not.toHaveProperty("__openclaw.senderId");
1868+
expect(message).not.toHaveProperty("__openclaw.senderName");
1869+
expect(message).not.toHaveProperty("__openclaw.senderUsername");
18061870
});
18071871

18081872
it("normalizes second-based inbound timestamps before preparing user turns", async () => {

‎src/auto-reply/templating.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,8 @@ export type MsgContext = Partial<CanonicalInboundText> & {
318318
SenderTag?: string;
319319
SenderE164?: string;
320320
SenderIsBot?: boolean;
321+
/** Channel-ingress fact: sender is the operator's own account (from-me). */
322+
SenderIsSelf?: boolean;
321323
Timestamp?: number;
322324
LocationLat?: number;
323325
LocationLon?: number;

‎src/channels/inbound-event/context.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ describe("buildChannelInboundEventContext", () => {
261261
SenderUsername: "userone",
262262
SenderTag: "User#0001",
263263
SenderIsBot: true,
264+
SenderIsSelf: undefined,
264265
MemberRoleIds: ["admin"],
265266
Timestamp: 123,
266267
Provider: "test-provider",
@@ -311,6 +312,18 @@ describe("buildChannelInboundEventContext", () => {
311312
expect(ctx.BodyForAgent).not.toContain("customSenderField");
312313
});
313314

315+
it("projects the ingress from-me sender fact as SenderIsSelf", () => {
316+
const ctx = buildTestInboundEventContext({
317+
sender: {
318+
id: "u1",
319+
name: "User One",
320+
isSelf: true,
321+
},
322+
});
323+
324+
expect(ctx.SenderIsSelf).toBe(true);
325+
});
326+
314327
it("uses resolved command authorization", async () => {
315328
const ctx = buildTestInboundEventContext({
316329
access: {

‎src/channels/inbound-event/context.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -563,6 +563,7 @@ function buildChannelInboundEventContextValue(
563563
SenderUsername: params.sender.username,
564564
SenderTag: params.sender.tag,
565565
SenderIsBot: params.sender.isBot,
566+
SenderIsSelf: params.sender.isSelf === true ? true : undefined,
566567
MemberRoleIds: params.sender.roles,
567568
Timestamp: params.timestamp,
568569
Provider: params.provider ?? params.channel,

0 commit comments

Comments
 (0)