Skip to content

Commit 85fd4c9

Browse files
authored
fix(qa): preserve scoped native message and command identity (#119499)
1 parent 80da616 commit 85fd4c9

10 files changed

Lines changed: 422 additions & 64 deletions

‎extensions/qa-channel/src/inbound.test.ts‎

Lines changed: 33 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -469,32 +469,41 @@ describe("handleQaInbound", () => {
469469
expect(ctxPayload?.SenderId).toBe("alice");
470470
});
471471

472-
it("routes native commands through a separate slash session to the conversation session", async () => {
473-
const runtime = createPluginRuntimeMock();
474-
setQaChannelRuntime(runtime);
472+
it.each([
473+
{ name: "stop", text: "/stop" },
474+
{ name: "queue", text: "/queue Can you diagnose this?" },
475+
{ name: "think", text: "/think high" },
476+
])(
477+
"preserves the complete /$name native command in its slash session",
478+
async ({ name, text }) => {
479+
const runtime = createPluginRuntimeMock();
480+
setQaChannelRuntime(runtime);
475481

476-
await handleQaInbound(
477-
createQaInboundParams({
478-
message: {
479-
text: "/stop",
480-
nativeCommand: { name: "stop" },
481-
},
482-
}),
483-
);
482+
await handleQaInbound(
483+
createQaInboundParams({
484+
message: {
485+
text,
486+
nativeCommand: { name },
487+
},
488+
}),
489+
);
484490

485-
const assembled = firstRunAssembledParams(runtime);
486-
expect(assembled.ctxPayload).toMatchObject({
487-
CommandAuthorized: true,
488-
CommandSource: "native",
489-
CommandTargetSessionKey: assembled.route.sessionKey,
490-
CommandTurn: {
491-
body: "/stop",
492-
source: "native",
493-
},
494-
});
495-
expect(assembled.ctxPayload.SessionKey).toContain("qa-channel:slash:alice");
496-
expect(assembled.ctxPayload.SessionKey).not.toBe(assembled.route.sessionKey);
497-
});
491+
const assembled = firstRunAssembledParams(runtime);
492+
expect(assembled.ctxPayload).toMatchObject({
493+
BodyForCommands: text,
494+
CommandAuthorized: true,
495+
CommandBody: text,
496+
CommandSource: "native",
497+
CommandTargetSessionKey: assembled.route.sessionKey,
498+
CommandTurn: {
499+
body: text,
500+
source: "native",
501+
},
502+
});
503+
expect(assembled.ctxPayload.SessionKey).toContain("qa-channel:slash:alice");
504+
expect(assembled.ctxPayload.SessionKey).not.toBe(assembled.route.sessionKey);
505+
},
506+
);
498507

499508
it("skips malformed inline attachment base64 without dropping the message", async () => {
500509
const runtime = createPluginRuntimeMock();

‎extensions/qa-channel/src/inbound.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -356,8 +356,6 @@ export async function handleQaInbound(params: {
356356
targetSessionKey: route.sessionKey,
357357
})
358358
: undefined;
359-
const commandBody = nativeCommand ? `/${nativeCommand.name}` : inbound.text;
360-
361359
const sessionKey = commandTargets?.sessionKey ?? route.sessionKey;
362360
const ctxPayload = buildChannelInboundEventContext({
363361
channel: params.channelId,
@@ -392,14 +390,14 @@ export async function handleQaInbound(params: {
392390
messageThreadId: inbound.threadId,
393391
threadParentId: inbound.threadId ? inbound.conversation.id : undefined,
394392
},
395-
message: { body, bodyForAgent: inbound.text, rawBody: inbound.text, commandBody },
393+
message: { body, bodyForAgent: inbound.text, rawBody: inbound.text, commandBody: inbound.text },
396394
media,
397395
access: {
398396
commands: { authorized: true },
399397
mentions: { canDetectMention: isGroup, wasMentioned: Boolean(wasMentioned) },
400398
},
401399
command: nativeCommand
402-
? { kind: "native", name: nativeCommand.name, body: commandBody, authorized: true }
400+
? { kind: "native", name: nativeCommand.name, body: inbound.text, authorized: true }
403401
: undefined,
404402
extra: {
405403
CommandTargetSessionKey: commandTargets?.commandTargetSessionKey,

‎extensions/qa-lab/src/bus-queries.ts‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -92,11 +92,24 @@ export function requireQaBusMessageForAccount(params: {
9292
messages: Map<string, QaBusMessage>;
9393
input: Pick<QaBusReadMessageInput, "accountId" | "messageId">;
9494
}): QaBusMessage {
95-
const message = params.messages.get(params.input.messageId);
96-
if (!message || message.accountId !== normalizeAccountId(params.input.accountId)) {
95+
const accountId = normalizeAccountId(params.input.accountId);
96+
let match: QaBusMessage | undefined;
97+
for (const message of params.messages.values()) {
98+
if (message.id !== params.input.messageId || message.accountId !== accountId) {
99+
continue;
100+
}
101+
// Reads have no conversation selector, so never guess which chat to mutate.
102+
if (match) {
103+
throw new Error(
104+
`qa-bus message id is ambiguous for selected account: ${params.input.messageId}`,
105+
);
106+
}
107+
match = message;
108+
}
109+
if (!match) {
97110
throw new Error(`qa-bus message not found: ${params.input.messageId}`);
98111
}
99-
return message;
112+
return match;
100113
}
101114

102115
export function readQaBusMessage(params: {

‎extensions/qa-lab/src/bus-state.test.ts‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,129 @@ describe("qa-bus state", () => {
4646
expect(snapshot.messages.map((message) => message.id)).toEqual([inbound.id, outbound.id]);
4747
});
4848

49+
it("records provider-native inbound IDs before indexing and publishing messages", () => {
50+
const state = createQaBusState();
51+
const providerMessageId = "$provider-event:matrix.test";
52+
53+
const inbound = state.addInboundMessage(
54+
{
55+
conversation: { id: "qa-room", kind: "group" },
56+
senderId: "alice",
57+
text: "provider-native identity",
58+
},
59+
providerMessageId,
60+
);
61+
const snapshot = state.getSnapshot();
62+
63+
expect(inbound.id).toBe(providerMessageId);
64+
expect(snapshot.messages[0]?.id).toBe(providerMessageId);
65+
expect(snapshot.events[0]).toMatchObject({
66+
kind: "inbound-message",
67+
message: { id: providerMessageId },
68+
});
69+
expect(state.poll().events[0]).toMatchObject({
70+
kind: "inbound-message",
71+
message: { id: providerMessageId },
72+
});
73+
expect(state.readMessage({ messageId: providerMessageId })).toMatchObject({
74+
id: providerMessageId,
75+
text: "provider-native identity",
76+
});
77+
});
78+
79+
it("keeps identical provider-native message IDs isolated by account", () => {
80+
const state = createQaBusState();
81+
const messageId = "42";
82+
83+
for (const accountId of ["account-a", "account-b"]) {
84+
state.addInboundMessage(
85+
{
86+
accountId,
87+
conversation: { id: `${accountId}-room`, kind: "group" },
88+
senderId: accountId,
89+
text: `${accountId} original`,
90+
},
91+
messageId,
92+
);
93+
}
94+
95+
const snapshot = state.getSnapshot();
96+
expect(snapshot.messages.map((message) => [message.accountId, message.id])).toEqual([
97+
["account-a", messageId],
98+
["account-b", messageId],
99+
]);
100+
expect(snapshot.events.map((event) => event.accountId)).toEqual(["account-a", "account-b"]);
101+
102+
for (const accountId of ["account-a", "account-b"]) {
103+
expect(state.readMessage({ accountId, messageId })).toMatchObject({
104+
accountId,
105+
id: messageId,
106+
text: `${accountId} original`,
107+
});
108+
expect(state.searchMessages({ accountId })).toEqual([
109+
expect.objectContaining({ accountId, id: messageId }),
110+
]);
111+
expect(state.poll({ accountId }).events).toEqual([
112+
expect.objectContaining({ accountId, message: expect.objectContaining({ id: messageId }) }),
113+
]);
114+
}
115+
116+
state.editMessage({ accountId: "account-a", messageId, text: "account-a edited" });
117+
state.reactToMessage({ accountId: "account-b", messageId, emoji: "eyes" });
118+
expect(state.readMessage({ accountId: "account-a", messageId })).toMatchObject({
119+
text: "account-a edited",
120+
reactions: [],
121+
});
122+
expect(state.readMessage({ accountId: "account-b", messageId })).toMatchObject({
123+
text: "account-b original",
124+
reactions: [expect.objectContaining({ emoji: "eyes" })],
125+
});
126+
});
127+
128+
it("rejects ambiguous provider-native IDs instead of selecting the wrong conversation", () => {
129+
const state = createQaBusState();
130+
const accountId = "account-a";
131+
const messageId = "42";
132+
133+
for (const conversationId of ["first-room", "second-room"]) {
134+
state.addInboundMessage(
135+
{
136+
accountId,
137+
conversation: { id: conversationId, kind: "group" },
138+
senderId: "alice",
139+
text: `${conversationId} original`,
140+
},
141+
messageId,
142+
);
143+
}
144+
145+
const originalSnapshot = state.getSnapshot();
146+
expect(originalSnapshot.messages.map((message) => message.conversation.id)).toEqual([
147+
"first-room",
148+
"second-room",
149+
]);
150+
expect(originalSnapshot.events.map((event) => event.accountId)).toEqual([accountId, accountId]);
151+
for (const conversationId of ["first-room", "second-room"]) {
152+
expect(state.searchMessages({ accountId, conversationId })).toEqual([
153+
expect.objectContaining({
154+
id: messageId,
155+
conversation: expect.objectContaining({ id: conversationId }),
156+
}),
157+
]);
158+
}
159+
160+
const ambiguousMessage = "qa-bus message id is ambiguous for selected account: 42";
161+
expect(() => state.readMessage({ accountId, messageId })).toThrow(ambiguousMessage);
162+
expect(() => state.editMessage({ accountId, messageId, text: "wrong conversation" })).toThrow(
163+
ambiguousMessage,
164+
);
165+
expect(() => state.reactToMessage({ accountId, messageId, emoji: "eyes" })).toThrow(
166+
ambiguousMessage,
167+
);
168+
expect(() => state.deleteMessage({ accountId, messageId })).toThrow(ambiguousMessage);
169+
expect(state.getSnapshot()).toEqual(originalSnapshot);
170+
});
171+
49172
it("normalizes the dm ingress alias before channel routing", () => {
50173
const state = createQaBusState();
51174

‎extensions/qa-lab/src/bus-state.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ export function createQaBusState() {
135135
const createMessage = (params: {
136136
direction: QaBusMessage["direction"];
137137
accountId: string;
138+
messageId?: string;
138139
conversation: QaBusConversation;
139140
senderId: string;
140141
senderName?: string;
@@ -161,7 +162,8 @@ export function createQaBusState() {
161162
const storedConversation = ensureConversation(params.accountId, params.conversation);
162163
const toolCalls = sanitizeQaBusToolCalls(params.toolCalls);
163164
const message: QaBusMessage = {
164-
id: randomUUID(),
165+
// Adopt native identity before indexing or publishing any message clone.
166+
id: params.messageId ?? randomUUID(),
165167
accountId: params.accountId,
166168
direction: params.direction,
167169
conversation: {
@@ -181,7 +183,9 @@ export function createQaBusState() {
181183
...(toolCalls ? { toolCalls } : {}),
182184
reactions: [],
183185
};
184-
messages.set(message.id, message);
186+
// Provider IDs are conversation-local and must never replace another chat's message.
187+
const { accountId, conversation, id } = message;
188+
messages.set(JSON.stringify([accountId, conversation.kind, conversation.id, id]), message);
185189
return message;
186190
};
187191

@@ -204,11 +208,12 @@ export function createQaBusState() {
204208
events,
205209
});
206210
},
207-
addInboundMessage(input: QaBusInboundMessageInput) {
211+
addInboundMessage(input: QaBusInboundMessageInput, messageId?: string) {
208212
const accountId = normalizeAccountId(input.accountId);
209213
const message = createMessage({
210214
direction: "inbound",
211215
accountId,
216+
messageId,
212217
// `dm:` is the canonical target spelling and is also used by manual
213218
// QA-bus clients. Normalize its matching ingress alias before routing
214219
// so a DM can never silently acquire group/channel privacy semantics.

0 commit comments

Comments
 (0)