tui-turn-complete-fallback.test.ts 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import assert from "node:assert/strict";
  2. import test from "node:test";
  3. import type React from "react";
  4. import { applyTurnCompleteFallbackResponse } from "../src/app-turn-complete.js";
  5. import { appendAgentResult } from "../src/app-submit.js";
  6. import type { Message } from "../src/app-model.js";
  7. // turn_complete 的 response 兜底:通知驱动的回合没有 applyResult,流式又可能一个字都没画
  8. // (只有工具调用、或流中途断掉)。这组测试钉住兜底的三条性质:该补时补、已画过不补、
  9. // 以及与 appendAgentResult 的守卫对称——同一段回答绝不出现两次。
  10. function dispatch(current: Message[], payload: Record<string, unknown>): Message[] {
  11. let next = current;
  12. const setMessages: React.Dispatch<React.SetStateAction<Message[]>> = (update) => {
  13. next = typeof update === "function" ? (update as (m: Message[]) => Message[])(next) : update;
  14. };
  15. applyTurnCompleteFallbackResponse(payload, setMessages);
  16. return next;
  17. }
  18. test("appends the authoritative response when nothing was streamed (tool-only turn)", () => {
  19. const result = dispatch([], { response: "Workflow settled: 3 findings." });
  20. assert.equal(result.length, 1);
  21. assert.equal(result[0]?.role, "agent");
  22. assert.equal(result[0]?.content, "Workflow settled: 3 findings.");
  23. });
  24. test("does not append when the streamed transcript already carries the response", () => {
  25. const streamed: Message = {
  26. content: "Workflow settled: 3 findings.",
  27. role: "agent",
  28. streamProjected: true,
  29. };
  30. const result = dispatch([streamed], { response: "Workflow settled: 3 findings." });
  31. assert.equal(result.length, 1);
  32. });
  33. test("empty or missing response is a no-op", () => {
  34. assert.equal(dispatch([], { response: "" }).length, 0);
  35. assert.equal(dispatch([], { response: " " }).length, 0);
  36. assert.equal(dispatch([], {}).length, 0);
  37. });
  38. test("re-delivery of the same response is idempotent", () => {
  39. const once = dispatch([], { response: "same answer" });
  40. const twice = dispatch(once, { response: "same answer" });
  41. assert.equal(twice.length, 1);
  42. });
  43. test("regression: fallback then applyResult must not duplicate the answer", () => {
  44. // 用户回合里流断掉的场景:turn_complete 先到(兜底补上),随后 submitPrompt 结算、
  45. // appendAgentResult 再跑。守卫只扫 streamProjected 消息,所以兜底消息必须自带该标记,
  46. // 否则这里会出现同一段回答的第二份。
  47. const afterFallback = dispatch([], { response: "the one answer" });
  48. const afterResult = appendAgentResult(afterFallback, { response: "the one answer" });
  49. const occurrences = afterResult.filter((m) => m.content === "the one answer");
  50. assert.equal(occurrences.length, 1);
  51. });