fix(tui): accept canonical session-key aliases in chat event routing

This commit is contained in:
Vignesh Natarajan
2026-03-05 22:00:54 -08:00
parent 0e2bc588c4
commit 726ef48c2a
3 changed files with 64 additions and 1 deletions

View File

@@ -193,6 +193,44 @@ describe("tui-event-handlers: handleAgentEvent", () => {
expect(chatLog.startTool).toHaveBeenCalledWith("tc1", "exec", undefined);
});
it("accepts chat events when session key is an alias of the active canonical key", () => {
const { state, chatLog, handleChatEvent } = createHandlersHarness({
state: {
currentSessionKey: "agent:main:main",
activeChatRunId: null,
},
});
handleChatEvent({
runId: "run-alias",
sessionKey: "main",
state: "delta",
message: { content: "hello" },
});
expect(state.activeChatRunId).toBe("run-alias");
expect(chatLog.updateAssistant).toHaveBeenCalledWith("hello", "run-alias");
});
it("does not cross-match canonical session keys from different agents", () => {
const { chatLog, handleChatEvent } = createHandlersHarness({
state: {
currentAgentId: "alpha",
currentSessionKey: "agent:alpha:main",
activeChatRunId: null,
},
});
handleChatEvent({
runId: "run-other-agent",
sessionKey: "agent:beta:main",
state: "delta",
message: { content: "should be ignored" },
});
expect(chatLog.updateAssistant).not.toHaveBeenCalled();
});
it("clears run mapping when the session changes", () => {
const { state, chatLog, tui, handleChatEvent, handleAgentEvent } = createHandlersHarness({
state: { activeChatRunId: null },

View File

@@ -1,3 +1,4 @@
import { parseAgentSessionKey } from "../sessions/session-key-utils.js";
import { asString, extractTextFromMessage, isCommandMessage } from "./tui-formatters.js";
import { TuiStreamAssembler } from "./tui-stream-assembler.js";
import type { AgentEvent, ChatEvent, TuiStateAccess } from "./tui-types.js";
@@ -146,13 +147,36 @@ export function createEventHandlers(context: EventHandlerContext) {
void loadHistory?.();
};
const isSameSessionKey = (left: string | undefined, right: string | undefined): boolean => {
const normalizedLeft = (left ?? "").trim().toLowerCase();
const normalizedRight = (right ?? "").trim().toLowerCase();
if (!normalizedLeft || !normalizedRight) {
return false;
}
if (normalizedLeft === normalizedRight) {
return true;
}
const parsedLeft = parseAgentSessionKey(normalizedLeft);
const parsedRight = parseAgentSessionKey(normalizedRight);
if (parsedLeft && parsedRight) {
return parsedLeft.agentId === parsedRight.agentId && parsedLeft.rest === parsedRight.rest;
}
if (parsedLeft) {
return parsedLeft.rest === normalizedRight;
}
if (parsedRight) {
return normalizedLeft === parsedRight.rest;
}
return false;
};
const handleChatEvent = (payload: unknown) => {
if (!payload || typeof payload !== "object") {
return;
}
const evt = payload as ChatEvent;
syncSessionKey();
if (evt.sessionKey !== state.currentSessionKey) {
if (!isSameSessionKey(evt.sessionKey, state.currentSessionKey)) {
return;
}
if (finalizedRuns.has(evt.runId)) {