diff --git a/backend/tests/domainClassifier.contextual.unit.test.js b/backend/tests/domainClassifier.contextual.unit.test.js new file mode 100644 index 00000000..3e5ec24e --- /dev/null +++ b/backend/tests/domainClassifier.contextual.unit.test.js @@ -0,0 +1,30 @@ +import { describe, it, expect } from "vitest"; +import { isContextualResponse } from "../utils/domainClassifier.js"; + +describe("isContextualResponse", () => { + const firstExchange = [ + { role: "user", text: "Help me prepare for an interview" }, + { role: "model", text: "Would you like to practice a question?" }, + ]; + + it("accepts a short reply when the previous assistant message ends the history", () => { + expect(isContextualResponse("yes", firstExchange)).toBe(true); + expect(isContextualResponse("yes", [{ role: "model", text: "Ready?" }])).toBe(true); + expect(isContextualResponse("continue", [ + ...firstExchange, + { role: "user", text: "Explain the answer" }, + { role: "model", text: "Should we try another?" }, + ])).toBe(true); + }); + + it("does not use an older assistant reply when history ends with a user message", () => { + expect(isContextualResponse("yes", [ + ...firstExchange, + { role: "user", text: "What is the weather?" }, + ])).toBe(false); + }); + + it("does not treat a reply as contextual with empty history", () => { + expect(isContextualResponse("yes", [])).toBe(false); + }); +}); diff --git a/backend/utils/domainClassifier.js b/backend/utils/domainClassifier.js index 976ed79e..510bdc1b 100644 --- a/backend/utils/domainClassifier.js +++ b/backend/utils/domainClassifier.js @@ -62,9 +62,9 @@ const isContextualResponse = (prompt, history) => { const trimmed = prompt.trim(); if (contextualRegex.test(trimmed)) { - // Only contextual if there's a previous assistant message - if (history && history.length > 1) { - const lastMessage = history[history.length - 2]; + // The current prompt is separate from history; its last entry must be the assistant. + if (history && history.length > 0) { + const lastMessage = history[history.length - 1]; if (lastMessage && lastMessage.role === "model") { return true; }